#discord-bots

1 messages ยท Page 196 of 1

slate swan
#

how to fix anyone?

lyric sphinx
#

you arent running the bot tho?

#

also, how are you trying to run the file?

naive briar
#

They're in Python repl

slate swan
#

im very new to coding

naive briar
#

Type exit() or ctrl+d to get out

lyric sphinx
#

yeah and then dont forget to client.run("YOURTOKEN") in your code

slate swan
#

okay 2 secs

slate swan
lyric sphinx
#

show the code? you can delete the token

unkempt canyonBOT
#

Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discord.com/developers/applications

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

slate swan
#

bruh

lyric sphinx
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

slate swan
#

python paste bin

#

!paste bin

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.

lyric sphinx
#

well, your code isnt large, so you could just paste it as a code block

slate swan
naive briar
#

I just said you're in the Python repl

slate swan
#

import discord
from discord.ext import commands

client = commands.bot(command_prefix="=", intents=discord.Intents.all())

@client.event
async def on_ready():
print("Success bot it ready")

client.run("")

lyric sphinx
#

seems like you are still in the repl, yep

naive briar
#

Exit it before running

lyric sphinx
#

because the code is fine

#

type exit() in the terminal

slate swan
lyric sphinx
#

i guess you need capital B instead of b

slate swan
lyric sphinx
#

commands.Bot

thin raft
#

Bot

slate swan
#

thank you guys

lyric sphinx
#

๐Ÿ‘

naive briar
#

You just sent your token

maiden fable
#

Nice

young dagger
#

Is this code correct?

if len(current_players) == 10 and after.member not in current_players:
    if after.member not in queue:
        queue.append(after.member)
    await after.member.disconnect()
else:
    current_players.append(after.member)```
#

Should I use else: or add member to current players if current players is less then 10 and member is not in current players list

vale wing
#

= 10 is safer

slate swan
#
    if member == None:
        em1=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please mention a member!", color=nextcord.Color.red())
        await ctx.send(embed=em1)
        return
    elif time == None:
        em2=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please set the time!", color=nextcord.Color.red())
        await ctx.send(embed=em2)    
        time=convert(time)
    
        return

    elif member == ctx.author:
        em3=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") You can't mute yourself!", color=nextcord.Color.red())
        await ctx.send(embed=em3)  
        
        return



    elif muterole == None:
        await ctx.send("No muterole has been setup for this server!")

        return

    elif muterole in member.roles:
        embed=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") This member is already muted!", color=nextcord.Color.red())
        await ctx.send(embed=embed) 
    else:```

```  File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 121, in mute
    elif muterole == None:
UnboundLocalError: local variable 'muterole' referenced before assignment```
#

know what the error means

young dagger
#
        if len(current_players) >= 10 and member not in current_players:

            if member not in queue:
                queue.append(member)

            await member.move_to(None)

        elif member not in current_players:
            current_players.append(member)```
slate swan
#

but like thats weird i didnt understand

young dagger
vale wing
young dagger
vale wing
vale wing
slate swan
#

how do i fix it

vale wing
#

Could you show full code

slate swan
#

yeah

vale wing
slate swan
#
@bot.command()
@commands.has_permissions(administrator=True)
async def muterole(ctx, role_: nextcord.Role = None):
    if role_ ==None:
        await ctx.send("Mention a role!")
    else:
        async with aiosqlite.connect("main.db") as db:
            async with db.cursor() as cursor:   
                await cursor.execute('SELECT role_id FROM mute WHERE guild = ?', (ctx.guild.id,))
                role = await cursor.fetchone()
                if role:
                    await cursor.execute('UPDATE mute SET role_id = ? WHERE guild = ?', (role_.id, ctx.guild.id,))
                else:
                    await cursor.execute('INSERT INTO mute (role_id, guild) VALUES (?, ?)', (role_.id, ctx.guild.id,))
            await ctx.send(f"Successfuly set the mute role to - {role_.mention}")
            await db.commit()

def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d": 86400}

    unit = time[-1]

    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2
    return val * time_dict[unit]

@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time: convert = None, *, reason=None):    
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT role_id FROM mute WHERE guild = ? AND time = ?', (ctx.guild.id, time,))
            role_id = await cursor.fetchone()
            if role_id:
                muterole = ctx.guild.get_role(role_id)
                
    if member == None:
        em1=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please mention a member!", color=nextcord.Color.red())
        await ctx.send(embed=em1)
        return
    elif time == None:
        em2=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please set the time!", color=nextcord.Color.red())
        await ctx.send(embed=em2)    
        time=convert(time)
    
        return

    elif member == ctx.author:
        em3=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") You can't mute yourself!", color=nextcord.Color.red())
        await ctx.send(embed=em3)  
        
        return



    elif muterole == None:
        await ctx.send("No muterole has been setup for this server!")

        return

    elif muterole in member.roles:
        embed=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") This member is already muted!", color=nextcord.Color.red())
        await ctx.send(embed=embed) 
    else:


        await member.add_roles(muterole)
    
    emmu = nextcord.Embed(
            color=nextcord.Colour.green(),
            title='![Vi](https://cdn.discordapp.com/emojis/1072123034099519519.webp?size=128 "Vi") Muted Success')
    emmu.add_field(name=f"__**Moderation:**__", value=ctx.author.mention, inline = False)
    emmu.add_field(name=f"__**Member:**__", value=member, inline = False)
    emmu.add_field(name=f"__**Time:**__", value=time, inline = False)
    emmu.add_field(name=f"__**Reason:**__", value=reason, inline = False)

    emmu.set_footer(text=f'Muted by {ctx.author}')
    await ctx.send(embed=emmu)
    await member.remove_roles(time=time)```
vale wing
#

Yeah

slate swan
#

wdymn

vale wing
#

If role_id is None, muterole will never be assigned

#

You need to ensure it is always defined, for example you can add muterole = None before making a query

vale wing
#

And yeah you should have one db connection for bot

#

Creating a connection is expensive and you can just use one for everything

slate swan
vale wing
vale wing
# slate swan

The way you added it here will make it so it is always None lol

slate swan
#

if muterole = None
....

vale wing
#

And still will be undefined if role_id is none

#

I mean it should be like py muterole = None role_id = await query(...) # pseudo if role_id is not None: muterole = get_role(role_id)

slate swan
vale wing
#

No

slate swan
#

oh

vale wing
#

Comparisons to None and bools should be done with is keyword

slate swan
#

oh okay

vale wing
#

For pure bool it's just if obj and if not obj, for bool | None it's is too

#

For None it's always is

slate swan
#

tysmmmm

young dagger
unkempt canyonBOT
#

Hey @tired notch!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

tired notch
ebon island
#

What's the proper means to invite or remove users from Stage? I see request_to_speak but not immediately obvious how to use it since it has no args so I'm not entirely sure on how to implement, any info/examples would be great ๐Ÿ™‚ I'm using Disnake btw

torn sail
#

how do i make a global app command check?

#

and also can a followup be a normal message if the interaction was deffered ephemerally?

slate swan
#
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time: convert = None, *, reason=None):    
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT role_id FROM mute WHERE guild = ? AND time = ?', (ctx.guild.id, time,))
            role_id = await cursor.fetchone()
            if role_id:
                muterole = ctx.guild.get_role(role_id)
                muterole = None
            if role_id is not None:
                muterole = ctx.guild.get_role(role_id)  
                        
    if member == None:
        em1=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please mention a member!", color=nextcord.Color.red())
        await ctx.send(embed=em1)
        return
    elif time == None:
        em2=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please set the time!", color=nextcord.Color.red())
        await ctx.send(embed=em2)    
        time=convert(time)
    
        return

    elif member == ctx.author:
        em3=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") You can't mute yourself!", color=nextcord.Color.red())
        await ctx.send(embed=em3)  
        
        return



    elif muterole == None:
        await ctx.send("No muterole has been setup for this server!")

        return

    elif muterole in member.roles:
        embed=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") This member is already muted!", color=nextcord.Color.red())
        await ctx.send(embed=embed) 
    else:


        await member.add_roles(muterole)
    
    emmu = nextcord.Embed(
            color=nextcord.Colour.green(),
            title='![Vi](https://cdn.discordapp.com/emojis/1072123034099519519.webp?size=128 "Vi") Muted Success')
    emmu.add_field(name=f"__**Moderation:**__", value=ctx.author.mention, inline = False)
    emmu.add_field(name=f"__**Member:**__", value=member, inline = False)
    emmu.add_field(name=f"__**Time:**__", value=time, inline = False)
    emmu.add_field(name=f"__**Reason:**__", value=reason, inline = False)

    emmu.set_footer(text=f'Muted by {ctx.author}')
    await ctx.send(embed=emmu)
    await member.remove_roles(time=time)


still the same error

    elif muterole == None:
UnboundLocalError: local variable 'muterole' referenced before assignment```
cold sonnet
#
            if role_id:
                muterole = ctx.guild.get_role(role_id)
                muterole = None
            if role_id is not None:
                muterole = ctx.guild.get_role(role_id)  
slate swan
#

ik its wrong

#

but like idk

zinc pollen
#

oh hey mudkip! lol

#

Hey, @smoky sinew I was thinking about the code last night, and instead of the second pull, do i need to chance that to a slash>

smoky sinew
#

mb i'm about to go out

zinc pollen
#

you're good. Just tryin to think about why commands aren't appearing lol

#

I made a help page too so I may get someone there

ionic garden
#

why are icons not showing

gentle nova
#

hey, anyone know mongo things ?

slate swan
ebon island
gentle nova
#

File "c:\Users\ovis\OneDrive\Desktop\Discord-Economy-Bot-main\Discord-Economy-Bot-main\Systems\Economy.py", line 21, in <module>
with open("Configs/config.yml", "r", encoding="utf-8") as file: any idea ?

smoky sinew
#

that's not even like 1/3 of the error

naive briar
#

Relatable

gentle nova
#

@smoky sinewfound out what's was wrong

normal current
#

hello , i'm trying to get my bot online , but everytime i run the code , nothing happens , no errors and the bot isn't online , if anyone has any idea on what to do that'd be great!

normal current
# smoky sinew share your code

` import discord
import responses

send messages

async def send_message(message, user_message, is_private):
try:
reponse = responses.handle_response(user_message)
await message.author.send(response) if is_private else await message.channel.send(response)

except Exception as e:
    print(e)

def run_discord_bot():
TOKEN = 'token'

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

@client.event
async def on_ready():
    print(f'{client.user} is now running!')

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

    username = str(message.author)
    user_message = str(message.content)
    channel = str(message.channel)

    print(f'{username} said: "{user_message}" ({channel})')

    if user_message[0] == '?':
        user_message = user_message[1:]
        await send_message(message, user_message, is_private=True)
    else:
        await send_message(message, user_message, is_private=False)

    client.run(TOKEN)

`

smoky sinew
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

smoky sinew
#

well you're not even running the discord bot function

#

but it wouldn't work anyway since you can't do async stuff inside an synchronous function

normal current
#

i did that in another .py file

#

`import bot

if name == 'main':
bot.run_discord_bot()
`

smoky sinew
normal current
normal current
#

i followed a tuto

naive briar
smoky sinew
#

just remove the functions

#

or make it async

normal current
smoky sinew
#

don't follow tutorials

normal current
smoky sinew
#

yes

#

well both of them actually

normal current
#

send_message is already async

naive briar
#

You didn't even run the bot to begin with

zinc pollen
#

he help channels don't last very long do they? lol

#

I am looking for a way to give a role after a reaction, but they first have to enter a gamertag or PSN (This doesn't have to be verified, just something entered into the field). This is what I have so far, but there are no commands appearing when the bot goes live and I don't know where to go from here. Eventually I want a database to hold all of the information as well.

#

Thats what I have so far

#

Mudkip was helping me but I fear im stressing him out lol

smoky sinew
smoky sinew
# zinc pollen

try this maybe:

@commands.is_owner()
@client.command()
async def sync(ctx):
    await client.tree.sync()
naive briar
#

They still didn't add the command to the bot instance

zinc pollen
#

Thats what I thought when I was looking at it lol

#

But im fairly new so I wasn't entirely sure

smoky sinew
#

i thought the decorator took care of that

#

so bot.add_command i guess?

regal galleon
naive briar
smoky sinew
#

ah i see

naive briar
#

This does not

naive briar
#

Don't sync in on_ready

smoky sinew
# zinc pollen

replace app_commands.command with client.tree.command i guess then

regal galleon
#

It's easy

smoky sinew
#

In my time as Helper, I see people syncing their CommandTree in the on_ready_event or in the new setup_hook entrypoint method. I do not advise this personally, it can lead to footguns if you aren't prepared. For examples, if you sync your tree before you load your extensions (which have your application commands), then you're effectively syncing an empty tree to Discord, which will wipe your commands. If you sync your tree and then make changes, you rely on the autosync and forget to sync changes, resulting in errors and failing commands.

#

@regal galleon

#

just make a message command to sync

gentle nova
#

Got discord bot source code from github, trying to run it but getting errors, everything look's fine but dont get it

#

raise CommandNotFound(name, parents)
discord.app_commands.errors.CommandNotFound: Application command 'balance' not found

regal galleon
gentle nova
#
**    @commands.command(aliases=['bal', 'money', 'profile'])
    async def balance(self, ctx, member: discord.Member = None):
        if member is None:
**```
smoky sinew
gentle nova
#

So where to find a solution

smoky sinew
#

run the message command instead of the application command?

gentle nova
#

Something is wrong, prefix is ! , but message command can run with /

smoky sinew
#

it shouldn't

#

just run it with !balance

gentle nova
#

discord.ext.commands.errors.CommandNotFound: Command "balance" is not found getting this then

smoky sinew
#

is the cog loaded

gentle nova
#

with / show's everything whats loaded i think so

#

and getting this c:\ekonomika\main.py:83: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f"Commands.{fn[:-3]}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
c:\ekonomika\main.py:87: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f"Systems.Economy")

#
logging.info("------------- Loading -------------")
for fn in listdir("Commands"):
    if fn.endswith(".py"):
        logging.info(f"Loading: {fn}")
        client.load_extension(f"Commands.{fn[:-3]}")
        logging.info(f"Loaded {fn}")

logging.info(f"Loading: Economy System")
client.load_extension(f"Systems.Economy")
logging.info(f"Loaded Economy System")

logging.info("------------- Finished Loading -------------")
smoky sinew
#

yeah, you need to await that

#

in 2.0 it's now a coroutine

gentle nova
#

Hard to make it works atleast to test everything ?

#

Cuz im noob at coding

smoky sinew
#

you're running a kind of outdated bot

gentle nova
#

Sad

#

Its hard to update it ? Or not worth even try ?

smoky sinew
#

not hard

#

im just wondering where you found this bot

gentle nova
#

github

smoky sinew
#

read this

gentle nova
#

so basically i need change alot

trail chasm
#

TypeError: Command.error() missing 1 required positional argument: 'coro'

#

the error poped up after pasted the kick.error command

#

purge.error command is running without problem

zinc pollen
#

yeah, so my commands still aren't working

#

not showing up

trail chasm
#

i feel that means there is a multiple events

#

what does it mean

zinc pollen
#

This is what I got so far, commands still aren't showing up

trail chasm
#

write bot instead client, i've never seen the client codes works so far

#

it pops up the error

#

as i observed

zinc pollen
#

I have no error running the bot itself, the commands just don't show up

naive briar
zinc pollen
#

nope

#

as I said im pretty new lol

#

mudkip has been walking me through it the best he can lol

#

if you think of a fix please dm me ๐Ÿ™‚ I have to head out for a bit but I would love to communicate about what you think would help!

trail chasm
#

thank you

#

i spent 6 hours

#

on coding, thats why i didnt see

#

lol 8 hours

slate swan
#

if anyone can help im trying to make a bot that reacts with an emoji to a specific user after i say something like "!nerd (user) and then itll wait for them to send a message and react with the emoji ive choosed, ive got most of the code down but i have no idea how to make it wait for the specific user to send the message, and it just reacts to the message i send

trail chasm
slate swan
#

is there any way to gen keys in discord.py using keyauth?

#
    await member.remove_roles(time=time)
TypeError: remove_roles() got an unexpected keyword argument 'time'```

```py
        await member.add_roles(muterole)
    
    emmu = nextcord.Embed(
            color=nextcord.Colour.green(),
            title='![Vi](https://cdn.discordapp.com/emojis/1072123034099519519.webp?size=128 "Vi") Muted Success')
    emmu.add_field(name=f"__**Moderation:**__", value=ctx.author.mention, inline = False)
    emmu.add_field(name=f"__**Member:**__", value=member, inline = False)
    emmu.add_field(name=f"__**Time:**__", value=time, inline = False)
    emmu.add_field(name=f"__**Reason:**__", value=reason, inline = False)

    emmu.set_footer(text=f'Muted by {ctx.author}')
    await ctx.send(embed=emmu)
    await member.remove_roles(muterole,time=time)```
smoky sinew
#

you can't just make up an argument

#

!d discord.Member.remove_roles

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s from this member.

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

defined what

slate swan
#

as a parameter

#

time

smoky sinew
#

how??

slate swan
smoky sinew
#

how did you define it

slate swan
#

time: convert = None

smoky sinew
#

? show the code

ebon island
#

Do you guys know what the deal with Stages is atm? Is it something Discord will continue to be developing? I saw on a larger server they had a Stage with Video and a Chat Channel, are those features which we can confidently expect to be made available? I'm not sure if that's somehow functionality limited to boosted servers or something, just want more info on them so I can better understand what to expect in terms of the continued development and implementation of the feature

slate swan
#

why my function is not detected by the code?

#
    async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):
        not_failure = True
        try:
            indice = []
            cont = 0
            for indz in args:
                if indz == "+" or indz == "-" or indz == "*" or indz == "/":
                    indice.append([cont,cont+1], indz)
                    cont = cont+1

            args_result = args.split('+', '-', "*", "/")
            total = 0
            ind = 0
            for y in args_result:
                if "#" in y:
                    ind = ind + 1
                    if y != args_result[0]:
                        not_failure = False
                        break
                    if ind > 1:
                        break
            
            if not_failure:
                store = []
                if "#" in args_result[0]:
                        mark = args_result.split('#')
                        args_result[0] = mark[1]
                        mark.pop(1)
                        for z in range(0, mark):
                            resp_sub = f"{z}#"
                            for x in args_result:
                                resp_sub = + f"{indice} {args_result[x]} {sub_roll(args_result[x])}"
#
                            resp_sub = + "\n"
                else:
                    for x in args_result:
                        resp_sub = + f"{indice} {args_result[x]} {sub_roll(args_result[x])}"
                        store.append(sub_roll(args_result[x]))
            
                sub_total = 0
                for count, clock in enumerate(indice):
                    if clock == "*":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] * store[pos2]
                        for ntz in range (count,store):
                            indice[ntz][0] = indice[ntz][0]-1
                            indice[ntz][1] = indice[ntz][1]-1
                        indice.pop(count)
                        store.remove(indice[count][0], ```
#
                            
                for count, clock in enumerate(indice):
                    if clock == "/":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] / store[pos2]
                        for ntz in range (count,store):
                            indice[ntz][0] = indice[ntz][0]-1
                            indice[ntz][1] = indice[ntz][1]-1
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
                    
                for clock in indice:
                    if clock == "+":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] + store[pos2]
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
                    if clock == "-":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] - store[pos2]
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
                total = sub_total

            resp_total = resp_sub + f"\n{total}"

        except:
            not_failure = False
        
        if not_failure:
            await ctx.send(resp_total)
        else:
            await ctx.send("Error! Arguments invalid")
fast vortex
slate swan
#

this is my function:

        result = []
        total = 0
        meta = []
        if "d" in inp:
            res = inp.split('d')
            sub_r = []
            z = 0
            while(z < res[0]-1):
                if res[1] == "f" or res[1] == "F":
                    sub_r.append(random.randint(1, 6))
                    if sub_r == range (1, 2):
                        sub_r[z] = "-"
                    elif sub_r == range (3,4):
                        sub_r[z] == "0"
                    else:
                        sub_r[z] == "+"
                else:
                    sub_r.append(random.randint(1, res[1]))
                z = z+1
            result = sub_r

        for x in result:
            total = total+x
        
        meta.append(result, total)
        return meta```
fast vortex
slate swan
#

roll

#

same file

#

and same class

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

fast vortex
slate swan
#

yes

fast vortex
#

Then do self.sub_roll

slate swan
#

oh i see

fast vortex
#

Whenever you wanna use a function you made inside the same class as the command add a self. in front of it

slate swan
#

why my code is not working?

#

isntead of run the code it just says arguments invalid

#

guess it's because i need to convert string to number

slate swan
#
@commands.command()
    async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):
        not_failure = True
        try:
            indice = []
            cont = 0
            for indz in args:
                if indz == "+" or indz == "-" or indz == "*" or indz == "/":
                    indice.append([cont,cont+1], indz)
                    cont = cont+1

#
            args_result = args.split("+", "-", "*", "/")
            total = 0
            for y in args_result:
                ind = 0
                if "#" in y:
                    ind = ind + 1
                    if y != args_result[0]:
                        not_failure = False
                        break
                    if ind > 1:
                        break
            
            if not_failure:
                store = []
                if "#" in args_result[0]:
                        mark = args_result.split('#')
                        args_result[0] = mark[1]
                        mark.pop(1)
                        for z in range(0, mark):
                            resp_sub = f"{z}#"
                            roll_result = self.sub_roll(args_result[x])
                            for x in args_result:
                                resp_sub = + f"{indice} {args_result[x]} {roll_result}"
                                store.append(roll_result[1])
                            resp_sub = + "\n"
                else:
                    for x in args_result:
                        roll_result = self.sub_roll(args_result[x])
                        resp_sub = + f"{indice} {args_result[x]} {roll_result}"
                        store.append(roll_result[1])
            
                sub_total = 0
                for count, clock in enumerate(indice):
                    if clock == "*":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] * store[pos2]
                        for ntz in range (count,store):
                            indice[ntz][0] = indice[ntz][0]-1
                            indice[ntz][1] = indice[ntz][1]-1
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
#
                            
                for count, clock in enumerate(indice):
                    if clock == "/":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] / store[pos2]
                        for ntz in range (count,store):
                            indice[ntz][0] = indice[ntz][0]-1
                            indice[ntz][1] = indice[ntz][1]-1
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
                    
                for clock in indice:
                    if clock == "+":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] + store[pos2]
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
                    if clock == "-":
                        pos1 = indice[count][0]
                        pos2 = indice[count][1]
                        sub_total = sub_total + store[pos1] - store[pos2]
                        indice.pop(count)
                        store.remove(indice[count][0], indice[count][1])
                total = sub_total

            resp_total = resp_sub + f"\n{total}"

        except:
            not_failure = False
        
        if not_failure:
            await ctx.send(resp_total)
        else:
            await ctx.send("Error! Arguments invalid")
#

why it's just sending me a error message?

#

guess i need to provide more information

#

but how i do it?

wraith meteor
#

discord.sinks.WaveSink() - module 'discord' has no attribute 'sinks' Hi, how to make it grate?

wraith meteor
#
async def listen(ctx):
    if ctx.voice_client:
        ctx.voice_client.start_recording(discord.sinks.WaveSink(), callback, ctx)
        await ctx.send("listening...")
    else:
        await ctx.send("not in a voice channel!")


async def callback(sink: discord.sinks, ctx):
    for user_id, audio in sink.audio_data.items():
        if user_id == ctx.author.id:
            audio: discord.sinks.core.AudioData = audio
            print(user_id)
            filename = "audio.wav"
            with open(filename, "wb") as f:
                f.write(audio.file.getvalue())
            text = model.transcribe(filename)["text"]
            os.remove(filename)
            print(f"Received from {ctx.author.name}: {text}")
            reply = parse(text)
            print(f"Reply: {reply}")
            tts(ctx, reply)
# stops recording
@client.command()
async def stop(ctx):
    ctx.voice_client.stop_recording()

``` How write this on nextcord? thanks
graceful ermine
#

Hey How could I get multiple global error handlers?

#

this is my code so far

smoky sinew
#

also why are your classes lowercase

graceful ermine
smoky sinew
#

fix them

graceful ermine
smoky sinew
#

that can all be done in one error handler

graceful ermine
smoky sinew
#

by checking the type of error

graceful ermine
smoky sinew
#

yes??

#
Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.

    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.
#

look at what the third part says

slate swan
#

thats 3.10+ tho

#

or was it for the Union types

#

!d isinstance

unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised. [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") may not be raised for an invalid type if an earlier check succeeds.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
slate swan
#

yeah nvm

smoky sinew
#

do you have an error handler

fresh ferry
#

im getting intent errors and im at a lose on how to fix them

import os
import requests
import discord
from discord.ext import commands
from discord_webhook import DiscordWebhook

intents = discord.Intents.default()
intents.guild_messages = True
intents = discord.Intents.default()
intents.privileged_intents = discord.Intents.privileged

client = commands.Bot(command_prefix='!', intents=intents)

@client.event
async def on_ready():
    print(f'Bot is ready. Logged in as {client.user}')

not complete source... i know its an easy fix but i have brain fog atm ahha

slate swan
fresh ferry
#

so

intents = discord.Intents.default()
intents.privileged_intents = discord.Intents.privileged
slate swan
#

yea remove that

slate swan
fresh ferry
#

still getting this error

slate swan
fresh ferry
#

it still fails ?

slate swan
#

now you remove all 4 lines bruh

fresh ferry
#

now im getting this

deep osprey
#

How to send a message to a specific channel by its ID using slash command?

slate swan
slate swan
unkempt canyonBOT
#

get_partial_messageable(id, *, guild_id=None, type=None)```
Returns a partial messageable with the given channel ID.

This is useful if you have a channel\_id but donโ€™t want to do an API call to send messages to it.

New in version 2.0.
slate swan
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
deep osprey
#

thank you โค๏ธ

deep osprey
#
@bot.tree.error
async def on_app_command_error(error: app_commands.AppCommandError, interaction: discord.Interaction):
    if isinstance(error,app_commands.CommandOnCooldown):
        await interaction.response.send_message(f"You are on a cooldown, Try again in {error.retry_after} seconds!",ephemeral=True)
    else: raise error``` the cooldown works but it doesn't send the custom error msg, just "the app did not respond"
young lintel
#

does anyone knows how to make a /say command

#

that only allows some users to use it

#

aka the bot owner

shrewd apex
#

the same as default error for message commands

shrewd fjord
shrewd apex
shrewd fjord
#

Forgor the deco

#

sorry is_owner

slate swan
shrewd apex
slate swan
#

it's just the wrong argument order

shrewd apex
#

its morning i am still not awake

slate swan
#

interaction comes before error

slate swan
shrewd apex
slate swan
#

too busy these days

shrewd apex
smoky sinew
# young lintel that only allows some users to use it
@app_commands.is_owner()
@app_commands.describe(message = "The message to say.")
@app_commands.command()
async def say(self, interaction: discord.Interaction, message: str):
    await interaction.response.send_message(message)

..yes it's a slash command, cope lol

#

if you want a message command the syntax is similar though

young lintel
naive briar
#

It's already in the code

#

At least try to understand the code, not just copy and paste

smoky sinew
#

it only works for the bot owner

young lintel
# smoky sinew it already does

yes i mean like only person A and person B can use it not just the bot owner, also sorry if im just asking too much questions i forgot how to code

young lintel
#

alr

#

ty

slate swan
flat pier
slate swan
flat pier
#

you'll have to handle this yourself

slate swan
#

asycio.tasks()?

flat pier
#

but you can do something like a "future task", utilizing the tasks functionality in dpy
example from a tag in discord.py server:

@tasks.loop()
async def yourtask():
  # if you don't care about keeping records of old tasks, remove this WHERE and change the UPDATE to DELETE
  next_task = await db_conn.fetchrow('SELECT * FROM tasks WHERE NOT completed ORDER BY end_time LIMIT 1')
  # if no remaining tasks, stop the loop
  if next_task is None:
    yourtask.stop()

  # sleep until the task should be done
  await discord.utils.sleep_until(next_task['end_time'])

  # do your task stuff here with `next_task`

  # UPDATE the task to mark it completed, or DELETE it
  await db_conn.execute('UPDATE tasks SET completed = true WHERE row_id = $1', next_task['row_id'])

# add a `before_loop` and `wait_until_ready` if you need the bot to be logged in
yourtask.start()

# in a command that adds new task in db
if yourtask.is_running():
  yourtask.restart()
else:
  yourtask.start()
#

assuming when the "time is up" is a datetime you would check against

#

something simliar may work

slate swan
#

Thank you so much!!! Ill try

shrewd fjord
#

Well actually more easiest method is check if there is any column which rn lower than current time in timestamp if not return if yes delete the column from table and do the tasks

clear elm
#

How do I make the bot mention the channel in the embed? This is my code.

@bot.event
async def on_message_edit(message_before, message_after):
    channel = bot.get_channel(1063026363084316703)
    editlogEmbed = discord.Embed(title="", description="", color=0xFF5349)
    editlogEmbed.add_field(name="", value=f'A message sent by {message_before.author.mention} was edited in {message_before.channel}', inline=True)
    editlogEmbed.add_field(name="Before:", value=f'{message_before.content}', inline=False)
    editlogEmbed.add_field(name="After:", value=f'{message_after.content}', inline=False)
    editlogEmbed.set_footer(text=f'Message ID: {message_before.id} โ€ข Made by justin;#6868')
    editlogEmbed.set_author(name=f'{message_before.author}', icon_url = f'{message_before.author.display_avatar}')
    await channel.send(embed=editlogEmbed)```
clear elm
#

I thought I tried that- Anyways, thanks.

haughty dagger
#
msg = await interaction.followup.send(embed=embed)
thread = await msg.create_thread(name="Response Thread", auto_archive_duration=120)

I'm getting an error: This message does not have guild info attached.

#

Idk what's wrong here

slate swan
golden portal
haughty dagger
golden portal
haughty dagger
#

Wait let me try

haughty dagger
#

but why

golden portal
#

its None when its not in a guild channel

#

try printing msg.channel.type

haughty dagger
#

<PartialMessageable id=380957505221820416 type=None>

#

just tried

clear elm
#

how would i make a number go up by +1 every time the command is run

golden portal
#

hmm i see

haughty dagger
#

is it because the message is a followup message -> webhook

golden portal
#

hmm, iirc WebhookMessage should have the channel at least instead of a PartialMessageable

naive briar
#

Just create the thread from the channel that is from the interaction

#

Why does it have to be from a message

haughty dagger
#

I've tried using interaction.message.create_thread

golden portal
#

pretty much a shortcut i suppose, also, i guess it is indeed in a DM channel there

haughty dagger
naive briar
#

I said what

#

!d discord.Interaction.channel

unkempt canyonBOT
naive briar
#

What even is interaction.message yert
Never seen it before

haughty dagger
golden portal
#

whats your full code other than this

haughty dagger
naive briar
#

Not again

haughty dagger
#

I'm sending this to prove that it's a channel

#

not dm

golden portal
#

interaction.message wouldnt be filled by slash invoke btw

naive briar
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
haughty dagger
#

okay

haughty dagger
#

Idk interaction.user just works fine but interaction.message is None

naive briar
#

I don't see any use of that attr

#

And do your bot have guilds intent

haughty dagger
#

yes

#

you mean server members intent

naive briar
#

No

haughty dagger
#

then what

naive briar
#

What?

haughty dagger
naive briar
#

!d discord.Intents.guilds

unkempt canyonBOT
naive briar
#

I said what I said

haughty dagger
#

I've discord.Intents.default() so it is enabled by default

#

A factory method that creates a Intents with everything enabled except presences, members, and message_content.

#

I've a /serverinfo command that works just fine

gaunt ice
#

guys

#

i have the guild id i tried to get the guildwith get_guildbut it returns Nonetype and fetch_guild returns coroutine

golden portal
haughty dagger
golden portal
golden portal
vale wing
#

Why he shouldn't? If his cache is not enabled he should. Otherwise getch_guild or whatever it's named in dpy

golden portal
#

fetch_guild doesnt have the proper member/channel data

vale wing
#

No way discord gave me free nitro but I am in Russia ๐Ÿ’€

golden portal
#

requires chunking

vale wing
#

He didn't mention anything about members did he

golden portal
#

generally people would, but sure, its so incase they have any followups

glad cradle
radiant bough
#

oh my bad

#

async def send_bot_help(self, mapping):
        """triggers when a `<prefix>help` is called"""
        ctx = self.context
        embed = HelpEmbed(title=f"{ctx.me.name} Help")
        embed.set_thumbnail(url=ctx.me.avatar.url)
        usable = 0 

        for cog, commands in mapping.items(): 
            if filtered_commands := await self.filter_commands(commands): 
                
                amount_commands = len(filtered_commands)
                usable += amount_commands
                if cog: 
                    name = cog.qualified_name
                    description = cog.description or "No cog description"
                else:
                    name = "No Category"
                    description = "Commands with no category"

                
        embed.description = f" Thanks for using **Axntron**. \n  If you'd like to view help for commands, you can use ,help <command> and for more help you can join my [support server](). \n \n My prefix is `,`. \n \n `,help mod` \n> :**Useful Moderation Commands.** \n:icons: `,help dank` \n> :**Useful Dank Commands.** \n:Icons_utility: `,help utility` \n> :**Useful Utility Comands.** \n:fun: `,help fun` \n> :**Useful Fun Commands.** \n `,help admin` \n> :**Useful Admin Commands.** \n `,help CoolKidsClub` \n> :**Useful text modifying commands.**" 
        embed.color=0xffffff
        view = helpowo2()
        view.message = await self.send(embed=embed,view=view)
radiant bough
golden portal
radiant bough
#

client.help_command = MyHelp()

golden portal
#

hmm there should be at least 1 error there

golden portal
gaunt ice
#

forgot to chnage that

#

but doesnt this much api calls ratelimit the bot

slate swan
#

!d discord.Guild.system_channel

unkempt canyonBOT
#

property system_channel```
Returns the guildโ€™s channel used for system messages.

If no channel is set, then this returns `None`.
golden portal
#

also, there is no reason to censor your guild id, no one can do anything with it

slate swan
#

mm

#

this thing exists?

radiant bough
golden portal
golden portal
golden portal
radiant bough
#
If __name == โ€œ__main__โ€:
    client.run(token)
golden portal
#

i see, do you have an error handler? could be a suppressed error

final walrus
#

What are some decent ways of deploying discord bots ?

#

Railway looks pretty good to me

#

So far I've just been using a VPs with docker

radiant bough
final walrus
final walrus
#

Morbid curiosity

radiant bough
#

๐Ÿ’€ ** **

radiant bough
clear elm
#

Is it possible to make it so you can only choose one option from the select menu and after it's selected, it expires?

vale wing
#

I mean it already can be considered deployment, what exactly do you mean by "deploy"

golden portal
vale wing
#

See examples on your lib github repo

#

@radiant bough if you shared code before could you please reply to that message? If not, please send the code that does not work

vale wing
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
clear elm
radiant bough
# golden portal no global ones? particularly w/ on_command_error
@client.listen("on_command_error")
async def idk123(ctx, error):
  if isinstance(error, CommandNotFound):
        e = discord.Embed(description=f"Error: \nCommand sent by user not found.\n", color=discord.Colour.dark_theme())
        await ctx.reply(embed=e,delete_after=15)
  if isinstance(error, MissingPermissions):
        e = discord.Embed(description=f"Error: \nUser is not having the required permissions.\n", color=discord.Colour.dark_theme())
        await ctx.reply(embed=e)
naive briar
#

Is that all

golden portal
radiant bough
radiant bough
naive briar
#

Then un-handled errors wouldn't be visible

golden portal
#

may wanna re-raise/reprint errors such as this, ```py
if ...:

elif ...:

else:
raise error

radiant bough
#

What should I use to get my botโ€™s avatar url

naive briar
#

Normally

golden portal
#

!d discord.ClientUser.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the userโ€™s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.
golden portal
#

then just .url

golden portal
#

so did you get the error now? there should be a .send attr error in that help command

golden portal
#

i see

radiant bough
#

I had the default one

shrewd fjord
#

:-:

radiant bough
#

:-:

shrewd fjord
#

.-.

final walrus
#

i wasnt sure whether its common practice or not

vale wing
final walrus
#

but if vps is common I'll jhust stick to that

upbeat gust
static holly
#
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions

@commands.command()
@has_permissions(manage_message = True)
async def clear (self, ctx, amount):
  if amount == 0:
    await ctx.send ("Veuillez entrer un nombre de message a effacer.")
  elif amount >= 1:
    await ctx.channel.purge(limit=amount)
Traceback (most recent call last):
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\moderation.py", line 9, in <module>
    class moderation_cmd(commands.Cog):
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\moderation.py", line 87, in moderation_cmd
    @has_permissions(manage_message = True)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 2187, in has_permissions
    raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")
TypeError: Invalid permission(s): manage_message
golden portal
#

note that has_permissions or any other decorator involving permissions follows the discord.Permissions attribute

#

!d discord.Permissions.manage_messages

unkempt canyonBOT
#

Returns True if a user can delete or pin messages in a text channel.

Note

Note that there are currently no ways to edit other peopleโ€™s messages.

static holly
#

thank you.

golden portal
#

welcome zerotwoheartlove

static holly
shrewd fjord
unkempt canyonBOT
shrewd fjord
#

And
!d datetime.datetime.now

#

Eh?

#

!d datetime

unkempt canyonBOT
#

Source code: Lib/datetime.py

The datetime module supplies classes for manipulating dates and times.

While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

shrewd fjord
#

Use datetime.datetime.now() and conv to seconds and conv created_at to secs and minus it and check if the seconds is lower or upper than 14 days in seconds or simply use timedelta

strong knoll
#

Hey guys, How to make in discord module (slash commands):
A player enters a flight code, and some other, and if a player uses other command it will show.

upbeat gust
#

Save the code in a db, then just get that value

strong knoll
upbeat gust
#

No, do it yourself

strong knoll
upbeat gust
#

Do you need to keep this code even after restarting the bot?

#

If not, just use a variable

strong knoll
# upbeat gust Do you need to keep this code even after restarting the bot?

So I have that code:

Set Flight Command

@client.tree.command(name="setflight", description="Set's Next Flight")
@discord.ext.commands.has_role("")
async def setflight(flight_Code:str, Plane:str, AvabilableClasses:str, Departure:str, Arrival:str):

#Flight Command
@client.tree.command(name="flight", description="Check info about next flight!")
async def flight(Interaction:discord.Interaction):
embed = discord.Embed(title="Flight:", value="", color=0x800080)
embed.add_field(name="Flight Code:", value="", inline=False)
embed.add_field(name="Plane:", value="", inline=False)
embed.add_field(name="Avabilable Clases:", value="", inline=False)
embed.add_field(name="Departure:", value="", inline=False)
embed.add_field(name="Arrival:", value="", inline=False)
await Interaction.response.send_message(embed=embed)

#

And I want to those "flight_code", Plane etc. To be in flight in value

vale wing
#

This naming convention is somewhat outstanding

upbeat gust
strong knoll
vale wing
#

PascalCase in parameters names

upbeat gust
#

sqlite or postgres

strong knoll
upbeat gust
#

Json is not a database

vale wing
#

Make own database ๐Ÿค“๐Ÿ‘

strong knoll
upbeat gust
#

why?

strong knoll
upbeat gust
#

sqlite is file-based

strong knoll
strong knoll
upbeat gust
vale wing
strong knoll
upbeat gust
#

.

strong knoll
#

Still I prefer repl

vale wing
#

Just try VSC or PyCharm and you will change your mind

strong knoll
vale wing
#

Then why use replit

upbeat gust
#

for hosting

strong knoll
vale wing
#

๐Ÿคฆโ€โ™‚๏ธ planes are definitely gonna crash

strong knoll
upbeat gust
#

.

upbeat gust
vale wing
#

Ephemeral file system, you just can't save data

strong knoll
vale wing
#

There probably are ways in replit but you should ask in corresponding place, i.e. their server/forum/support

upbeat gust
strong knoll
vocal snow
#

replit is not a good option for hosting a discord bot

strong knoll
#

Yeah, MySQL Database (without installing)

strong knoll
upbeat gust
vocal snow
#

I never said you can't

naive briar
#

Sure, see what happens

vale wing
#

Unless it is hosted by someone

strong knoll
vocal snow
#

that's replit's builtin key-value storage

#

not mysql

upbeat gust
vale wing
#

Why can't you just get a free tier of VPS

dim tapir
static holly
#
@commands.command()
    @has_permissions(manage_messages = True)
    async def effacer (self, ctx, amount=0):

        if amount == 0:
            await ctx.send ("Veuillez entrer un nombre de message a effacer.")
            return
        elif amount > 0 and amount <= 99:
            amount=amount +1
            deleted_messages = await ctx.channel.purge(limit=amount, after =  datetime.utcnow()-timedelta (days=14))
            await ctx.send ("les message sont infereieurs ร  14 jours", delete_after=3)
            await ctx.send (f"{deleted_messages} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
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: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.
dim tapir
#

ur issue is

await ctx.send ("les message sont infereieurs ร  14 jours", delete_after=3)
await ctx.send (f"{deleted_messages} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
#

u have a lot of deleted_messages

#

Invalid Form Body
In content: Must be 2000 or fewer in length.

static holly
dim tapir
#

the message u send

#

is too long

static holly
#

impossible.... why to long?

dim tapir
#

le corps du message est trop long

#

la limite est de 2000 caractรจres

static holly
fiery cairn
#

Hi there, I'm having issues running my code. It runs fine but the event doesn't work...

import discord
from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        status = after.status
        if status == discord.Status.online or status == discord.Status.idle:
            if "invitelink" in after.activity.name.lower():
                guild = self.bot.get_guild(1066829912943636510)
                role = discord.utils.get(guild.roles, id=1066829913031712773)
                await after.add_roles(role)
                channel = self.bot.get_channel(1074386028745457777)
                await channel.send(f"{after.mention} has been awarded vip role for having invitelink in their status")

def setup(bot):
    bot.add_cog(VIPRoleCog(bot))```
It's meant to give the user the vip role when their status is set to the invitelink, but it's not working...
dim tapir
# static holly its a command...
await ctx.send ("les message sont infereieurs ร  14 jours", delete_after=3)
await ctx.send (f"{deleted_messages} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
visual yarrow
#

The .gg/xxx is detected as an invite link.

#

@fiery cairn this (for future reference)

dim tapir
fiery cairn
#

neither work

naive briar
visual yarrow
fiery cairn
#

yea make sence

naive briar
#

Hmmm, wrong one

static holly
#

it no long message...

dim tapir
# static holly

thats what the error says ๐Ÿคทโ€โ™‚๏ธ

naive briar
#

You're sending a list of message objects

dim tapir
#

no send here

naive briar
#

And the message object's repr is huge

dim tapir
#

do

print(deleted_messages)

to see what it is

naive briar
#

A list of messages, obviously

dim tapir
naive briar
#

Sure

dim tapir
#

i think what u should instead do is

await ctx.send (f"{len(deleted_messages)} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
static holly
#
        elif amount > 0 and amount <= 99:
            amount=amount +1
            deleted_messages = await ctx.channel.purge(limit=amount, after =  datetime.utcnow()-timedelta (days=14))
            print (len(deleted_messages))

            await ctx.send ("les message sont infereieurs ร  14 jours", delete_after=3)
            await ctx.send (f"{len(deleted_messages)} messages ont รฉtรฉ supprimรฉs.", delete_after=5)
#

the bot the me the number of message deleted, but the number of message are not deleted...

#

just send 2 message at the end of code

dim tapir
#
deleted_messages = await ctx.channel.purge(limit=amount)
#

cause i think

after =  datetime.utcnow()-timedelta (days=14)

is looking for old messages

naive briar
#

Not really

slate swan
naive briar
#

The code already explained itself

slate swan
#

That's not a good explanation.

naive briar
#

after is set to looking for any messages that is sent after 14 hours days ago

#

Wait not hours

#

Eh, it's already explained

slate swan
#

It seems that you are struggling.

naive umbra
naive briar
#

Sure

dim tapir
naive umbra
dim tapir
#

ah then i understood wrong

#

where can u get a SQL server for 1$? Lol

static holly
#

@naive briarwhy are the messages not being deleted?

naive umbra
strong knoll
#

So 1:0 To me

naive umbra
#

๐Ÿค”

dim tapir
#

id stick to aws

upbeat gust
dim tapir
upbeat gust
#

good job for not using the stuff everyone recommends because its reliable

#

heres a medal

strong knoll
strong knoll
dim tapir
#

but will be extremely slow later

strong knoll
dim tapir
strong knoll
upbeat gust
dim tapir
static holly
dim tapir
#

14 jours

static holly
#

because I want that if the messages to be deleted are greater than 14 days then I have to send an error message in the channel

dim tapir
#

si vous le supprimez simplement. Il devrait juste supprimer le dernier x nombre de messages

dim tapir
static holly
#

but the way it's coded, the messages don't delete each other

dim tapir
#

unless you have messages that ARE older than 14 days that aren't being deleted then thats a different issue

naive briar
#

And there's no difference between with and without, because Discord will just ignore the message that's older than 14 themselves

static holly
dim tapir
#

then change the day

static holly
#

?

#

by what?

dim tapir
#

timedelta (days=14)

#

by what u want

static holly
dim tapir
#

for example 1 or 4

naive briar
#

There's no point changing it

naive briar
vale wing
#

You have to attach a card to all of services, that's true, but you don't spend anything on free tier

dim tapir
#

i miss read

vale wing
#

Happens

vale wing
vale wing
slate swan
#

mfw when json can't save discord IDs without rounding them off

thin raft
#

shwo your code

pliant gulch
#

This is a certified 53-bit resolution moment

wraith meteor
#

53-bit resolution COOL

shrewd apex
#

save as string

#

pretty sure u can't use integers as keys anyways need to be string

slate swan
#

im not facing an issue

#

just talking about behaviour of json/js in general

shrewd apex
#

ik

slate swan
#

now i get why IDs in djs are strings

pliant gulch
#

The very old versions will prob not support uint64 whereas newer version do have support

slate swan
#

i mean isnt 19 the latest?

shrewd fjord
pliant gulch
slate swan
#

js moment

#

but actually makes sense

pliant gulch
#

I would actually just keep all int64 numbers in a string if your using JavaScript

#

Since pretty much every API does the same

dim tapir
vale wing
slate swan
#

yes they are

gilded cedar
#

i hate async def on_message every time try to make the commands work it ignores it i even attempted to await bot.process.commands thingy but never worked as intended

#

@bot.event
async def on_message(message):
if message.author.id == bot.user.id:
return
if bot.user in message.mentions:
await message.channel.send("Hello This Is Mention Test")
if message.content.lower() in ["any","blacklisted","word"]:
await message.delete()
await message.author.send("""There's Something Called "No Swearing" Rule bruh""")
await bot.process_commands(message)

#Help commands
@bot.command()
async def test(ctx):
await ctx.send("it works")

slate swan
#

because you're doing it wrong

#

await bot.process_commands should be outside of those conditions

naive briar
#

Your bot.process_commands is in an if block

slate swan
#

you should actually just change the .event decorator to .listen(), cleaner and simpler

naive briar
#

Just move it down one indent or set it as listener

gilded cedar
lethal bloom
#

I have a mistake in my code for a long time, and I still don't understand how to fix it. Someone help me?

Code:

@bot.event
async def on_message_edit(message_before, message_after):
    embed = discord.Embed(
        title="{} edited a message".format(message_before.author.name),
        description=
        f"From: **{message_before.guild} / {message_before.guild.id}**",
        color=0xFF0000)
    embed.add_field(name=message_before.content,
                    value="This is the message before any edits.",
                    inline=True)
    embed.add_field(name=message_after.content,
                    value="This is the message after editing.",
                    inline=True)
    channel = bot.get_channel(1234567)

    await channel.send(embed=embed)

Error:

Traceback (most recent call last):
  File "/home/runner/HELPER/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 4385, in on_message_edit
    await channel.send(embed=embed)
  File "/home/runner/HELPER/venv/lib/python3.8/site-packages/discord/abc.py", line 1538, in send
    data = await state.http.send_message(channel.id, params=params)
  File "/home/runner/HELPER/venv/lib/python3.8/site-packages/discord/http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.1.name: Must be 256 or fewer in length.
wraith meteor
#

Hi all, have any examples how to read command + few arguments on nextcord, thanks

cursive spindle
#

hey, i can change a button disabled=True by clicking other button?

naive briar
#

Yes

cursive spindle
naive briar
#

Get the button, set it ๐Ÿคท

#

Are you subclassing the view

static holly
#

why is the final message taking a long time to appear? (about 2 seconds)

    @commands.command()
    @has_permissions(manage_messages = True)
    async def supp (self, ctx, amount=0):

        if amount == 0:
            await ctx.send ("Veuillez entrer un nombre de message a effacer.")
            return
        elif amount > 0 and amount <= 99:
            if amount == 1:
                amount +=1
                await ctx.channel.purge(limit=amount)
                amount -= 1
                await ctx.send (f"{amount} message a รฉtรฉ supprimรฉs!", delete_after=5)
                return
golden portal
static holly
golden portal
static holly
golden portal
#

you can't, thats how it is, purging isnt instant

static holly
#

okay

#

can i use typing... or other? for the latence

golden portal
#

yes

#

!d discord.ext.commands.Context.typing

unkempt canyonBOT
#

async with typing(*, ephemeral=False)```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.

In an interaction based context, this is equivalent to a [`defer()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.defer "discord.ext.commands.Context.defer") call and does not do any typing calls.

Example Usage:

```py
async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(20)

await channel.send('Done!')
```...
static holly
#

tks

slate swan
#

i'm planning tio split my function by operator, but it doesn't seems to separate:
args_result = args.split("+", "-", "*", "/")

naive briar
#

What is args

slate swan
#

this:
async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):

#

an input

slate swan
#

when hit th args.split it erroes

#

or better, don't seems to work

#

what is the correct way to do what i was trying to do?

naive briar
#

There can be only one separator

#

!d str.split

unkempt canyonBOT
#

str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).

If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.

For example:
gusty shard
#

is channel id string or integer

exotic palm
#

i have installed discord.py extension but its giving error module not found in vs code , any way to fix ?

exotic palm
slate swan
#

okay, now i'm trying this and i don't know why it's not working:
args_result = re.split(r'[+-*/]', args)

naive briar
exotic palm
#

like did "pip install discord"

naive briar
#

Why

#

Are you talking about discord.ext.commands

slate swan
#

me?

exotic palm
#

yes

naive briar
#

No

maiden fable
slate swan
#

!d re.split

unkempt canyonBOT
#

re.split(pattern, string, maxsplit=0, flags=0)```
Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list.

```py
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
slate swan
#

it seems to not treat "+" as a separator

naive briar
#

Of course not

slate swan
#

i see, then how do i use it to detect operators as a split thing?

naive briar
#

!e

import re
pattern = re.compile(r"[\+\-\*\\/]")

print(pattern.split("cat+meow-kitty"))
unkempt canyonBOT
#

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

['cat', 'meow', 'kitty']
naive briar
#

Understand its pattern (although I also don't know shit about regex)

slate swan
#

i don't know why it's not starting to roll

        result = []
        total = 0
        meta = []
        if "d" in inp:
            print("rolling...")
            res = int(inp.split('d'))
            print(res)
            sub_r = []
            z = 0
            while(z < res[0]-1):
                if res[1] == "f" or res[1] == "F":
                    sub_r.append(random.randint(1, 6))
                    if sub_r == range (1, 2):
                        sub_r[z] = "-"
                    elif sub_r == range (3,4):
                        sub_r[z] == "0"
                    else:
                        sub_r[z] == "+"
                else:
                    sub_r.append(random.randint(1, res[1]))
                z = z+1
            result.append(sub_r)

        for x in result:
            total = total+x
        
        meta.append(result, total)
        return meta```
#

it's not even entering into if "d"

vale wing
#

Then there's no "d" in inp

#

How do you call this func

cloud dawn
#

it's a pretty interesting function as well

cloud dawn
golden portal
#

iirc discord alone is a broken mirror of discord.py

wraith meteor
#

How run 2 deferent sounds parallely by this method on one voice channel nextcord.FFmpegOpusAudio?

forest oyster
#

class SimpleView(discord.ui.View):

@discord.ui.button(label='Crear un ticket', custom_id='Tickets', style=discord.ButtonStyle.success,  emoji='๐Ÿ”ง')
async def Ticket_Create(self, interaction:discord.Interaction, button:discord.ui.Button):
    view = Menu_select
    await interaction.send(view=view)
#

does someone know how i should call the Menu_select class? This is wrong:
await interaction.send(view=view)

cloud dawn
#

Well you can just pass it instantly

#

But you got to initialize it.

forest oyster
cloud dawn
forest oyster
#

yea, I already did, but I have an error

sick birch
#

It's hard for us to help you when we don't know what the error is

cloud dawn
#

Could you post it?

forest oyster
sick birch
#

It's interaction.response.send_message

cloud dawn
#

Needs to be a response.

forest oyster
sick birch
#

On discord?

forest oyster
sick birch
#

Does this happen when you press the "Crear un ticket" button?

forest oyster
#

yeap

sick birch
#

And could you post your code?

forest oyster
#

I dont understand

cloud dawn
#

He's asking for the updated code

sick birch
#

Can you show us your code

forest oyster
#

the code?

sick birch
#

Yes

cloud dawn
#

I can speak Robin so I can translate.

sick birch
#

Oh shut up

#

English is hard

cloud dawn
#

๐Ÿคญ

forest oyster
#

class SimpleView(discord.ui.View):

@discord.ui.button(label='Crear un ticket', custom_id='Tickets', style=discord.ButtonStyle.success,  emoji='๐Ÿ”ง')
async def Ticket_Create(self, interaction:discord.Interaction, button:discord.ui.Button):
    await interaction.send(Menu_select)
#

this is the code

sick birch
#

Where ... is the parameters that the class takes (if any)

forest oyster
#

class SimpleView(discord.ui.View):

@discord.ui.button(label='Crear un ticket', custom_id='Tickets', style=discord.ButtonStyle.success,  emoji='๐Ÿ”ง')
async def Ticket_Create(self, interaction:discord.Interaction, button:discord.ui.Button):
    view = Menu_select
    await interaction.send(view=view)
#

like this?

cloud dawn
#

What changed?

#

Oh no you have to pass the class in the kwarg view and also initialize it.

forest oyster
#

oooo ok wwait

#

ok ok

#

it was that

#

what a dumb error

cloud dawn
#

There are no dumb errors

forest oyster
#

Yeah, I mean what a dumb mistake

#

you now, Im form spain, sorry for the expresions๐Ÿ˜…

cloud dawn
#

A lot of us aren't English natively.

cloud dawn
#

Robin

sick birch
#

FWIW English ain't my first language either

cloud dawn
#

Can I test something on you Robin? :3

sick birch
#

I suppose

cloud dawn
#

@sick birch Did this ping you?

sick birch
#

But it has a weird icon next to it

#

Looks like a bell with the letter z

cloud dawn
#

Supposed to be a silent message, rigged.

sick birch
unkempt canyonBOT
#
== Raw message ==

@sick birch Did this ping you?
slate swan
#

i made a debug but it didn't entered the funtion

vale wing
#

Actually do you even call the function

slate swan
#

it's calling, but not working in pratice

vale wing
#

Too many of variables I don't know origin of

#

Could you paste the whole code

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

also @vale wing i will probably need suggestions and help to simplify the variables

#

so they would be more understandable

#

like, better name

slate swan
#

Anyone know if it possible to edit wehbook image ?
```webhook_id = "myid"
webhook_token ="mytoken"

url = f"https://discord.com/api/webhooks/%7Bwebhook_id%7D/%7Bwebhook_token%7D"

payload = {
    "name": "Myname",
    "avatar": "base64image "
}

requests.patch(url, json=payload)```

Cuz with this only my name edits

slate swan
#

probably not ||guess it's struggling with my spaghetti XD||

dull terrace
#

Hey i've got a weird bug

#

it's saying an option is already being used in my dropdown im creating

#
new_option = Option(label=f"{attacker_name}", value=f"att{attacker_id}{end}")
if new_option not in options:
    options.append(new_option)```
but i have this code
#

in a for loop, then it makes the options at the end

#

it's impossible right?

mild bear
#

guys why this is not turning my bot online? ```import discord
import asyncio

client = discord.Client(intents=discord.Intents.default())
TOKEN = 'somerandomnumbersandletters'

@client.event
async def on_message(message):
if message.author == client.user:
return
await asyncio.sleep(4)
async with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send("test")

client.run(TOKEN)and this doesimport discord
import asyncio
import torch
from transformers import pipeline

client = discord.Client(intents=discord.Intents.default())
TOKEN = 'somerandomnumbersandletters'

generator = pipeline('conversational', model='EleutherAI/gpt-neo-2.7B')
prompt = 'This is an ai chatbot based on gpt neo'

@client.event
async def on_message(message):
res = generator(prompt, max_length=40, do_sample=True, temperature=0.9)
if message.author == client.user:
return
await asyncio.sleep(4)
async with message.channel.typing():
await asyncio.sleep(2)
await message.channel.send(res[0]['generated_text'])

client.run(TOKEN)```

#

the first one works the secone doesnt work

simple kettle
#

how can i make this slash command's name have spaces

@bot.tree.command(description="Clears the specified stat")
async def clear_stat(interaction : discord.Interaction, member : Optional[discord.Member], stat : stat_choices):
wraith meteor
#
async def SendMessage(ctx):
    package.setup.setsettings.settranslationlanguage_hindi()
    print('Hindi translation language selected')
    await ctx.send('Hindi translation language selected')``` how RUN this from PYTHON code?? not from chat by command.....
glad cradle
wraith meteor
#

no from python code, not from text chat

#

just call to this one big fucntion onsly

wraith meteor
#

not hindi ok..

glad cradle
wraith meteor
#

so in this and the question I do not understand how to register such a function ๐Ÿ™‚

glad cradle
#

tbh there are a lot of wrong things here

  • you shouldn't use a json file as database, its purpose is not that
  • even if you wanted to use a json file, reading and loading a file is a blocking call, that means the event loop will be affected by this, to put it simple your Bot may be some seconds behind the API and may lose connection because of it
#

use a database

#

with an async driver

#

I would recommend PostegreSQL but you should look into relational databases to use it well

#

or you could use MongoDB

#

that's a document based database

#

the important thing here is that you must use async drivers/clients to connect to the databases and to do things

simple kettle
short zinc
#

does discord.InteractionResponse.send_message() not return the just sent message?

#

how can I get the object for the just sent message?

glad cradle
unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions") will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
glad cradle
short zinc
glad cradle
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
short zinc
glad cradle
#

no this fetches the first interaction response

#
If the interaction response was a newly created message (i.e. through InteractionResponse.send_message() or InteractionResponse.defer(), where thinking is True) then this returns the message that was sent using that response.
short zinc
#

ah thanks didn't read the second part ๐Ÿ˜…

glad cradle
#

no problem

short zinc
#

also the name is confusing

glad cradle
#

usually that method is not used in this way

slate swan
#

can sum1 help with this

smoky sinew
#

how do i pass an enum as an option in a slash command?

#

do i have to do an autocomplete thing?

#

i think i found it

#

it's the autocomplete decorator

tulip frigate
#

How could I set an cooldown on message? Save times in cache and compare time now?

ancient elm
#

I think d.py had some cooldown decorators. Never used them though. This would be the manual solution, yes

unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

tulip frigate
slate swan
naive briar
#

They never will

wraith meteor
#

updating never....:)

ionic garden
#

how do i take a list of users in app_commands?

spiral crypt
#
    if welcome_channel:
        embed = discord.Embed(title=f"Welcome {member.name}!",
                              description=f"Thank you for joining our server! Please take a moment to read the "
                                          f"{discord.utils.get(member.guild.channels, name='rules')} and introduce yourself in the "
                                          f"{discord.utils.get(member.guild.channels, name='introductions')} channel.",
                              color=0x00ff00)
        embed.set_thumbnail(url=member.avatar_url)
        await welcome_channel.send(embed=embed)

Hey question, how would I get it to put #introductions/#rules as channel links in the embed?

#

oh maybe cuz i missed the # oops

graceful ermine
#

How could I fix this?

#
    async def help(self, ctx):
        embed = nextcord.Embed(
            title="Help", description="List of available commands:", color= nextcord.Color.green())
        for i in self.bot.cogs:
            cog = self.bot.get_cog(i.lower())
            commands = cog.get_commands()
            data = []
            for command in commands:
                description = command.description.partition('\n')[0]
                data.append(f"{command.name} - {description}")
            help_text = "\n".join(data)
            embed.add_field(name=i.capitalize(),
                            value=f'
{help_text}
', inline=False)
            embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1068706276768497836/1071609900469334056/pngtree-eagle-head-logo-png-image_8704115.png')
            embed.set_image(url='https://cdn.discordapp.com/attachments/1056648270216171630/1059649382456234104/standard.gif')
        await ctx.author.send(embed=embed)```
slate swan
naive briar
unkempt canyonBOT
naive briar
#

It's already returning the cogs, why are you getting it again

graceful ermine
#

so it can show you the listed command and etc

naive briar
#

And? I'm saying that it has already returned the cogs

graceful ermine
#

@naive briar

#

??

naive briar
#

Just use the cogs that it returned?

#

There's nothing hard to understand

graceful ermine
#

@naive briar bro this is a custom help command and it used to work and I never messed around with the code this is how it worked

naive briar
#

Why are you asking for help if it works then ๐Ÿคท

#

There's no point asking for help if you don't accept it

graceful ermine
#

....

naive briar
#

I don't know what to say anymore, I already said that the cogs attr already returned the cogs and there's no point getting it again

smoky sinew
#

a read-only mapping of cog name to cog.

coral glen
graceful ermine
coral glen
#

it doesnt work

naive briar
#

Install pip first

coral glen
#

how

graceful ermine
#

Yeah you need to get a text editor

coral glen
#

sorry sorry im new

graceful ermine
#

such as vscode

#

or pycharm

#

@coral glen ^

coral glen
graceful ermine
#

for multiple coding languages but if you're gonna only stick with Python then Pycharm

coral glen
#

hm ok

coral glen
smoky sinew
smoky sinew
naive briar
#

๐Ÿคท

coral glen
smoky sinew
#

what does it say

shrewd apex
#

whats the error

coral glen
smoky sinew
#

how did you install python @coral glen

smoky sinew
coral glen
coral glen
smoky sinew
#

try reinstalling python with pip maybe

coral glen
#

how

smoky sinew
#

you probably disabled it if you did custom install

coral glen
#

oh

shrewd apex
#

u didn't install properly why do u have python.exe in desktop?

#

ur paths are not set properly either

autumn junco
#

I'm wanting to send two messages for the response of an interaction how can I do this. Well the issue is I'm responding with another menu but I also want it to have a message

coral glen
#

๐Ÿ˜ต

shrewd apex
unkempt canyonBOT
autumn junco
shrewd apex
#

yeah

winged cloud
coral glen
shrewd apex
coral glen
shrewd apex
smoky sinew
#

@winged cloud don't make your repls public, anyone can access them and view your token

smoky sinew
coral glen
viral stump
#

that's why

coral glen
#

??

viral stump
#

you have to go customize installation and then check everything

#

the default installation don't install pip

hushed galleon
#

pip is supposed to be installed by default, but in the case it isnt installed you can use py -m ensurepip to bootstrap it, then retry pip install discord.py

viral stump
#

it's weird

hushed galleon
#

welp i never had the same issue

viral stump
#

maybe it's a new "feature" to let the user choose

slate swan
hushed galleon
#

they're on a windows machine, and you also wouldnt want to be using the system python for your projects

slate swan
coral glen
#

epic

#

.

slate swan
coral glen
#

ok

viral stump
# coral glen a

install python again with full check on custom, it will make less errors

#

weird.

coral glen
viral stump
#

damn bot

slate swan
coral glen
#

yes

coral glen
#

4th time uninstalling python within an hour ๐Ÿ˜ญ

slate swan
#

lmao

viral stump
coral glen
viral stump
slate swan
coral glen
#

lemme reinstall

viral stump
#

this is good

coral glen
viral stump
#

check all

coral glen
#

ok

viral stump
#

if you do python it's useful to have more tools in your hand and it's light anyway

#

no big deal to have 10mo more

hushed galleon
#

you really dont need to check all of them

viral stump
hushed galleon
#

if anything its less efficient, you're asking it to do things you wont need

viral stump
#

but the PATH is important

#

and precompile should make the code run faster

#

for all user should not be a problem if the user is alone on it's computer