#discord-bots

1 messages · Page 335 of 1

pale zenith
#

I try to be patient with people shrug that only happens when they don't collaborate/don't put in some effort

graceful ermine
#

Hey how could I register this slash command to this guild ID? I have no errors but it's been 15 minutes and the slash commands aren't there

code:

#
@bot.tree.command(name="reload", description="Reloads a cogs", guild=discord.Object(1175954196567183450))
@app_commands.checks.has_role('AN | Owner')
async def reload(interaction: discord.Interaction, cog: str):
    
    time = datetime.datetime.now()
    
    if not cog:
        
        async with print("s"):
            embed =  discord.Embed(
                title="Reload all cogs",
                color= 0x00FF00,
                timestamp=time
            )
        
#
       for ext in os.listdir("./cogs/"):
            if ext.endswith(".py") and not ext.startswith("_"):
                try:
                    await bot.reload_extension(f"cogs.{ext[:-3]}")
                    
                    
                    embed.add_field(
                        name=f'Reloaded: `{ext}` :white_check_mark: ',
                        value='\uFEFF',
                        inline=False)
                    
                    
                except Exception as e:
                    embed.add_field(
                        name=f"failed to reload: `{ext}` :x:",
                        value=e,
                        inline=False
                    )
                    
        await asyncio.sleep(0.5)
        await interaction.response.send_message(embed=embed)
        return
        
    else:
        
        
        embed2 =  discord.Embed(
            title="Reloaded!",
            color= 0x00FF00,
            timestamp=time
        )
    
    ext = f"{cog.lower()}.py"
    if not os.path.exists(f"./cogs/{ext}"):
        
        embed2.add_field(
            name=f"failed to reload {ext}",
            value="This cog does not exist"
        )
    
    elif ext in os.listdir("./cogs"):
        if ext.endswith(".py") and not ext.startswith("_"):
            try:
                await bot.unload_extension(f"cogs.{ext[:-3]}")
                await bot.load_extension(f"cogs.{ext[:-3]}")
                
                
                embed2.add_field(
                    name=f"Reloaded: `{ext}` :white_check_mark:",
                    value='\uFeFF',
                    inline=False
                )
                
                
                
#
            except Exception as failed:
                trace = traceback.format_exc(limit=True)
                embed2.add_field(
                    name=f"Failed to reload: {ext} :x:",
                    value=trace,
                    inline=False
                )
    await asyncio.sleep(0.5)
    await interaction.response.send_message(embed=embed2)```
hushed galleon
#

!paste for long code snippets

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

hushed galleon
#

regardless, how did you try to sync the command?

graceful ermine
hushed galleon
#

did you call sync() with the same guild= that you wanted to sync it to?

sick birch
graceful ermine
# sick birch can you show us the code

@bot.event
async def on_ready():
    changepresence.start()
    bot.db = await aiosqlite.connect(database="Database/setup.db")
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS setup (guild INTEGER, ps_channel INTEGER, pm_role INTEGER, ps_request INTEGER)")
        await bot.db.commit()


    bot.db2 = await aiosqlite.connect(database="Database/ad.db")
    async with bot.db2.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS ad (guild INTEGER, ad STRING)")
        await bot.db2.commit()


    await bot.tree.sync()

    print(f"{bot.user} is now online!")

sick birch
graceful ermine
#

Okay thanks, make sense now

reef trail
#

Does anyone have a good math lib to use that doesnt use eval?

#

I plan to make a calculator command

sick birch
unkempt canyonBOT
#

ast.literal_eval(node_or_string)```
Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, `None` and `Ellipsis`.

This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
sick birch
#

should be safe and is built in

slate swan
#

Ok so I have a problem and I need help let me begin explaining

from .user import User
from .channel import Channel

# Message
class Message:

    # Initialization
    def __init__(self, message_data, http, client):
        self.http = http
        self.client = client
        channel_data = await self.client.get_channel(message_data.get('channel_id')
        self.channel = Channel(channel_data)
        self.id = message_data.get('id')
        self.pinned = message_data.get('pinned')
        self.author = User(message_data.get('author'))
        self.content = message_data.get('content')
        self.guild_id = message_data.get('guild_id')
        self.timestamp = message_data.get('timestamp')
        self.channel_id = message_data.get('channel_id')
        ```
this is what I want to achieve but I cannot put async stuff in `__init__ `and if I make an async function I cannot await it in `__init__` so i need help.
sick birch
slate swan
slate swan
#

well because I have a consistency in the code and i dont wanna break it by taking this 1 thing as an argument

#

self.client.get_channel is an async function

sick birch
#

that doesn't really change consistency

slate swan
#

idk but im looking for some better ways yk?

sick birch
slate swan
#

ight tysm @sick birch works

#

vouch robin helped me!

inland plover
#

hi i'am trying to make a bot that when u join a vc the time that u have spend will go to a google sheet but when i join a vc there is an error in the terminal that say {"error":"Bad data format"} and nothing appears in the gsheet as well

#

can someone help pls

pale zenith
#

also, consider using a database for this :) it's easier code-wise

#

although visually accessing the data may be a bit more tedious. but there are database browsing apps that make it look like excel

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

pale zenith
#

also, storing data in google sheets is against their terms of services and will get your google account terminated without prior warning. I've seen it happen

pale zenith
#

lol yeah

inland plover
pale zenith
#

it aint meant for that lmao

inland plover
pale zenith
#

but I do recall that being not allowed. but if you want to be sure, you should consult the terms of service yourself. I ain't no lawyer lamo

frail perch
#

Hey! I'm currently having trouble with a discord and wordpress integration. The plan is simple: bot asks user for their order id and then proceeds to act on it accordingly.

The error as of now is stupidly frustrating. The bot is unable to read any messages at all. It will print user names, but never the contents of their messages. Here's the code https://paste.pythondiscord.com/B7UA

sick birch
#
  intents = discord.Intents.default()
  intents.messages = True
  intents.guilds = True
+ intents.message_content = True
  bot = commands.Bot(command_prefix='!', intents=intents)
frail perch
#

Thankyou for such a fast response! I'll give it a go!

#

I'm baffeled. It reads contents now!! I appreachiate it. I guess chatgpt will only get you so far...

sick birch
#

you would be better served asking here

frail perch
#

Everything else was generated with the help of GPT so I'm guite suprised it missed this. Using GPT4. Will return here, when any seemingly impossible issues arise again 🥲

slate swan
#

i run my code but it just says
ModuleNotFoundError: No module named 'pip._internal.utils.temp_dir
I havent had an issue until today

feral timber
#

Are you using pip's internals in your code?

slate swan
graceful ermine
#

Hey, for some reason none of my other commands that are in a cog doesn't work except for slash commands that are synced to a specific guild. How can I fix this issue?


@bot.event
async def on_ready():
    changepresence.start()
    bot.db = await aiosqlite.connect(database="Database/setup.db")
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS setup (guild INTEGER, ps_channel INTEGER, pm_role INTEGER, ps_request INTEGER)")
        await bot.db.commit()


    bot.db2 = await aiosqlite.connect(database="Database/ad.db")
    async with bot.db2.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS ad (guild INTEGER, ad STRING)")
        await bot.db2.commit()


    await bot.tree.sync(guild=discord.Object(1175954196567183450))
    await bot.load_extension("cogs.partner")
    await bot.load_extension(f"cogs.setup")
    await bot.tree.sync()

    print(f"{bot.user} is now online!")



@bot.tree.command(name="sync", description="sync a command", guild=discord.Object(id=1175954196567183450))
@app_commands.checks.has_role('AN | Owner')
async def sync(interaction: discord.Interaction):
    await bot.tree.sync()




pale zenith
#

because you look to be
1- syncing
2- loading cogs

#

3- syincing global

graceful ermine
sick birch
pale zenith
#

also, you shouldn't really do any of this within on_ready

#

since it can trigger many times during your bot's lifetime. Matter of fact, you should only sync manually through a sync command, rather than automatically

graceful ermine
slate swan
hushed galleon
sturdy fractal
#
    @commands.Cog.listener()
    async def on_message(self, message):
        # Check if the message is from Sofi and contains the card drop indication
        if self.sofi_id == message.author.id and "is dropping cards" in message.content:
            user_id = message.author.id

            if user_id not in self.drop_counts:
                self.drop_counts[user_id] = 1
            else:
                self.drop_counts[user_id] += 1

            user = self.bot.get_user(user_id)
            if user:
                await message.channel.send(f"Successfully counted a drop for {user.name}!")
        
        await self.bot.process_commands(message)
#

this code doesnt work whats wrong?

fickle aurora
sturdy fractal
fickle aurora
#

though it is weird that no errors are shown

#

maybe your self.sofi_id is incorrect

sturdy fractal
#

no i cross checked it

fickle aurora
#

well make sure you are sending messages in the channel that your bot is in and that your message actually contains "is dropping cards", it also has to be lowercase

fickle aurora
#
from collections import Counter

...

    self.drop_counts: Counter[int] = Counter()

...

    self.drop_counts[user_id] += 1  # without checking if it's in or not
sturdy fractal
fickle aurora
vapid parcel
#

Would Emoji Steal be against ToS?

#

I just wanna know lol

sturdy fractal
#

like u wanna use a server emoji outside of discord?

#

whatsapp , telegram?

vapid parcel
#

No, where you use a command from a bot, it sends a download link to that emoji.

#

where you can just download it

#

I added it to my bot either way, but if you still didn't understand, this is what it does basically.

#

I mean I doubt its against ToS because other bots do it, plus you can do it yourself so I highly doubt its against any rule.

sturdy fractal
sturdy fractal
#

good feature btw

vapid parcel
sturdy fractal
#

u can add thoes emoji to other platforms if u want

vapid parcel
#

Yeah or to your own server if you wanted

#

And the bot doesn't even need to be in the server for the emoji.

#

it just goes off the url then sends the url, which you can copy the url of any emoji with your own acc. But some people don't know that some how lol

sturdy fractal
#

lmao

#

great

vapid parcel
sturdy fractal
vapid parcel
#

Ye

sturdy fractal
#

sure dm me the code

#

thx

vapid parcel
#

ill just send it here lol

sturdy fractal
vapid parcel
#
    @commands.hybrid_command()
    @commands.guild_only()
    @app_commands.describe(emoji='Please give a discord Emoji.')
    async def steal(self, ctx, emoji: discord.PartialEmoji):
        embed = discord.Embed(title='Emoji Stealer', description=f'Download the emoji: [Download Emoji]({emoji.url})', timestamp=discord.utils.utcnow(), color=config.main_color)
        embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
        embed.set_thumbnail(url=emoji.url)
        await ctx.send(embed=embed)```
#

No need for pastebin lol

sturdy fractal
#

o lmao that just 4 lines code

vapid parcel
#

ye

#

really simple.

sturdy fractal
#

wait we can just use hybrind_command to make it slash and prefix both

vapid parcel
#

Yes

sturdy fractal
#

dam

vapid parcel
#

hybrid is for prefix + slash

sturdy fractal
#

great

vapid parcel
#

You didn't know that?

sturdy fractal
sturdy fractal
vapid parcel
#

@commands.dm_only()?

vapid parcel
#

Yeah, im a fan of hybrid

#

Only because I can do certain things slash commands can't do if that makes sense, like you can't reply to messages using a slash command, so I have certain prefix commands that require you to reply to someone

#
    @commands.command(name='ratio')
    async def ratio(self, ctx):
        """
        Ratio another member's message by replying to it with the ratio command!
        """
        if not ctx.message.reference:
            await ctx.send("Please reply to a message with `ratio` to ratio it.")
            return

        target_message = await ctx.fetch_message(ctx.message.reference.message_id)

        random.shuffle(emojis)

        selected_emojis = emojis[:10]

        for emoji in selected_emojis:
            try:
                await target_message.add_reaction(emoji)
            except discord.errors.HTTPException as e:
                if "Unknown Emoji" in str(e):
                    embed = discord.Embed(
                        title="Error",
                        description=f"An error occurred while adding an emoji to the message. Unknown Emoji: {emoji}\n\nPlease report this error to our [Support Server]({config.SUPPORT_SERVER})!",
                        color=config.error_color
                    )
                    await ctx.send(embed=embed)```
#

Which would be a ratio command, you could make it go off message id, but thats boring lol.

#

You would have to get the message ID yourself, but I rather do it the lazy way and make the bot do it, making it a prefix command only

vapid parcel
#

I have a file called config

#

so i don't have to type certain things out every time

#

so I can just use the config file

#
main_color = 0x5865F2  # Main color for all EMBEDS, not Errors or Success usually...

error_color = 0xFF0000  # Error color for all errors

success_color = 0x00FF00  # Success color for all successful embeds

xp_per_message = random.randint(5, 15)

footer_text = "© UniBot 2023-2024"```

Like having stuff like this, so when I set a footer I can just do config.footer_text instead of typing it out again.
rugged shadow
#

so you get the same xp per message across every mesasge

vapid parcel
#

alr

#

Each message goes back to xp_per_message

#

so it pick random each time if im not wrong, but I didn't write the leveling system, the other dev did.

rugged shadow
#

it does not run random.randint whenever you access it

#

so you should move that calculation in your handler

vapid parcel
#

alr ty

iron sorrel
#

hello!

#

does anyone know how i can instantly register slash commands in only one server using discord.py 2.0>?

vapid parcel
shrewd apex
vapid parcel
iron sorrel
sturdy fractal
#

@iron sorrel which module for buttoms?

vapid parcel
ashen river
#

any idea what might be wrong here?

    def __init__(self):
        super().__init__(title="Input")
        self.add_item(discord.ui.TextInput(label='Input',
                                           style=discord.TextStyle.long,
                                           placeholder='Enter Input, one per line, in the format: HH:MM:SS:HH:MM:SS',
                                           required=True))

    async def callback(self, interaction: discord.Interaction):
        # Defer the interaction to give us more time to respond
        await interaction.response.defer()

        # Try to process the input data and catch any exceptions
        try:
            input_data = self.children[0].value.split('\n')

            # Create and write to file
            filename = f"input_{datetime.now().strftime('%Y%m%d%H%M%S')}.txt"
            with open(filename, 'w') as file:
                file.write("StartingHour:StartingMinute:StartingSecond:EndingHour:EndingMinute:EndingSecond\n")
                for line in input_data:
                    if line.strip():  # Ensure the line is not empty
                        file.write(line.strip() + '\n')

            # Send confirmation after processing is done
            await interaction.followup.send(f"File {filename} created successfully.")

        except Exception as e:
            # Log the exception
            logging.error(f"An error occurred: {e}")

            # Inform the user
            await interaction.followup.send("An error occurred while processing your request.")

@bot.tree.command(name='create_modal', description='Create a modal')
async def create_modal(interaction: discord.Interaction):
    # Show the modal to the user
    modal = Modal()
    await interaction.response.send_modal(modal)```
vapid parcel
#

Issue?

ashen river
#

nothing appears on terminal

vapid parcel
#

Print the error

iron sorrel
sturdy fractal
vapid parcel
sturdy fractal
#

right

vapid parcel
#

its discord.ui.button

ashen river
sturdy fractal
#

oo

vapid parcel
#

print each step. So you can find out where it messes up at

ashen river
#

ok

vapid parcel
#

I don't mess with modal often, but no one else is here talking about it, so im just giving best advice by saying use prints to figure out the error

iron sorrel
sturdy fractal
iron sorrel
#

2.0+

sturdy fractal
vapid parcel
#

you only need to import discord

#

you need to learn interaction too

sturdy fractal
vapid parcel
#

It shows examples here

sturdy fractal
vapid parcel
#

....

#

Bro what 😭

#

you talking about the button label being Yes n No??

ashen river
sturdy fractal
#

sorry i m disturbing u

vapid parcel
#

Well first

#

No one in here is going to write that for you, we aren't just gonna give code like that lol. Second, you gotta read what its saying, you can easily learn what its doing by reading them make the interactions yourself.

#

We are all here to help you, not write it for you, not to sound rude or anything, its just how it is, we are trying to help or help you with a problem, not write the code for you.

sturdy fractal
vapid parcel
# sturdy fractal i thought thats a 3,4 line code mb

Depends on how you do it, but yes it could be. But we are here to help or let you learn if that makes sense? We don't wanna give code because then you don't learn if that makes sense, not trying to be rude either.

sturdy fractal
sturdy fractal
vapid parcel
#

I can't just write a template lol

#

I mean, the github shows examples, so you can kinda go off what they are doing

#

it teaches you all.

sturdy fractal
vapid parcel
#

on the github there is..?

#

for buttons

sturdy fractal
#

i m writing code with using it getting some error

iron sorrel
unkempt canyonBOT
#

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

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

New in version 2.0.
tall creek
#
import discord
from discord.ext import commands



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

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.MissingPermissions):
            missing_permissions = ', '.join(error.missing_perms) if hasattr(error, 'missing_perms') and error.missing_perms else "Unknown"

            embed = discord.Embed(
                title="",
                description=f":mod_untick: You need certain Kryptex Permissions to use this command!\n:mod_arrow: You need one of those permissions:\n `{missing_permissions}`",
                color=0x2f3136
            )
            embed.set_author(name="You can't use this command!",
                             icon_url=ctx.author.avatar.url)
            await ctx.send(embed=embed)

async def setup(bot):
    await bot.add_cog(Errors(bot))
#

@iron sorrel

sturdy fractal
#

check

#

i get interaction failed

tall creek
#

Ban permission kick permission

#

This is not showing

iron sorrel
#

whaa

sturdy fractal
#

@iron sorrel bro can u check my code

iron sorrel
sturdy fractal
#

interactions

#

check callback

vapid parcel
#

Bro what is happening

vapid parcel
sturdy fractal
#

i used the github way

#

i get attribute errors

vapid parcel
#

send error

#

n code

sturdy fractal
#

AttributeError: 'Button' object has no attribute 'response'

#

interaction failed

vapid parcel
#

Alright bro

#

you have to have interaction first

#

You have Button then interaction. It needs to be interaction then Button

#

just swap the order, then issue should be fixed maybe..?

sturdy fractal
vapid parcel
sturdy fractal
vapid parcel
#

they are your buttons GoofySkull

sturdy fractal
#

i didnt knew it was your code

vapid parcel
#

its my code 😭

#

I make discord bots too GoofySkull

sturdy fractal
vapid parcel
#

i was showing you an example of it being correct...

sturdy fractal
#

ye got it

vapid parcel
sturdy fractal
vapid parcel
#

?

sturdy fractal
#

Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 18, in no_button
await self.cog.confirmation_callback(False, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 81, in confirmation_callback
await interaction.followup.send("Operation canceled.")
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async
.py", line 1817, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

vapid parcel
#

Why are you using a webhook?

sturdy fractal
#

i m not

vapid parcel
#

send updated code 😭

sturdy fractal
#

thats the same code

vapid parcel
#

just send the updated code.

sturdy fractal
#

kk

vapid parcel
#
async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
    try:
        await interaction.message.edit(content="Operation canceled.")
        await self.cog.confirmation_callback(False, interaction)
    except discord.errors.NotFound as e:
        print(f"Error: {e}")
#

Do this

#

to print error

tall creek
vapid parcel
tall creek
#

On_command_error

vapid parcel
tall creek
#

Okey

#

w8

vapid parcel
#

ll

#

kk

vapid parcel
tall creek
#
@client.command()
@commands.has_permissions(administrator=True)
async def testerror(ctx):
  await ctx.send("error")
import discord
from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.MissingPermissions):
            missing_permissions = ', '.join(error.missing_perms) if hasattr(error, 'missing_perms') and error.missing_perms else "Unknown"

            embed = discord.Embed(
                title="",
                description=f":mod_untick: You need certain Kryptex Permissions to use this command!\n:mod_arrow: You need one of those permissions:\n `{missing_permissions}`",
                color=0x2f3136
            )
            embed.set_author(name="You can't use this command!",
                             icon_url=ctx.author.avatar.url)
            await ctx.send(embed=embed)

async def setup(bot):
    await bot.add_cog(Errors(bot))
tall creek
#

testerror
Kryptex
BOT
— Today at 3:53 PM

You can't use this command!
:mod_untick: You need certain Kryptex Permissions to use this command!
:mod_arrow: You need one of those permissions:
Unknown

#

Unknown

vapid parcel
#

is it cuz its doing Unknown?

tall creek
vapid parcel
#

what is the error 😭

sturdy fractal
vapid parcel
tall creek
sturdy fractal
#

lemon_sentimental bro

tall creek
#

or Administrator permisson

sturdy fractal
#

he gets unknown as result

#

rather than ban perms

tall creek
vapid parcel
#

I literally said that GoofySkull

tall creek
vapid parcel
#

Bro

#

what is the command GoofySkull

#

Because if the command has no perm on it, then its gonna be unknown

tall creek
#
@client.command()
@commands.has_permissions(administrator=True)
async def testerror(ctx):
  await ctx.send("error")
vapid parcel
#

do you have admin?

tall creek
#

no

vapid parcel
#

are you owner of the server?

tall creek
#

no

#

only member

sturdy fractal
# vapid parcel its your button........

2024-01-14 16:00:03 ERROR discord.ui.view Ignoring exception in view <Buttons timeout=30 children=2> for item <Button style=<ButtonStyle.danger: 4> url=None disabled=False label='No' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 18, in no_button
await self.cog.confirmation_callback(False, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 83, in confirmation_callback
await interaction.followup.send("Operation canceled.")
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async
.py", line 1817, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

vapid parcel
#

idk dawg

tall creek
vapid parcel
# tall creek only member
    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.MissingPermissions):
            missing_permissions = ', '.join(getattr(error, 'missing_perms', [])) or "Unknown"

            embed = discord.Embed(
                title="",
                description=f":mod_untick: You need certain Kryptex Permissions to use this command!\n:mod_arrow: You need one of those permissions:\n `{missing_permissions}`",
                color=0x2f3136
            )
            embed.set_author(name="You can't use this command!",
                             icon_url=ctx.author.avatar.url)
            await ctx.send(embed=embed)```
#

Try this, idk you are doing it weird tbh GoofySkull

vapid parcel
vapid parcel
#

Bro

#

alright

#

Lets not do missing perms like you are doing then?

sturdy fractal
vapid parcel
#
            elif isinstance(error, commands.MissingPermissions):
                missing_permissions = ', '.join(error.missing_permissions)
                error_embed = discord.Embed(
                    title="Error",
                    description=f"You don't have the required permissions for this command, you need ``{missing_permissions}`` permission to use this command.",
                    timestamp=discord.utils.utcnow(),
                    color=config.error_color
                )
                error_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
                await ctx.send(embed=error_embed, ephemeral=True)
#

This is how I do it, you can customize it how you want

vapid parcel
#

he knows some things, but half the time he is stupid

sturdy fractal
#

i use it as last option

vapid parcel
#

I barely use him unless I know nothing

sturdy fractal
#

it fixed kinda

#

but another error lma

vapid parcel
sturdy fractal
#

2024-01-14 16:03:49 ERROR discord.ui.view Ignoring exception in view <Buttons timeout=30 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Yes' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 13, in yes_button
await self.cog.confirmation_callback(True, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 81, in confirmation_callback
await interaction.response.send_message("Drop counts have been reset.", ephemeral=True)
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 786, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

vapid parcel
#

ah

#

I know

sturdy fractal
#

does this means i clicked the the button twice>

vapid parcel
#

show code please, so I can help you,

tall creek
#

@vapid parcel thnx bro its working

vapid parcel
sturdy fractal
vapid parcel
sturdy fractal
#
 async def confirmation_callback(self, confirmed: bool, interaction: discord.Interaction):
        if confirmed:
            self.drop_counts.clear()
            await interaction.response.send_message("Drop counts have been reset.")
        else:
            await interaction.response.send_message("Operation canceled.",)
            
    async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        try:
            await interaction.message.edit(content="Operation canceled.")
            await self.cog.confirmation_callback(False, interaction)
        except discord.errors.NotFound as e:
            print(f"Error: {e}")
#

only 2 line lmao

#

and i want the button to be off

#

after being clicked

vapid parcel
#

oh

#

I see

#

you are doing a callback. You don't need a call back when the buttons already do it for you I think

#

Wait

#

no

sturdy fractal
#

huh?

#

u also looks confused

vapid parcel
#

Kinda am atp GoofySkull

sturdy fractal
vapid parcel
#

you have it in a weird way....

#

well see, you are doing a followup... even tho idk hold on

sturdy fractal
vapid parcel
#
 async def confirmation_callback(self, confirmed: bool, interaction: discord.Interaction):
        if confirmed:
            self.drop_counts.clear()
            await interaction.response.defer()

    async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        try:
            await interaction.message.edit(content="Operation canceled.")
            await self.cog.confirmation_callback(False, interaction)
        except discord.errors.NotFound as e:
            print(f"Error: {e}")```
sturdy fractal
vapid parcel
#

Try the confirm button

#

see if it gives error

vapid parcel
#

Wait... Why are you using call back...?

sturdy fractal
#

defer?

vapid parcel
#

Bro im so confused, im lost in the sauce atp 😭

sturdy fractal
vapid parcel
#

Buttons do that already...

#

Alright, we can do something like this I guess.. idk if it will work

sturdy fractal
#

hmm

vapid parcel
#
 async def confirmation_callback(self, confirmed: bool, interaction: discord.Interaction):
        if confirmed:
            await interaction.response.defer()

    async def no_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        try:
            await interaction.response.defer()
        except discord.errors.NotFound as e:
            print(f"Error: {e}")```
#

Do these, because your callback already does the rest

#

Unless im tripping, it is 5am GoofySkull

sturdy fractal
#

what is defer ?

vapid parcel
#

!tag defer

unkempt canyonBOT
#
Did you mean ...

» mutable-default-args
» defaultdict

vapid parcel
vapid parcel
#

without having a fail.

sturdy fractal
vapid parcel
#

Tell me if those buttons work

sturdy fractal
#

btw button.disabled=true

#

dont work

vapid parcel
#

Buttons arent working?

#

Just try the buttons first, we can disable later 😭

sturdy fractal
vapid parcel
#

they work?

sturdy fractal
#

i got it why we used to get error

#

when we alr responded

#

and tried to response 2nd time

vapid parcel
#

Yeahhh

sturdy fractal
#

thats why we get the error

vapid parcel
#

thats why i was confused on why we used call back

#

not we, YOU used callback

#

so I just made it accept interaction, then it shouldve worked

sturdy fractal
vapid parcel
#

Okay so the buttons are working? can you confirm?

sturdy fractal
#

ye

vapid parcel
#

alr

sturdy fractal
#

lemme use again

vapid parcel
#

Alright

#

await self.disable_buttons()

#

use this then do

await interaction.message.edit(view=self)

sturdy fractal
#

but doesnt actually clear the drop counts

vapid parcel
#

then use await

#

its clearly accepting interaction tho

#

so that means you arent doing something right on your side, im doing my part tho GoofySkull

sturdy fractal
#

ye but it doesnt clear the counts which he used to

vapid parcel
#

its 5am

#

i have no brain power GoofySkull

sturdy fractal
#

self.drop_counts.clear()

#

BRUHH

#

u didnt added this

#

i mean i have to add it mb

vapid parcel
#

do it yourself 😭

sturdy fractal
#

ye

sturdy fractal
sturdy fractal
vapid parcel
#

Bro

#

it will show for everyone GoofySkull

#

an edit is an edit, no one can change how discord does edits GoofySkull

sturdy fractal
#

self i thought only the user

vapid parcel
#

.....................................

#

my brain is gonna explode 😭

#

do this

#

send updated code actually

#

so i can do this for you, then you can go on with your day 😭

sturdy fractal
#

i did it lemme test

vapid parcel
#

nah

#

imma just make it simple for you, just incase you did it wrong

sturdy fractal
#

kk

sturdy fractal
#

i even have to add storing counts in a file that gonna be a pain as well

vapid parcel
#

this should work, if not then skill issue ig

#

hard to edit shit in a non IDE at 5am GoofySkull

pale zenith
#

You shouldn't delete messages after you ping someone

pale zenith
vapid parcel
#

Yeah I am currently helping them

vapid parcel
sturdy fractal
pale zenith
vapid parcel
pale zenith
vapid parcel
#

@sturdy fractal did it work

#

i need you to like, confirm whats happening

#

so I can possibly go to sleep GoofySkull

pale zenith
#

Breaking news: mods ban the android operating system

pale zenith
vapid parcel
#

its 5am 😭

#

ive been helping peps all night

sturdy fractal
vapid parcel
#

got really bored

sturdy fractal
#

wtf

vapid parcel
#

XD

sturdy fractal
#

waiy bro

vapid parcel
#

😭

sturdy fractal
#

nitro hacks

vapid parcel
#

it doesnt take this long 😭

sturdy fractal
#

File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 32, in no_button
await self.disable_buttons()
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Buttons' object has no attribute 'disable_buttons'

vapid parcel
#

dawg

sturdy fractal
vapid parcel
#

maybe, copy what i send....................

#

oh wait

#

oh wait, mb mb mb mb mb

sturdy fractal
#

😵‍💫

vapid parcel
#

There 😭

#

@sturdy fractal does it work nowwwwwwwwwwwwwww

#

if not then i prolly forgot another thing 😭

sturdy fractal
#

pray it works

#

FINALLY IT WORKED

#

BUT STILL interaction failed

vapid parcel
#

USE DEFER

#

I GAVE YOU DEFER GoofySkull

sturdy fractal
#

@vapid parcel confirm doesnt work

vapid parcel
#

to bad bro GoofySkull

#

its 5am, ask another person for help 😭

sturdy fractal
vapid parcel
#

like what is the issue now...? idk why you are using call back atp 😭

sturdy fractal
vapid parcel
#

just make the buttons do it all GoofySkull

sturdy fractal
#

and sorry for all the mental dmg i gave u

vapid parcel
#

I already had that before I met you GoofySkull

#

so dw GoofySkull

sturdy fractal
vapid parcel
# sturdy fractal THE BUTTONS DONT WORK WITHOUT IT

...................................................................................................................................................................................................................................................

sturdy fractal
vapid parcel
#

Bro

#

Im about to like

sturdy fractal
#

i feel pity for u
go to sleep ig

vapid parcel
#

blow your house up atp 😭

#

joking obvi, don't report me 😭

#

So does disable work btw?

#

like what are the current issues you are HAVING

sturdy fractal
vapid parcel
sturdy fractal
#

and for confirm it doesnt

vapid parcel
#

Okay

#

hold on

sturdy fractal
#

File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 23, in yes_button
await self.cog.confirmation_callback(True, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 115, in confirmation_callback
await interaction.response.defer()
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 651, in defer
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

#

this error

sturdy fractal
vapid parcel
#

:/

#

Dawg, ive never used call back GoofySkull

#

n im trying my best to like help you 😭

#

imma just sleep, just wait for another person to help ig 😭

sturdy fractal
#

thanks and sorry

vapid parcel
#

imma go work on my bot tmr ig after I wake up XD

vapid parcel
#

or you can just dm me n when I wake up I can rework it ig

#

to a way that i know works GoofySkull

sturdy fractal
sturdy fractal
vapid parcel
#

just dm me if no one helps

#

but I bet someone will help you

sturdy fractal
vapid parcel
#

ig

sturdy fractal
vapid parcel
#

bros slow 😭

pale zenith
sturdy fractal
#

I JUST checked your

#

profile o nvm

#

clickbait

pale zenith
#

If you need my help, what's your latest code and like a quick explanation of your error?

sturdy fractal
#

so the error is

#

when i use cancel button i get interaction failed
but it does his work , the button gets disabled

#

while the confirm button doesnt work

#

Traceback (most recent call last):
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
await item.callback(interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 23, in yes_button
await self.cog.confirmation_callback(True, interaction)
File "c:\Users\aksha\OneDrive\Documents\Code\Discord bots\Sofi utility\cogs\sofi.py", line 115, in confirmation_callback
await interaction.response.defer()
File "C:\Users\aksha\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 651, in defer
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

pale zenith
#

I see

#

You can only do one interaction.response.xxxxx per each interaction object you receive

pale zenith
#

You here are first sending a message (line 22) then calling another function (line 23) and that function sends another response (line 115)

#

Sending a second response will always fail, you can only send one per each interaction object

sturdy fractal
#

!resetdrop

and on 2nd !resetdrop it says interaction has alr been responded

pale zenith
#

And the same goes for the other one

sturdy fractal
#

o

vapid parcel
#

yeahh... i meant to change edit to send

pale zenith
#

Also I don't really see the reason for self.button_disabled

vapid parcel
#

GoofySkull mb

vapid parcel
pale zenith
#

Since you set it to true then stop the view, meaning that it won't work anymore

sturdy fractal
pale zenith
#

!examples views/confirm

#

Oh shit I forget this is pydis

sturdy fractal
#

lmao

sturdy fractal
pale zenith
#

An example of a confirmation prompt, from the official discord.py repository. Could be good to take a look

pale zenith
#

Also, why not just do self.cog.drop_counts.clear() directly from the view? I see no point in having these callbacks on the Cog

sturdy fractal
pale zenith
#

Well it doesn't matter if you clear it from the cog callback, or the view button callback

#

Either way it'll get cleared on-click, since you're invoking the cog callback from the button one

sturdy fractal
#

alr lemme try

sturdy fractal
# pale zenith

need to remove this line as welll
await self.cog.confirmation_callback

pale zenith
sturdy fractal
#

to clear counts

#

confused

little perch
#

Guys how do i set a bots about me

pale zenith
sturdy fractal
little perch
#

Thanks

pale zenith
#

The view is a standalone thing that handles button stuff

sturdy fractal
#

oo

pale zenith
#

Your cog callbacks are something that you made

#

And that you are manually invoking from your button code

#

Them existing doesn't change the view's function

sturdy fractal
#

now if i even click cancell it will reset the drop counts

#

i just added what u said

#

and disabled callbacks

pale zenith
#

If you're calling .clear() from the no button callback

supple ridge
#

how can i use jishaku to run a function inside my cog?

sturdy fractal
#

here the code have a look

#

@pale zenith have a look

pale zenith
sturdy fractal
#

i m just keeping it till this gets fixed

pale zenith
# sturdy fractal once i fix this i will erase all comments

No, by that I mean, for example, your no button, it could be reduced to the following:

#
    @discord.ui.button(label="No", style=discord.ButtonStyle.red)
    async def no_button(self,interaction: discord.Interaction, button: discord.ui.Button):
        self.stop()
        await self.disable_buttons()
        await interaction.response.edit_message(content="Operation canceled.", view=self)
supple ridge
#

how can i use jishaku to run a function inside my cog?

sturdy fractal
#

alr

#

and about the error?

pale zenith
sturdy fractal
#

lmao

#

u forgot the main thing

#

i clicked no

#

and it still reset the drop counts

pale zenith
#

You're clearing your leaderboard in the init lol

sturdy fractal
pale zenith
#

Not in the init

pale zenith
#

Yeah by directly on the view I mean within async def yes button

#

Aka It would replace that comment you have

sturdy fractal
#

@discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
async def yes_button(self,interaction: discord.Interaction, button: discord.ui.Button):
self.stop()
await self.disable_buttons()
await interaction.response.edit_message(content="Drop counts have been reset.")
self.cog.drop_counts.clear()

pale zenith
pale zenith
sturdy fractal
#

await interaction.message.edit(view=self)

#

without it , it as well get edited

tiny coyote
#

im tryin to get bot cogs and im receiving an error:

C:/Users/Naseer/AppData/Local/Programs/Python/Python312/python.exe "c:/Users/Naseer/Desktop/That one server/GameLoop.py"
Traceback (most recent call last):
  File "c:\Users\Naseer\Desktop\That one server\GameLoop.py", line 35, in <module>
    bot.load_extentions(f"cogs{filename[:-3]}")
    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'load_extentions'
PS C:\Users\Naseer\Desktop\That one server> 
sturdy fractal
#

show the code

tiny coyote
sturdy fractal
#

no only this cogs part

#

u have your actually code in? main.py?

tiny coyote
#
for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        bot.load_extentions(f"cogs{filename[:-3]}")

Token = "TOKEN?"
bot.run(config.Token)```
sturdy fractal
#

extension

#

setup_hook is a better way to do it

tiny coyote
#

setup_hook

#

alr

pale zenith
sturdy fractal
#

Ye

tall creek
#
jsk py
 await ctx.send("hey")
#

Error

#
    value = await base.asend(self.send_value)
  File "<repl>", line 1, in _repl_coroutine
    await ctx.send("hey")
NameError: name 'ctx' is not defined
golden portal
#

jishaku define context as _ctx by default so

pale zenith
# tall creek ?

All variables provided by Jishaku are prefixed with an underscore

#

_channel, _bot, _message, _ctx, _guild, _get, _find and so on

#

You can change it with an environment variable

tall creek
#

okey thnx

golden portal
#

jishaku support on pydis

pale zenith
pale zenith
#
import os
os.environ["JISHAKU_NO_UNDERSCORE"] = "true"
``` or
```py
import jishaku
jishaku.Flags.NO_UNDERSCORE = True
pale zenith
tiny coyote
#
Traceback (most recent call last):
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Naseer\Desktop\That one server\GameLoop.py", line 35, in on_message
    await c.execute("SELECT * FROM status WHERE id = ? ", (message.author.id))
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\cursor.py", line 48, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\cursor.py", line 40, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\core.py", line 133, in _execute
    return await future
           ^^^^^^^^^^^^
  File "C:\Users\Naseer\AppData\Local\Programs\Python\Python312\Lib\site-packages\aiosqlite\core.py", line 106, in run
    result = function()
             ^^^^^^^^^^
sqlite3.ProgrammingError: parameters are of unsupported type
daring grove
#
elif isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(title="",
                                  description=f":mod_untick: You need to provide a valid argument for this command!\n:mod_arrow: Usage:\n `{ctx.prefix}{ctx.command.name} {ctx.command.signature}`", color=0x2f3136)
            await ctx.send(embed=embed)
pale zenith
#

(X) is not a tuple. Those are parentheses of order of operation stuff.
(X, ) is a tuple.

sturdy fractal
#

Command raised an exception: TypeError: Buttons.init() takes 2 positional arguments but 4 were given

odd jasper
#

`@client.event
async def on_member_join(member):
welcome_role_1 = member.guild.get_role(1158290739244048484)
if welcome_role_1:
await member.add_roles(welcome_role_1)

welcome_role_2 = member.guild.get_role(1159466928503533609)  
if welcome_role_2:
    await member.add_roles(welcome_role_2)

welcome_channel = client.get_channel(1158134371308540075)
if welcome_channel:
    embed = discord.Embed(title=f"Herzlich willkommen {member.display_name}!",
                          description="Willkommen auf DevUnit, der ultimativen Coding & Tech-\nCommunity! 🎉",
                          color=discord.Color.blue())
    embed.set_thumbnail(url=member.avatar_url)  
    embed.set_footer(text="DevUnit • DE")
    await welcome_channel.send(embed=embed)`
#

Why doesnt this work?

#

Something is wrong with the avatar thing ig

slate swan
#

In 2.0 and above it's member.avatar.url

#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar)
odd jasper
#

Ahhh dawn

#

I forgot, thanks mate

#

`@client.event
async def on_member_join(member):
welcome_role_1 = member.guild.get_role(1158290739244048484)
if welcome_role_1:
await member.add_roles(welcome_role_1)

welcome_role_2 = member.guild.get_role(1159466928503533609)  
if welcome_role_2:
    await member.add_roles(welcome_role_2)

welcome_channel = client.get_channel(1158134371308540075)
if welcome_channel:
    embed = discord.Embed(title=f"Herzlich willkommen {member.display_name}!",
                          description="Willkommen auf DevUnit, der ultimativen Coding & Tech-\nCommunity! 🎉",
                          color=discord.Color.blue())
    embed.set_thumbnail(url=member.avatar.url)  
    embed.set_footer(text="DevUnit • DE")
    await welcome_channel.send(embed=embed) `
#

Bot is still not starting...

slate swan
#

Errors would be nice

pale zenith
#

(Also note how add_roles is plural. You can add_roles(as, many, roles, you, want) in one single call)

odd jasper
#

`@client.tree.command()
async def comingsoon(ctx):
embed = discord.Embed(
title="Coming Soon!",
description="Dieses Feature ist in Entwicklung und\nwird bald verfügbar sein.\nWir freuen uns darauf,\nes mit euch zu teilen!",
color=discord.Color.blue()
)
embed.set_footer(text="DevUnit • DE")
embed.set_thumbnail(url=client.user.avatar_url)

await ctx.send(embed=embed)`

But there is a new thing that doesnt work, already searched for a resolution but didnt find any.
What is wrong there? :P

pale zenith
#

they take an interaction object. You use interaction.response.send_message() to send messages with it

#

here are some resources on app commands you may like

civic reef
#

can anyone give good video tutorials to learn Discord bot dev?

slate swan
#

All are bad. Reading documentation and looking at the examples is better

civic reef
#

okay, thanks

pale zenith
civic reef
#

thanks for this also

midnight oracle
#

Is there a way to get all the users of all the servers the bot is in and check if those users are in a specific list of servers (via server ID) and if so, do something like apply a role, if not, then pass?

midnight oracle
#

Solved, nevermind

fading yew
#

Is it preferable to use decorators or subclass Client (discord.py)? Why?

final iron
fading yew
final iron
#

not for this

fading yew
#

Would still love to hear some, any opinions on if there even is a difference (other than just visual style) pithink

pale zenith
#

Plus I can create a single bot class and use it in many projects

#

(e.g. a friend taught me about git submodules and they are neato asf)

pale zenith
#

If you ask a question 😉

inland plover
#

how do i paste the code

pale zenith
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

inland plover
#

so i did this and its not showingg in the gsheet

pale zenith
#

Oh, no I can't help since I've never worked with that. Sorry

inland plover
#

oh

#

its alr

pale zenith
#

Best I can say is suggestion to use an actual database like sqlite

inland plover
#

ok thx

inland plover
pale zenith
#

pip install git+THAT LINK

inland plover
pale zenith
#

As stated:

A simple and easy to use async wrapper for sqlite3.

This is basically the same as sqlite3 except you use async with and await in front of most operations.

#

!d sqlite3

unkempt canyonBOT
#

Source code: Lib/sqlite3/

SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.

The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.

This document includes four main sections:

inland plover
#

ok thx

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

pale zenith
#

then you can just send(embed=X, view=Y)

vale wing
fading yew
vale wing
#

I still can't understand the subject

#

I mean you typically would use decorators and subclassing for different subjects

#

Like subclassing for database, custom bot functions and other stuff; decorators ultimately for commands (in context of discord.py)

#

While you technically can use subclassing for commands (however that will be unholy af) I can't even think how you would implement additional functionality using dpy decorators

#

So there's no thing that is "better" to use, they are specific to the cases and solve different problems

fading yew
# vale wing I still can't understand the subject

I be direct:

client = discord.Client()

@client.event
async def on_ready():
    print(f'{client.user} has connected to Discord!')

client.run(TOKEN)

vs

class CustomClient(discord.Client):
    async def on_ready(self):
        print(f'{self.user} has connected to Discord!')

client = CustomClient()
client.run(TOKEN)
vale wing
#

This is probably the single case where decos and method overriding are interchangeable

vale wing
#

I'm bored, someone please come here with a weird internal lib traceback issue that is actually caused by a typo

little perch
#

how to make it so people can only use a command in a specific channel

severe sonnet
#

i had a friend recommending using Ruff and he gave me instructions to install poetry and all. But now since i lost his instructions i'm completely lost on what to do, i installed mypy, black and ruff for the configuration, but i'm still lost
.vscode:
settings.json

#
{
    "python.analysis.extraPaths": [
        "./database",
    ],
    "[python]": {
        "editor.defaultFormatter": "ms-python.black-formatter",
        "editor.formatOnSave": true,
        "editor.codeActionsOnSave": {
            "source.organizeImports": "explicit"
        },
    },
    "files.exclude": {
        "**/__pycache__": true,
        ".mypy_cache": true
    },
    "ruff.organizeImports": false
}
#

extension.json

latent jay
#

How do I create my own check deco again

severe sonnet
#
{
    "recommendations": [
        "ms-python.python",
        "zeshuaro.vscode-python-poetry",
        "charliermarsh.ruff",
        "matangover.mypy",
        "ms-python.black-formatter"
    ]
}
#

I still receive erroers and my traceback seems to not being enabled

#
C:/Users/User/AppData/Local/pypoetry/Cache/virtualenvs/rp-utilities-2cgrnvKo-py3.11/Scripts/Activate.ps1
& : O arquivo C:\Users\User\AppData\Local\pypoetry\Cache\virtualenvs\rp-utilities-2cgrnvKo-py3.11\Scripts\Activate.ps1 não 
about_Execution_Policies em https://go.microsoft.com/fwlink/?LinkID=135170.
No linha:1 caractere:3
+ & C:/Users/User/AppData/Local/pypoetry/Cache/virtualenvs/rp-utilities ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ErrodeSegurança: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
#

okay guess the program is having issue with this:

latent jay
severe sonnet
#
Mypy extension activated, version 0.3.0
Registering listener for interpreter changed event
Listener registered
[1] Check folder: c:\Users\User\Documents\GitHub\RP-Utilities
[1] Using extra arguments: 
Activation complete
[1] Received Python path from Python extension: c:\Users\User\AppData\Local\pypoetry\Cache\virtualenvs\rp-utilities-2cgrnvKo-py3.11\Scripts\python.exe
[1] Running dmypy in folder c:\Users\User\Documents\GitHub\RP-Utilities
'C:\Users\User\AppData\Local\Programs\Python\Python311\Scripts\dmypy.EXE' --status-file 'c:\Users\User\AppData\Roaming\Code\User\workspaceStorage\7d9b54f5a8aa8c586d40915065449da4\matangover.mypy\dmypy-d26e67611339ec4bc1bc942196999aa8e80daf2d-4864.json' run --log-file 'c:\Users\User\AppData\Roaming\Code\User\workspaceStorage\7d9b54f5a8aa8c586d40915065449da4\matangover.mypy\dmypy-d26e67611339ec4bc1bc942196999aa8e80daf2d.log' -- --python-executable 'c:\Users\User\AppData\Local\pypoetry\Cache\virtualenvs\rp-utilities-2cgrnvKo-py3.11\Scripts\python.exe' . --show-error-end --no-error-summary --no-pretty --no-color-output
[1] stderr:
rp-utilities is not a valid Python package name

[1] Error running mypy in c:\Users\User\Documents\GitHub\RP-Utilities: mypy failed with error: "rp-utilities is not a valid Python package name
". See Output panel for details.
little perch
#

Solved

severe sonnet
#

what did i did wrong i have no idea

#

how do i solve this mypy problem?

#

it's saying rp-utilities is not a valid Python package

latent jay
young dagger
#

Can someone explain why they are not inline?

#

10 players, 10 games played, 10 ranks

final iron
final iron
young dagger
# final iron <:shrug:1159570387953258616>

Something wrong with this?

        if rank == 1:
            emoji = ":first_place:"
        elif rank == 2:
            emoji = ":second_place:"
        elif rank == 3:
            emoji = ":third_place:"
        else:
            emoji = ""

        rank_display = f"{emoji}" if emoji else f"{rank}."
final iron
#

The ones with the emojis seem to be much closer together

final iron
#

You'll have to find a way around it

young dagger
hushed galleon
#

if you want to prevent the numbered list formatting, it seems like you can put a backslash in front of each period

hushed galleon
#

well, embed field values support markdown

#

i have this embed pinned for whenever i need to reference which parts of embeds support markdown

hazy kraken
#

hi

#

i'm having problems in downloading mysql-connector in my server

vale wing
tall creek
#
No module found wavelink
vale wing
#

Before we can help, please tell what you are using wavelink for

naive briar
#

Classic

vale wing
tall creek
vale wing
tall creek
vale wing
#

Well you don't AI generate it do you

tall creek
#

I just added my bot token and run the code

tall creek
#
, in <module>
    async def on_wavelink_track_end(player: wavelink.Player, track: wavelink.Track, reason):
AttributeError: module 'wavelink' has no attribute 'Track'. Did you mean: 'tracks'?
vale wing
#

Are there local files that you own copyright for

tepid dagger
#

how do you do set your bot's status to online from mobile

pale zenith
#

It's not possible. Not by regular means, you need to do some hacky shit

robust fulcrum
tepid dagger
#

no

#

to set the discord.status to mobile, cus i think you can doit in discord.js

tall creek
pale zenith
tepid dagger
#

could be wrong

tall creek
#

No

#

My friend code

tepid dagger
#

the music

#

not the code

#

where did you get the audio file with the music from

untold heart
#

data["embeds"] = [
{
"description" : "more text",
"title" : "This is a test",
"image" : [{"url": "htt p://a_cool_site.site" + file}]
}
]

{'content': 'message content', 'username': 'custom username', 'embeds': [{'description': 'more text', 'title': 'This is a test', 'image': [{'url': 'htt p://a_cool_site.site/uploads/Screenshot_2024-01-14_142626.png'}]}]}
400 Client Error: Bad Request for url: htt ps://discord.com/api/webhooks/the_id/secret_token

Someone who knows how to solve it?

wary belfry
#

first of all, there is obviously a space in the urls that doesn't belong there...
secondly, it's not even a valid api request url...

#

what is the_id and secret_token supposed to be?

#

Also, the code you pasted does not really seem to have anything to do with the error...

naive briar
pale zenith
#

Shocker kek

wary belfry
#

like ofc you get an error, when trying to call that url...

pale zenith
#

interaction comes before button
(self, interaction, button) is the order. not (self, button, interaction)
you are probably following an old tutorial. OR just updated from a pre-release version of discord.py (older versions of the discord.py v2.0alpha used the latter order)

hushed galleon
# untold heart data["embeds"] = [ { "description" : "more text", ...

400 Bad Request typically means something about your payload is incorrectly structured
https://discord.com/developers/docs/resources/channel#embed-object

image? embed image object
https://discord.com/developers/docs/resources/channel#embed-object-embed-image-structure
url string source url of image (only supports http(s) and attachments)
following the documentation, embeds[].image should be given the object containing the url and not an array, or in other words it should look like: json [ { "description": "...", "image": {"url": "https://example.com/my_image.png"} } ]

edgy plinth
#

How do I make a parameter optional?

@client.tree.command(name="map",description = "Display the current map.")
@app_commands.choices(mode=[discord.app_commands.Choice(name="Default",value=1),
discord.app_commands.Choice(name="Political",value=2),
discord.app_commands.Choice(name="Topography",value=3)])
async def map(interaction:discord.Interaction,mode: discord.app_commands.Choice[int]):

Such as mode?

hushed galleon
hushed galleon
#

i dont think the Choice typehint is necessary though, what your command receives will always be one of the value= arguments from your choices decorator

sullen chasm
#

It wont let me install discord on python because of a multidict error can any1 help?

hushed galleon
# sullen chasm It wont let me install discord on python because of a multidict error can any1 h...

the multidict dependency doesn't have any prebuilt wheels on python 3.12, so you should either:

  1. add --extra-index-url https://abstractumbra.github.io/pip/ to the end of your pip install command which provides third-party 3.12 wheels for multidict
  2. downgrade python to 3.11 and then reinstall discord.py
  3. follow the error message to install the C++ build tools before installing discord.py, though it requires about 6GB
sullen chasm
hushed galleon
#

don't forget to tell pip to install discord.py

sullen chasm
#

this?

hushed galleon
#

also that seems like an unusual place for your python installation to be placed at...

#

well assuming the python path is valid, sure

sullen chasm
#

ye i had to move the folder cus my user folder was broken

hushed galleon
#

eek, that doesn't sound good

sullen chasm
hushed galleon
#

oh, the normal way to work around that is to put quotes around the program you want to run, i.e. "C:\Users\My Name\AppData\Local\Programs\Python\Python312\python.exe" -m pip ... or in the case of python on windows, using the py launcher enabled by default in the python.org installer: py -m pip ... (assuming you didn't literally move the python installation files where it used to be, if so you'll need to move it back or repair it with the installer)

full lily
#

can i restrict discord.py slash command integer parameters to a certain range?

#

Like this

#

ooo i found something

hushed galleon
unkempt canyonBOT
#

class discord.app_commands.Range```
A type annotation that can be applied to a parameter to require a numeric or string type to fit within the range provided.

During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) so type checkers understand the intent of the code.

Some example ranges...
full lily
#

👍thanks

#

how do i create a dropdown with a bunch of options?

#

I'm seeing discord.ui.Select. Is it possible to have a dropdown in a slash command? That's what I'm after

#

For the user to select from a range of discrete choices

hushed galleon
#

note that they're hardcoded choices, if it needs to be unique to each user or otherwise generated dynamically, you'll need to use an @autocomplete() callback or a transformer that implements autocomplete()
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.Command.autocomplete
https://discordpy.readthedocs.io/en/stable/interactions/api.html#transformer
the latter might be nicer if you need to validate the user's input as autocomplete isn't allowed to restrict the user's input

full lily
#

Hm I'm getting TypeError: choices must all have the same inner option type as the parameter choice type

 @app_commands.choices(voice=[
        Choice(name='Sam', value=1),
        Choice(name='Mike', value=2),
        Choice(name='Mary', value=3),
        Choice(name='BonziBUDDY', value=4),
    ])
    async def say(self, ctx, text:str, voice:app_commands.Choice[str], pitch:app_commands.Range[int, 50, 400], speed:app_commands.Range[int, 50, 250]):
#

ah i changed the values

hushed galleon
#

i think your command receives the value directly and not as a Choice instance, so im not sure if app_commands.Choice[str] is a valid typehint

#

besides than the inner type being different from the values that is

full lily
#

the inner type?

hushed galleon
#

oh i mean str being a different type from your values 1, 2, etc.

full lily
#

ah I changed the values to strings now

#

that typehint I found on stack overflow. I'll try experimenting

dry kelp
#
status = Literal["online", 'idle', 'offline', 'dnd']


def _memberStatusStats(interaction: CommandInteraction) -> dict[status, int]:
    statuses = groupby(interaction.guild.members, lambda m: m.status)
    return dict(map(lambda k: (k[0], len(k[1])), dict(statuses)))

statuses = _memberStatusStats(interaction)
#

I didn't start up the bot for a while, seems like my command got outdated or something

#

Wait

#

could the error appear because there are no "IDLE" members?

#

What the fuck actually happened? 😂

#

2 different commands

#

But makes no sense to me, because i am using the same var in both commands

#

in guild members i am using lambda to distinguish humans from bots

#
    @guild.sub_command()
    async def members(self, interaction: CommandInteraction):
        """
        List server members
        """

        humans = len(list(filter(lambda m: not m.bot, interaction.guild.members)))
        bots = len(list(filter(lambda m: m.bot, interaction.guild.members)))

        statuses = _memberStatusStats(interaction)

        em = Embed(
            description=f"> {settings.emojis.members} Humans: `{humans}`\n"
                        f"> {settings.emojis.bots} Bots: `{bots}`\n"
                        f"> {settings.emojis.gd} Online: `{statuses['online']}`\n"
                        f"> {settings.emojis.wd} Offline: `{statuses['offline']}`\n"
                        f"> {settings.emojis.od} Idle: `{statuses['idle']}`\n"
                        f"> {settings.emojis.rd} DND: `{statuses['dnd']}`",
            color=Color(settings.colors.embed),
        )
        em.set_author(name="Member Count")
        await interaction.send(embed=em)
#

but i am using the same var

hushed galleon
pale zenith
full lily
#

Ok!

dry kelp
#

Yeah in fact

#

that was the issue, there was none

pale zenith
#

is _memberStatusStats a collections.Counter subclass? or something

#

you should be able to that_thing.setdefault('idle', 0)

dry kelp
full lily
#

I'm having a problem atm with discord registering my commands. Not sure what's up there. I've called self.bot.tree.sync() a few times. There doesn't seem to be an error

dry kelp
#

Well lambda should do detect all the members including bots statutes

#

It just randomly sends them, that makes it weird

pale zenith
#

you could also do x= {'idle': 0, ....}
x.update(dict(map(.....)))

dry kelp
#

mmmmm

pale zenith
#

so all have a default of 0 even if there aren't any

hushed galleon
full lily
#

Alright it just started to work again. Not sure what I changed

dry kelp
pale zenith
#

nope, that function that uses groupby()

full lily
#

I've been syncing via command. I am guessing I misconfigured one of the slash command signatures or whatever and it didn't error out for me

dry kelp
#

ahhh

#

Yeah but look at this

hushed galleon
#

so try indexing it with disnake.Status.idle instead

pale zenith
#

but you could also use a collections.Counter which returns 0 for empty keys

dry kelp
#

i hate statuses omfg

pale zenith
#

return collections.Counter(guild.members, key=lambda m: m.status)

#

:) ez as

hushed galleon
#

dang i didnt know counter had a key function

#

oh, it doesn't seem to

#

!d collections.Counter

unkempt canyonBOT
#

class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) subclass for counting [hashable](https://docs.python.org/3/glossary.html#term-hashable) objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) class is similar to bags or multisets in other languages.

Elements are counted from an *iterable* or initialized from another *mapping* (or counter):

```py
>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args
dry kelp
pale zenith
#

it's a built-in python module

#

docs above ^^

dry kelp
#

Oh nice

pale zenith
#

return collections.Counter([m.status for m in guild.members]) *would be appropriate

#

it would be soo nice if it had one, though

#

but I guess you accomplish the same with a listcomp/map so it doesn't really matter lol

hushed galleon
#

mhm

pale zenith
#

counter[anything that's not counted] will give 0, rather than raising a KeyError

dry kelp
#

crap that's not what i need

#

My problem is that it also randomize the numbers, or i can't tell where they come from

pale zenith
#

🤔

dry kelp
#

commands using the same variable

#

no members switched in that second

pale zenith
#

i have no idea what groupby() is or what it does. It could be that what messes it up

hushed galleon
dry kelp
#
    @guild.sub_command()
    async def members(self, interaction: CommandInteraction):
        """
        List server members
        """

        humans = len(list(filter(lambda m: not m.bot, interaction.guild.members)))
        bots = len(list(filter(lambda m: m.bot, interaction.guild.members)))

        statuses = _memberStatusStats(interaction)

        em = Embed(
            description=f"> {settings.emojis.members} Humans: `{humans}`\n"
                        f"> {settings.emojis.bots} Bots: `{bots}`\n"
                        f"> {settings.emojis.gd} Online: `{statuses['online']}`\n"
                        f"> {settings.emojis.wd} Offline: `{statuses['offline']}`\n"
                        f"> {settings.emojis.od} Idle: `{statuses['idle']}`\n"
                        f"> {settings.emojis.rd} DND: `{statuses['dnd']}`",
            color=Color(settings.colors.embed),
        )
        em.set_author(name="Member Count")
        await interaction.send(embed=em)
#
            .add_field(
                name=f"{settings.emojis.activity} Status",
                value=f"{settings.emojis.reply} {settings.emojis.gd} "
                      f"`{statuses['online']}`\n"
                      f"{settings.emojis.reply} {settings.emojis.od} "
                      f"`{statuses['offline']}`\n"
                      f"{settings.emojis.reply} {settings.emojis.rd} "
                      f"`{statuses['idle']}`\n"
                      f"{settings.emojis.reply} {settings.emojis.wd} "
                      f"`{statuses['dnd']}`\n",
            )
#

this is inside guild info

#

wait i did mess them up

dry kelp
graceful ermine
#

!pastebin

dry kelp
graceful ermine
#

Hey how can I fix this error?

https://paste.pythondiscord.com/W2KA

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\Desktop\Partner Bot\cogs\setup.py", line 106, in setup
    overwrite = pschannel.overwrites_for(self.bot.user.id)
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 587, in overwrites_for
    if overwrite.id == obj.id:
                       ^^^^^^
AttributeError: 'int' object has no attribute 'id'

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

Traceback (most recent call last):
  File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'setup' raised an exception: AttributeError: 'int' object has no attribute 'id'```
dry kelp
#

that number has no attribute for id

untold heart
#

noice an other spooky bot

dry kelp
#

i had 1 verified but i quit for a while tbh

untold heart
#

my bot is also called spooky

pale zenith
untold heart
#

but it is created in js

final iron
#

Nice token

sly hamlet
#

It's not the same one as that's currently being used

sly hamlet
final iron
#

It did

#

You're using a different environment than you installed into

#

run py -0

sly hamlet
final iron
#

Oh linux

#

Prefix it with whatever you prefix your install with instead of py

#

Oh I'm not even sure that commnad exists on Linux

sly hamlet
#

Yeah it still says it's not a command

#

It also says the installation is satisfied for discord.py

final iron
#

No clue how to check the system interpreters on Linux

sly hamlet
#

No idea but it's definitely installed

final iron
#

Well yes, but as previously mentioned you're using a different environment than you're installing into

#

This issue was solved in an update about a year ago

vale wing
#

@sly hamlet are you on vps or just coding on linux

summer axle
#

how do i can do music bot queue any tips?

summer axle
naive briar
#

Which part of it?

upbeat otter
#

using > before a sentence makes that sort of styling

sullen chasm
#
async def beans(interaction:discord.Interaction, user:discord.Member):
    await interaction.response.send_message("Succesfully sent Beans message", ephemeral=False)
    await interaction.channel.send(f"Beans {user.mention}!") ```
its not showing up as a /command
#

does anyone know how to fix?

pale zenith
sullen chasm
#

im not sure

#

how do i do?

pale zenith
sullen chasm
#

ok thanks

frail perch
hushed galleon
unkempt canyonBOT
hushed galleon
#

find the tags you want there, then use the applied_tags= argument when you're creating/editing a forum thread

frail perch
hushed galleon
little perch
#

I Made a simple oauth callback it works and saves the discord user information but i want to give the user in my a role in my discord after completing the oauth2 how can i do this

nova hawk
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s handle (e.g. `name` or `name#discriminator`).
slate swan
#

the attributes changed in 2.0 update

#

its now avatar.url

nova hawk
little perch
#

I Made a simple oauth callback it works and saves the discord user information but i want to give the user in my a role in my discord after completing the oauth2 how can i do this

proud wolf
#

Hello, I need some help. I'm trying to create a music bot in Python using ffmpeg and yt_dlp. However, when I use the command !play url, the bot joins the call, stays for about 5 seconds, and then disconnects. I can't figure out how to resolve this issue, please help.

Information appearing in the console after executing the !play command:

[2024-01-16 19:05:09] [INFO ] discord.voice_client: Starting voice handshake... (connection attempt 1)
[2024-01-16 19:05:10] [INFO ] discord.voice_client: Voice handshake complete. Endpoint found brazil9229.discord.media
[youtube] Extracting URL: https://www.youtube.com/watch?v=HJsv2IAYhkA
[youtube] HJsv2IAYhkA: Downloading webpage
[youtube] HJsv2IAYhkA: Downloading ios player API JSON
[youtube] HJsv2IAYhkA: Downloading android player API JSON
[youtube] HJsv2IAYhkA: Downloading m3u8 information
[2024-01-16 19:05:24] [INFO ] discord.player: ffmpeg process 13292 successfully terminated with a return code of 4294967274.
[2024-01-16 19:05:24] [INFO ] discord.voice_client: Disconnecting from voice normally, close code 1000.
[2024-01-16 19:05:24] [INFO ] discord.voice_client: The voice handshake is being terminated for Channel ID 1147392369130475633 (Guild ID 1147392368648126504)```
#

Code:

async def play(ctx, url):
    # Verifica se o bot está em um canal de voz
    if not ctx.author.voice or not ctx.author.voice.channel:
        await ctx.send('Você precisa estar em um canal de voz para usar esse comando!')
        return

    # Obtém o canal de voz do autor da mensagem
    channel = ctx.author.voice.channel

    # Conecta ao canal de voz
    vc = await channel.connect()

    try:
        # Cria uma instância do cliente yt_dlp
        ydl = yt_dlp.YoutubeDL()

        # Extrai informações do vídeo
        info = ydl.extract_info(url, download=False)
        url2 = info['formats'][0]['url']

        # Adiciona opções para o FFmpeg
        options = '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'

        # Inicia a reprodução de áudio no canal de voz
        vc.play(discord.FFmpegPCMAudio(url2, options=options))

        # Aguarda o término da reprodução antes de desconectar
        while vc.is_playing():
            await asyncio.sleep(1)

    except Exception as e:
        print(f"Erro ao reproduzir áudio: {e}")
    
    finally:
        # Desconecta do canal de voz
        await vc.disconnect()```
drifting arrow
#
    @commands.Cog.listener()
    async def on_raw_member_remove(self, payload):
        guild_id = payload.guild.id
        user_id = payload.user.id
        await fun.approve_user(user_id=user_id, guildid=guild_id, approved=False)
``` why isnt this working? 🤔
sick birch
#

depends on what "not working" means here

drifting arrow
#
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\site-packages\discord\client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Gnome\Desktop\adminmaster\cogs\private_commands.py", line 109, in on_raw_member_remove
    guild_id = payload.guild.id
AttributeError: 'RawMemberRemoveEvent' object has no attribute 'guild'
``` ;-;
golden portal
#

!d discord.RawMemberRemoveEvent.guild_id

unkempt canyonBOT
drifting arrow
#

ofc it's straight "guild_id" and not "guild.id"

sick birch
#

which is unfortunately not the case

drifting arrow
#

;-;

#

This is why we cant have nice things.

sick birch
#

on_member_remove gives you nice objects but only if they're cached

drifting arrow
#

lies I tell you, random member uncached leaves and it all breaks

#

the matrix is broken

graceful ermine
#

Hey, how can I fix this error?

File "C:\Users\berka\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Cooldown.init() takes 3 positional arguments but 4 were given

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

Traceback (most recent call last):
File "C:\Users\berka\Desktop\Partner Bot\main.py", line 392, in load
await bot.load_extension(f"cogs.{ext[:-3]}")
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.partner' raised an error: TypeError: Cooldown.init() takes 3 positional arguments but 4 were given

I'm trying to make my custom cooldown

Code:



    async def is_premium(self, guild_id):
        self.bot.db4 = await aiosqlite.connect(database="Database/premium.db")
        async with self.bot.db4.cursor() as cursor:
            await cursor.execute("SELECT guild FROM premium WHERE guild = ?", (guild_id,))
            guild = await cursor.fetchone()
            return guild is not None

    class PremiumBypassCooldown(commands.Cooldown):
        def __init__(self, rate, per, premium_check):
            super().__init__(rate, per, commands.BucketType.guild)
            self.premium_check = premium_check

        async def update_rate_limit(self, current=None):
            guild_id = self._bucket_key
            if await self.premium_check(guild_id):
                return None
            return super().update_rate_limit(current)
        
 @app_commands.commands.command(name="partner", description="Partner with this guild to another guild")
    @app_commands.checks.cooldown(1, 120, type=PremiumBypassCooldown(per=1, rate=120, premium_check=is_premium))    
    @app_commands.checks.bot_has_permissions(send_messages=True)
    async def partner(self, interaction: discord.Interaction, guild_id: str):```
hushed galleon
unkempt canyonBOT
#

discord/app_commands/checks.py line 91

def __init__(self, rate: float, per: float) -> None:```
hushed galleon
#

the cooldown check for app commands also only takes a key= function, what you want instead is the dynamic cooldown decorator

#

!d discord.app_commands.checks.dynamic_cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.dynamic_cooldown(factory, *, key=...)```
A decorator that adds a dynamic cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.

If a `factory` function is given, it must be a function that accepts a single parameter of type [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown) or `None`. If `None` is returned then that cooldown is effectively bypassed.

Both `key` and `factory` can optionally be coroutines.
graceful ermine
# hushed galleon dpy 2.0 changed how cooldowns were implemented so now commands.Cooldown is an al...

Update: I got the gist on how to make dynamic cooldowns but I have a different problem and the problem is filling in the arguments that I made for the dynamic_cooldown function that I made

@app_commands.commands.command(name="partner", description="Partner with this guild to another guild")
    @app_commands.checks.dynamic_cooldown(lambda interaction, self: self.is_premium(interaction=interaction, self=self))
    @app_commands.checks.bot_has_permissions(send_messages=True)```

```py

async def is_premium(self, interaction: discord.Interaction) -> [app_commands.Cooldown]:
        
        self.bot.db4 = await aiosqlite.connect(database="Database/premium.db")
        async with self.bot.db4.cursor() as cursor:
            await cursor.execute("SELECT guild FROM premium WHERE guild = ?", (interaction.guild.id,))
            guild = await cursor.fetchone()

            if guild:
                return None
            else:
                return app_commands.Cooldown(1, 180)
#

!pastebin

#

Error^