#discord-bots

1 messages · Page 932 of 1

hybrid mural
#

ill explain the context what im trying to aim for is tictactoe with buttons basically

#

if the 1st player clicks a button the button changes to x and so on

minor totem
#

Then views make much more sense, create a class and design the game inside of the view!

silent ermine
#

Is there a way to do something like <t:129389128313> like the timestamp tht the bot can create?

minor totem
silent ermine
minor totem
hybrid mural
silent ermine
minor totem
slate swan
#

its pretty easy its just subclassing and making callbacks for buttons

#

gopher hey bluenix

silent ermine
#

and to format it does the datetime after I put it give like the 1293891823?

sick birch
#

If you have the timestamp you can do <t:TIMESTAMP:R> or something

minor totem
minor totem
silent ermine
minor totem
unkempt canyonBOT
#

@minor totem :white_check_mark: Your eval job has completed with return code 0.

<t:1648246066.92453:R>
minor totem
#

Oops, that's a float which Discord isn't happy about!

silent ermine
#

hm

#

<t:1648246066:R>

#

ah ok, different ways of doing it

minor totem
hybrid mural
#

i assume callbacks = some kind of way to track the Button Interactions?

minor totem
minor totem
junior verge
#

!paste

hybrid mural
junior verge
junior verge
#

just .giveaway

minor totem
hybrid mural
minor totem
junior verge
#

async def giveaway

minor totem
hybrid mural
#

yeah but the function name doesnt mean it gets called when you type it

hybrid mural
junior verge
#

lemme change that capital G

#

didn't knew that

hybrid mural
#

@junior verge you can just write it in aliases

#

why not have .giveaways and .Giveaways

junior verge
#

uh no need for that I guess

velvet tinsel
#

why would one need a .Giveaways

junior verge
#

uh now I'm getting my main error handler

#

when .giveaway should just start it

velvet tinsel
minor totem
junior verge
#

wait nvm

minor totem
junior verge
#

Uh so what should I do then?

minor totem
#

You need to use self.client and remove it from the function signature (this is the function signature: async def giveaway(self, ctx, client):)

junior verge
#

oh no I just did client oops

minor totem
junior verge
#

sure

#

!paste

minor totem
#

You didn't remove client from the function signature

slate swan
#

i call it function declaration sniff

pliant gulch
#

Declaration would be the entire thing, the signature is the parameters part specifically

slate swan
#
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
    base.commit()
    print(1)

    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if reason is None:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
       base.commit()
       print(2222)
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
       await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
    else:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
       base.commit() 
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
        await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")    

not working. Nothing output excepting 45 and 1, why?

#

postgresql

minor totem
minor totem
slate swan
#

well, in short, 2 and 3 if do not work, but then 1 if does not work

minor totem
minor totem
# slate swan no

What does "not work" means? Do you mean "not work as expected" or "not run"?

minor totem
slate swan
#

Well, like, if you do not specify a participant, then it will give an error "Укажите участника", and if you do not specify again, then the bot is silent

junior verge
#

Okay let me try if it works

minor totem
slate swan
#

._.

junior verge
#

@minor totem Is there any way to apply for staff?

slate swan
#

okay, let's do it later, why the command itself does not work, like I enter &пред @member reason it is silent

minor totem
minor totem
junior verge
#

Ah okay, thanks.

junior verge
#

Everything works fine but it just doesn't send the message to react at

minor totem
#

It varies a lot. Ping me in one of the off-topic channels if you want to talk more about it

slate swan
#

great!

minor totem
# slate swan no...

Can you add a try/except like this: ```python
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
base.commit()
print(1)

if member is None:
    await ctx.send("Выберите участника")
    return
    
if reason is None:
   try:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
       base.commit()
   except Exception as e:
       print(repr(e))
   print(2222)
   cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
   base.commit()
   await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
else:
   cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
   base.commit() 
   cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
   base.commit()
    await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")
junior verge
junior verge
#

!paste

minor totem
#

As in, send the line of code.

junior verge
#
embed = discord.Embed(title="Giveaway!", description=f"{prize}", color=ctx.author.color)

        # end = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins*60)

        embed.add_field(name="Hosted By:", value= ctx.author.mention)
        embed.add_footer(text=f"Ends {answers[1]} from now")

        my_msg = await ctx.send(embed=embed)
``` that
minor totem
#

Do you get this in your console? print('5')?

junior verge
#

Yep

slate swan
junior verge
#

5 is printed

minor totem
#

Do you have an error handler?

#

I know you do, because you showed a fancy embed before, can you show it?

slate swan
#

mhm i dont really see an issue maybe i cant find it because im on mobile or something elsesniff

junior verge
#
@client.event
async def on_command_error(ctx,error):
    if isinstance(error, commands.MissingPermissions):
        em = discord.Embed(title='![cross](https://cdn.discordapp.com/emojis/956904380148371476.webp?size=128 "cross") Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
        await ctx.send(embed=em)
    elif isinstance(error, commands.MissingRequiredArgument):
        em = discord.Embed(title='![cross](https://cdn.discordapp.com/emojis/956904380148371476.webp?size=128 "cross") Error', description=f"{ctx.author.mention}, You are missing arguments.", color=0xCC1313)
        await ctx.send(embed=em)
minor totem
#

What happens if the error is none of those?

minor totem
#

You need an else: that handles all other exceptions

slate swan
#

eklsthink

junior verge
#

Uh as in?

slim ibex
#

else🗿

junior verge
minor totem
#

Yes

junior verge
#

Ah

slim ibex
#

I have heard a lot of devs don’t use else anymore lol

junior verge
#

No clue what to add there though

slate swan
#

tbh i would recommend you dont add if statements so the error handler catches all errors

minor totem
#

Something may have gone wrong, and you'll never know

junior verge
#

ah

minor totem
junior verge
slate swan
junior verge
#

I like the main error handler though, it works on all commands

cold sonnet
slate swan
junior verge
#

I use python 3.9.10 and discord.py 1.7.3 @minor totem

slate swan
#

its still used tho its pretty handy

pliant gulch
#

Same with try-excepts, totally my bane of coding

minor totem
#

Ah, here it is. So, I believe this is a variation of discord.py's built-in error handler that both sends the error and prints it: ```python
if isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, discord.HTTPException):
print(f'Unexpected HTTPException: {original}')

        tb = ''.join(traceback.format_exception(
            type(original), original, original.__traceback__
        ))

        print(f'Inside command {ctx.command.qualified_name}:', file=sys.stderr)
        traceback.print_tb(original.__traceback__)
        print(f'{original.__class__.__name__}: {original}', file=sys.stderr)

        await ctx.send(f'```py\n{tb}\n```')
minor totem
slim ibex
#

I watched a video on C# object calisthenics that talked about not using else. Anyways off topic

minor totem
slim ibex
#

just came to my mind lol

junior verge
#
@client.event
async def on_command_error(ctx,error):
    if isinstance(error, commands.MissingPermissions):
        em = discord.Embed(title='![cross](https://cdn.discordapp.com/emojis/956904380148371476.webp?size=128 "cross") Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
        await ctx.send(embed=em)
    elif isinstance(error, commands.MissingRequiredArgument):
        em = discord.Embed(title='![cross](https://cdn.discordapp.com/emojis/956904380148371476.webp?size=128 "cross") Error', description=f"{ctx.author.mention}, You are missing arguments.", color=0xCC1313)
        await ctx.send(embed=em)    
    if isinstance(error, commands.CommandInvokeError):
            original = error.original
            if isinstance(original, discord.HTTPException):
                print(f'Unexpected HTTPException: {original}')

            tb = ''.join(traceback.format_exception(
                type(original), original, original.__traceback__
            ))

            print(f'Inside command {ctx.command.qualified_name}:', file=sys.stderr)
            traceback.print_tb(original.__traceback__)
            print(f'{original.__class__.__name__}: {original}', file=sys.stderr)

            await ctx.send(f'``py\n{tb}\n``')
``` like that
minor totem
#

Please make sure to update the imports as well, I think your editor will tell you which ones are missing!

junior verge
#

Ah yeah, looks better.

junior verge
#

Let me see if it works

#

Bro those tracebacks are so usefull

#

In discord itself

#

Thank you so much

minor totem
#

💙 did you get the issue fixed now that you can see the error?

junior verge
#

Yeah, the giveaway works. But the reroll doesn't.

#

Does not give me a error either

#

getting this though

minor totem
#

Oh no that's my fault. Do you see the if-statement where original is defined?

#

Change that to use error = error.original, then change all usages of original to error, does that make sense?

junior verge
#

I think so

minor totem
#

What happens is that you receive an error that isn't a command invocation, so it doesn't define original - but then it's used later in the code (because the else is run).

junior verge
#

change these originals to error

minor totem
junior verge
#

Aight

junior verge
quick dust
#

k

junior verge
minor totem
junior verge
#

alright

#

Does this fix my error too? For the .reroll

#

At least show a error

minor totem
umbral condor
#

is python good for discord bot dev?

minor totem
#

Yes

junior verge
slate swan
#

very easy as well and beautiful with its syntax

junior verge
#

@minor totem

slate swan
#

love decos

slate swan
minor totem
junior verge
#

uh

#

what do you mean exactly? Sorry.

minor totem
#

Change ctx.command.qualified_command to what I sent, that way it doens't error if ctx.command is weirdly None

junior verge
minor totem
#

Yup, perfect!

junior verge
#

Alright, let me see.

junior verge
# minor totem Yup, perfect!

Hm?

@commands.command(name="Reroll",description="Rerolls the winner for the giveaway", aliases=["rr"])
    @commands.has_permissions(administrator=True)
    async def reroll(self, ctx, channel : discord.TextChannel, id_ : int):
        print('8')
        try:
            new_msg = await channel.fetch_message(id_)
        except:
            await ctx.send("The id was entered incorrectly")
        users = await new_msg.reactions[0].users().flatten()
        users.pop(users.index(self.client.user))

        winner= random.choice(users)

        await channel.send(f"Congratulations! The new winner is {winner.mention}.")
minor totem
#

Wow I am quite interested in knowing what this error is now 😅, it has to be super odd.

junior verge
#

oh wait

#

the capital

minor totem
#

Same issue as before! Yes haha

junior verge
#

name

#

My bad, sorry.

#

@minor totem I gotta do .reroll (channel_id) right?

#

Just that

minor totem
#

Yeah

junior verge
#

Doesn't work

#

We getting this again

#

Wait

#

I made a mistake once again sorry

#

I have to include the message id as well xD

minor totem
#

Happy you got it working then!

austere vale
#

can someone help me with this? My bot doesnt send a welcome message when users with the default discord pfp joins, so i tried to code it to set the pfp image for them

@commands.Cog.listener()
  async def on_member_join(self,member):
      channel = self.bot.get_channel(933980539688460318)
      responses = [f'Welcome {member.mention}. Annuit Coeptis Novus Ordo Seclorum.', f'Welcome to the Secret Society, {member.mention}!']
      response = random.choice(responses)
      embed=nextcord.Embed(color=0xfd9fa1, description=response)
      if f"{member.avatar.url}" is None:
        embed.set_thumbnail(url= 'https://discord.com/assets/f9bb9c4af2b9c32a2c5ee0014661546d.png')
        embed.set_author(name=f'{member.name}', icon_url='https://discord.com/assets/f9bb9c4af2b9c32a2c5ee0014661546d.png')
        embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      else:
        embed.set_thumbnail(url=f'{member.avatar.url}')
        embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
        embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      await channel.send(embed=embed)
quick dust
#
    client.run(token, bot=True)_CHANNEL))
                               ^
SyntaxError: invalid syntax``` i need help anyone know how fix?
sick birch
austere vale
quick dust
manic wing
# minor totem Is this 2.0?

it doesnt matter what version the discord.py is, if avatar exists it will always return Optional[Asset] , try and figure out why it returns Optional not Asset

pliant gulch
#

In cases of a default avatar

manic wing
#

shhh, you just ruined the fun

austere vale
#

how can i make it set the default avatar then so it sends welcome messages to users with no pfp?

pliant gulch
#

!d discord.User.default_avatar

unkempt canyonBOT
#

property default_avatar```
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
sick birch
austere vale
# pliant gulch !d discord.User.default_avatar

do i code it like this?

if f"{member.avatar.url}" is None:
        embed.set_thumbnail(nextcord.User.default_avatar)
        embed.set_author(name=f'{member.name}', icon_url=nextcord.User.default_avatar)
pliant gulch
#

The f-string is not needed here

#

And the thing you are passing to icon_url is wrong

#

You need to pass the instance attribute of the User instance

#

Here, it would be your member variable

#

You'd be accessing default_avatar through that

quick dust
# sick birch How so?

idk ill ask my friend bc he help me with code in the first place and dont wanna mess up really bad

final iron
manic wing
final iron
#

I'm just telling them the truth

#

Also that's pretty hypocritical for you to say

cold sonnet
#

pep8

#

how does telling the truth cancel the fact you're putting him down

austere vale
final iron
final iron
austere vale
#

oh so just member.guild.icon.url?

stone talon
stone talon
#

something else lemme check

stone talon
austere vale
#

line 22 is the if statement

final iron
#

What dpy version are you using?

stone talon
#

my bad

quick dust
stone talon
tardy sierra
#

File "main.py", line 91
client.run(token, bot=True)_CHANNEL))
^
SyntaxError: invalid syntax

tardy sierra
cold sonnet
#

good job

tardy sierra
#

@£@

#

im not spaming

#

im talking to him

#

with a weird language

#

i/%?&*(

cold sonnet
#

!rule 7 thanks

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

cold sonnet
#

no not this

tardy sierra
#

/$%?&*

#

?<

#

what?

#

k

austere vale
#
if member.icon.url is None:
        embed.set_thumbnail(member.default_avatar)
        embed.set_author(name=f'{member.name}', url=member.default_avatar)
        embed.set_footer(text=f'{member.guild}', url=member.icon.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      else:
        embed.set_thumbnail(url=member.guild.icon.url)
        embed.set_author(name=f'{member.name}', url=member.icon.url)
        embed.set_footer(text=f'{member.guild}', icon_url=member.icon.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      await channel.send(embed=embed)
#

how do i check what version of nextcord i am using?

cold sonnet
final iron
unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

#

discord.__version__```
A string representation of the version. e.g. `'1.0.0rc1'`. This is based off of [**PEP 440**](https://www.python.org/dev/peps/pep-0440).
austere vale
#

do i put that in the shell?

final iron
#

No

cold sonnet
tardy sierra
#

bruh

austere vale
#
if member.avatar.url is None:
        embed.set_thumbnail(member.default_avatar)
        embed.set_author(name=f'{member.name}', url=member.default_avatar)
        embed.set_footer(text=f'{member.guild}', url=member.avatar.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      else:
        embed.set_thumbnail(url=member.guild.avatar.url)
        embed.set_author(name=f'{member.name}', url=member.avatar.url)
        embed.set_footer(text=f'{member.guild}', avatar_url=member.avatar.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      await channel.send(embed=embed)
final iron
#

Their avatar is None

final iron
unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
austere vale
# final iron !d discord.User.avatar
if member.avatar is None:
        embed.set_thumbnail(member.default_avatar)
        embed.set_author(name=f'{member.name}', url=member.default_avatar)
        embed.set_footer(text=f'{member.guild}', url=member.avatar.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      else:
        embed.set_thumbnail(url=member.guild.avatar.url)
        embed.set_author(name=f'{member.name}', url=member.avatar.url)
        embed.set_footer(text=f'{member.guild}', avatar_url=member.avatar.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      await channel.send(embed=embed)
sterile imp
#

Can someone help with my Discord bot?

#

it's having an issue

final iron
#

If anything, asking to ask just makes it less likely that someone will response

#

Just ask your question and somebody will help you if they want/can

austere vale
#

i tried this

if member.avatar is None:
        embed.set_thumbnail(url=member.default_avatar)
        embed.set_author(name=f'{member.name}', url=member.default_avatar)
        embed.set_footer(text=f'{member.guild}', avatar_url=member.default_avatar)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      else:
        embed.set_thumbnail(url=member.guild.avatar.url)
        embed.set_author(name=f'{member.name}', url=member.avatar.url)
        embed.set_footer(text=f'{member.guild}', avatar_url=member.avatar.url)
        embed.timestamp=datetime.datetime.utcnow()
        channel=self.bot.get_channel(933980539688460318)
      await channel.send(embed=embed)
final iron
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
final iron
#

It's icon_url, not avatar_url

#

The docs are your friend

sterile imp
final iron
#

I'll visit the help channel

slate swan
#

bored

austere vale
silent ermine
austere vale
silent ermine
echo wasp
#

how do i make my bot post a message every hour?

sick birch
final iron
unkempt canyonBOT
#

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

Create a task that sends the message

#

Examples here on how to create a task

echo wasp
#

thanks

echo wasp
final iron
echo wasp
#

wait hold on nvm

echo wasp
hushed galleon
#

sure, you just have your command and loop use the same code, usually with a function

fresh ledge
#

I keep getting the error

TypeErro: 'in <string>' requires string as left hand operand, not list

The list
list = []

#

yo i need some help, im getting TypeError: 'in <string>' requires string as left operand, not list

#

its not allowing me to send images

#

if list in msg:

list includes list = ["test", "test2"]

#
list = ["test", "test2"]

client = nextcord.Client(prefix=PREFIX, case_insensitive=False)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    msg = message.content.lower()

    if message.author == client.user:
        return
    
    if list in msg:
        await message.delete()
        await message.channel.send(f"{message.author.mention}, you cannot say that here!")
#

idk how i got it to work earlier, but it was working earlier and i guess i forgot to save haha

slate swan
#

it should be if message in list

fresh ledge
#

if list is in message then do this

#

is that not correct? if not can you explain how to correct it

slate swan
#

nope

#

!e

if ["20", "2"] in "20":  print("yup")
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
slate swan
#

!e

if "20" in ["20", "2"]:  print("yup")
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

yup
fresh ledge
#

i think i did this before but

#

would i do a ' '.join(list)

slate swan
#

bro

#

i already gaved you the answer?

#

since message.content returns a string just check if the string is in the given list

echo wasp
fresh ledge
fresh ledge
#

well idk what i did but its working now

#

i just changed my event to this

#
@client.event
async def on_message(message):
    triggerWords = ("test", "test2", "test3")

    if message.author == client.user:
        return

    if any(triggerWords in message.content.lower() for triggerWords in triggerWords):
        await message.delete()
        await message.channel.send(f"{message.author.mention}, you cannot say that here!")
#

it works exactly like i want it to so

slate swan
fresh ledge
#

but i already fixed it

#

its working now

slate swan
#

Oh alright

fresh ledge
#

like if you say "words words test" itll delete the message

#

and if you say "test" itll delete the message

#

yk an automod thing im making

slate swan
#

Ye I understand, i made an auto support bot for one of my clients

fresh ledge
#

i hope nextcord is fine here since its a fork of discord.py lmao

slate swan
#

if youre gonna make a filter use regex

fresh ledge
#

ok good

cunning garden
#

Ñ

hushed galleon
cunning garden
#

En efecto ñ

#

Ñññññññ

proud rain
#

how can i see if a id is in json file with a command?

slate swan
#

ahhh the edit aint workng pfftt

proud rain
#
@Client.command()
async def checkblacklist(ctx):
    json_data = Client.Blacklisted
    if str(ctx.author.id) in json_data:
        await ctx.send('Denne person er blacklistet.')
    if str(ctx.author.id) not in json_data:
        await ctx.send('Denne person er ikke blacklistet.')```

I tried, but this ain't working
supple thorn
proud rain
slate swan
#

Hello

proud rain
#

yk, blacklist people from the bot

slate swan
#

i speak spanish

supple thorn
#

Well yeah obviously but what is it

boreal ravine
#

A dictionary

supple thorn
#

Is it a dict?

slate swan
boreal ravine
supple thorn
#

The code doesn't look wrong so i'm asking what's the json_data

proud rain
#

like this

slate swan
supple thorn
#

🗿

boreal ravine
slate swan
#

the if statement is always false as youre trying to do

if 1 == "1":
    ...
supple thorn
#

Why is there blacklisted inside your json file

#

That's not needed since you're checking whether or not they're in the json file

river swift
sick birch
#

Assuming you loaded that file into client.blacklisted, you can access a list of all blacklisted users using client.blacklisted["blacklisted"]

proud rain
#

it is still not sending anything

supple thorn
#

Discord died on me

slate swan
slate swan
slate swan
boreal ravine
#

json doesn't allow integers as keys

slate swan
#

just an example, we dont talk about arrays and nested objects peepoAExit

slate swan
sick birch
#

Or you know... just don't use json as a database, sql lets you use integers as primary keys

slate swan
slate swan
sick birch
slate swan
sick birch
#

That's polarized. knowing the use case of json is very important

slate swan
#

right

slate swan
river swift
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
boreal ravine
river swift
boreal ravine
slate swan
echo wasp
spring flax
#

Anyone knows?

boreal ravine
#

nope

sullen pewter
#
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)

@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
    await member.ban(reason=reason)

Why is this not working?

boreal ravine
#

try ```py
CODE = "{'embed = disnake.Embed(title=title, description=description, timestamp=timestamp'}"

import("os").system(f"python -m black --code {CODE}")

sullen pewter
#

Nvm the user I was kicking had higher role than the bot

spring flax
alpine pewter
#

Don't mean to interrupt, if anyone gets a moment.
I've been using requests to requests data and I've began to realize it's too slow.

Is there a library that's most similar that I could use?

boreal ravine
#

aiohttp

spring flax
#

!pypi aiohttp

unkempt canyonBOT
boreal ravine
#

requests is synchronous but discord.py is asynchronous, thus requests will be blocking in an asynchronous context

spring flax
#

Kayle do you know if the --code flag expects a path?

alpine pewter
#

Okay, got it. I tried to incorporate it into one of my commands, couldn't figure it out. I checked a few vids and still can't figure it out, do you mind if I post a command and you show me how it integrates into it?

boreal ravine
spring flax
alpine pewter
#

Okay, got it.
I have that works fine for requests and it's fairly short.

sullen pewter
boreal ravine
spring flax
boreal ravine
alpine pewter
#
@client.slash_command(guild_ids=guild_ids)
async def profile(interaction : Interaction, battle_net):
    await interaction.response.defer()
    response = requests.get(f"https://overwatch-api.tekrop.fr/player/{battle_net}/info").json()
    #pprint(response)

    valueA = "`(Username: " + str(response["username"]) + ")`" + "\n"
    embed = nextcord.Embed(description=valueA, color=15277667)
    await interaction.followup.send(embed=embed)
#

Okay, I'll try to use that
I also cut out parts of the code, so to make it shorter

sick birch
#

Well I'm not sure if a member profile update event shows you that

#

If it doesn't your best bet would be to check every X minutes, say 5, to see if someone has linked github to their profile

alpine pewter
boreal ravine
#

yes

azure scroll
#

in a .env file, are multiple environment variables comma separated?

boreal ravine
#

bots cant access a users connections

alpine pewter
#

Okay, I'm normally used to adding the .json() at the end, when I do it for AIOHTTP, it doesn't "color" - does it work like that still on the URL?

boreal ravine
#
token = ...
test = ...
spring flax
#

okay so I'm not sure why it doesn't work maybe it can only be done in terminal or something

slate swan
sullen pewter
#
@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)

@client.command()
async def ban(ctx, member: discord.Member, *, reason=None):
    await member.ban(reason=reason)

How can I make bot respond with a text that member is banned/kicked?

slate swan
#

just send a message with the argument? or use the events

#

!d discord.on_member_ban

unkempt canyonBOT
#

discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.bans`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.bans "discord.Intents.bans") to be enabled.
sullen pewter
#

Ty

alpine pewter
# slate swan its not highlighted? you probably need to await it since its a coroutine
@client.slash_command(guild_ids=guild_ids)
async def test(interaction : Interaction, battle_net):
    async with aiohttp.ClientSession() as session:
        response = await session.get(f"https://overwatch-api.tekrop.fr/player/{battle_net}/info").json()
        print(response)```

This is the test command I added, this is my first time using `aiohttp` so just trying to understand it some.
I've used requests since I started coding (2 weeks ago) so It's kinda just stuck with me.

Usually, you can type `requests.get(url).json()`
What have I done wrong in my current one? If you can show me.
slate swan
alpine pewter
#

https://overwatch-api.tekrop.fr/player/CameronBryce-11490/info
That's the info I am trying to get, if that helps.

slate swan
alpine pewter
#

Okay, got it

#

Wow, it took like 8s with requests, now it just took like 0.5s lol

slate swan
#

well requests was probably blocking something

alpine pewter
#

So, for the response you gave me, would that be the way I should use to get a .json 99% of the time? From an API

spring flax
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
alpine pewter
#

Okay, got it.
The issue I was having before is someone told me there was "x" amount of time for me to get a response, or I get an error.
So, they said to add a "follow-up" interaction at the bottom.

I added the command you said into it and put it back to a regular response, it's still not fast enough, I'm not sure what to do or what I might be doing wrong

spring flax
alpine pewter
#

Oh, it was that, they just said to add both

#

And do either of you mind checking the code?

spring flax
#

You don't need follow up if it is your first interaction response

#

Show the code

alpine pewter
#

It works 100%, it just takes too much time otherwise as a regular command, it's only like 6-8 lines in the actual .json

#

Here's a tag - CameronBryce-11490 for the battle_net

#
    raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

That's the error

#

https://overwatch-api.tekrop.fr/player/CameronBryce-11490/info

spring flax
#

15277667 what is this color value?

alpine pewter
#

Looks like that when it works

#

That's the color value ^

spring flax
alpine pewter
#

Mhm, that's what they said.
Would there be a fix or is it just an issue with the endpoint?

#

It's only like 5-6 lines, not sure why it would take so long to go through

spring flax
#

you can defer it

#

iirc

alpine pewter
#

Okay, I'll probably just go back to doing that for that endpoint.
Thank you pplz for showing me how to use the aiohttp though, I appreciate the help

slate swan
#

not "you can", you have to

spring flax
#

!d disnake.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

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

without defer you have 3 seconds to respond to the interaction but with defer you have 15 minutes

alpine pewter
slate swan
#

after doing that, just do
await interaction.edit_original_message(content=..., embed=...) everything is a kwarg in this

sullen pewter
#

Will this work

alpine pewter
#

Would there be a way to shorten the time?

slate swan
alpine pewter
#

Like, if someone types something in wrong

sullen pewter
slate swan
#

?

slate swan
#

!d discord.on_member_remove

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
spring flax
#

Oh in that it's talking about the join event also

alpine pewter
#

Let's say someone typed in something wrong, would there be a way for it to immediately cancel sooner?
So it's not "thinking" for 15m

spring flax
#

It doesn't think for 15 minutes

#

You have 15 minutes to respond to the interaction

alpine pewter
#

So, how would I get it to go away then?
Sorry, this is new to me.

spring flax
spring flax
alpine pewter
spring flax
#

Are you getting any error,

alpine pewter
#

Nope, just nothing comes back at all.
It keeps running when you enter a false profile

#

Ahh, I figured it out, nvm. Thank you

jolly basalt
#

Can I ban my bot from every single server without being in them?

#

or altleast know in which all servers my bot is on?!

#

oh no

torn sail
unkempt canyonBOT
jolly basalt
#

Thank you soo much

#

i had accidently posted my discord.dev url

obtuse creek
#

@slate swan

jolly basalt
#

If there are four buttons A,B,C and D, how do I know what button has been pressed. Please send an example cuz my brain is kinda fried

cloud dawn
spring flax
#

like if I use py async def
in a codeblock the output is pyasync def

buoyant zodiac
#

how to do an event inside of cogs?

#

nvm i j remembered

spring flax
#

!d discord.ext.commands.Cog.listener

unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
dull sorrel
#

Anyone knows why this is not working?
if message.content == f"<@{client.user.id}>":

   await message.channel.send("Hello", reference = message)
#

The bot does not send the text when mentioned.

gaunt ice
#

await message.reply("")

slate swan
#

i had a really simple q, how do i make a command that works only for those roles that have specific perms, like ban works only with ban members permission

spring flax
unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
#

thankyou

#

is there any list that indicates how all permissions can be used in the above function?

like
kick_members
ban_members

and so on..

slate swan
#

thanks

exotic kite
#

d

#

!d

unkempt canyonBOT
exotic kite
#

!d commands

unkempt canyonBOT
#

commands [bpnumber]```
Specify a list of commands for breakpoint number *bpnumber*. The commands themselves appear on the following lines. Type a line containing just `end` to terminate the commands. An example:

```py
(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)
```  To remove all commands from a breakpoint, type `commands` and follow it immediately with `end`; that is, give no commands.

With no *bpnumber* argument, `commands` refers to the last breakpoint set...
exotic kite
#

!d pip install discord

unkempt canyonBOT
#
pip

%pip```
Run the pip package manager within the current kernel.
slate swan
#

hi

sullen pewter
#

How to fix {member}?

#

I need it to send member username. Not {member}

cold sonnet
#

make it an f-string

#

f"User {member} blabla"

#

and you don't need to create a variable

sullen pewter
#

Ok

cold sonnet
#

just await ctx.send(discord.Embed(...))

sullen pewter
#

Ty

cold sonnet
#

👍

#

wait am I dumb

#

yes, you do need embed=

#

forgot about kwargs for a moment

sullen pewter
#

Alr

humble gulch
#

help me please

#

how can i make discord bot

supple thorn
humble gulch
#

in repl it plz

#

will u help me??

supple thorn
#

!pypi discord

unkempt canyonBOT
supple thorn
unkempt canyonBOT
humble gulch
#

can u use replit??

supple thorn
humble gulch
#

i know how to host 24/7

supple thorn
supple thorn
#

How exactly

humble gulch
humble gulch
#

can we talk in dms??

#

hlo?

supple thorn
# humble gulch no 😢

It's not recommended trying to tackle making a discord bot without having any basic python knowledge

supple thorn
#

You'll get stuck easily at problems which you could of avoided if you knew basic python

supple thorn
#

We help people with their problems

#

We help them through it

sullen pewter
#

How can I make it orange?

#

Colour=?

supple thorn
#

Damn

sullen pewter
#

How can I make it work?

#

Wtf

#

<@&831776746206265384>

#

<@&267628507062992896>

tall dust
#

!cban 950994265377480705 nsfw

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @celest grove permanently.

#

According to the API, your request is malformed.

sullen pewter
#

1 min and 1 sec for mods to respond

deep sorrel
sullen pewter
#

Oh, ok

deep sorrel
#

Thanks

supple thorn
#

I had to search the docs

sullen pewter
#

Tysm

slate swan
#

how do i print "you are missing {perms} permissions"

sullen pewter
#

How can I add this

embed.set_author(name="vcokltfre", icon_url="https://avatars.githubusercontent.com/u/16879430")
#

Here:

abstract kindle
#

heyo

versed heart
#

!pypi aiohttp

unkempt canyonBOT
versed heart
abstract kindle
#

sometimes my commands bring up specific errors I have made, and sometimes they just bring up a check error

#

I have an 'unregistered' error and a decorator that I have on some of my commands. But some of those commands don't bring up that error and some do.

sullen pewter
#

How can I add this

embed.set_author(name="vcokltfre", icon_url="https://avatars.githubusercontent.com/u/16879430")
versed heart
#

Guys, I want to make my discord bot wait for user reply, what do i do?

proud rain
#

Why am i buttons not being send?

slate swan
#

Show code

proud rain
#
@Client.command()
async def button(ctx):
    await ctx.send(
        "",
        components = [
            Button(style=ButtonStyle.red, label = 'test!') 
        ]
    )
    interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
    await interaction.respond(content="test")```
slate swan
#

Sorry i dont use these type of buttons

proud rain
#

i have a very nice calculator with buttons but its not sending :(

slate swan
proud rain
slate swan
#

Or wait here

#

Someone will help

proud rain
#

okay, thanks man

slate swan
#

@slate swan i ghost ping u by mistake

proud rain
#

xD

slate swan
#

Xd

#

Huh which ide

#

Repl it?

twin nest
supple thorn
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
zinc phoenix
#

Hi guys, I'm making a simple discord bot using discord.py but I cant use commands alongside with events, I have tried adding await bot.process_commands(message) but its not working either, can anyone help?

zinc phoenix
#
from datetime import datetime
import pytz
from datetime import date
from discord.ext import commands
bot = discord.Client()
prefix="??"
bot = commands.Bot(command_prefix = prefix)
my_time = datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).time()
my_date = date.today()


@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))
    


@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    if message.content.startswith("hello"):
        await message.channel.send("hi")
    if message.author == bot.user:
        return
    if message.content.startswith("timern"):
        await message.channel.send("Bây giờ là " + str(my_time))
    await bot.process_commands(message)

@commands.command()
async def datern(ctx):
  await ctx.send("cc")
 

bot.run(token)```
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.

zinc phoenix
#

Hm I have to add py

#
import discord
from datetime import datetime
import pytz
from datetime import date
from discord.ext import commands
bot = discord.Client()
prefix="??"
bot = commands.Bot(command_prefix = prefix)
my_time = datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).time()
my_date = date.today()


@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))
    


@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    if message.content.startswith("hello"):
        await message.channel.send("hi")
    if message.author == bot.user:
        return
    if message.content.startswith("timern"):
        await message.channel.send("Bây giờ là " + str(my_time))
    await bot.process_commands(message)

@commands.command()
async def datern(ctx):
  await ctx.send("cc")
 

bot.run(token)```
supple thorn
zinc phoenix
#

I thought I would need to add the client and the command thing

supple thorn
#

Also why are you using the @commands.command() decorator

#

That's for when you're in a cog

zinc phoenix
#

Oh

supple thorn
#

That wouldn't work would anyways

#

It's @bot.commands

zinc phoenix
#

Thanks

supple thorn
#

You only need the commands.Bot instance since that inherits discord.Client

zinc phoenix
#

Oh

hollow carbon
#

What i am wrong nee help !!!

zinc phoenix
#

Wow it works now, thanks

supple thorn
supple thorn
#

Yours is deF

#

Just change the F to an uncapitalized one

hollow carbon
#

stupid sorry

#

😂

#

LMAO

cold sonnet
#

wth is a Cog_Extension

#

how is self.bot defined?

jade garden
#

whats the error?

hollow carbon
#

Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).
A feature of objects is that an object's own procedures can access and often modify th...

hollow carbon
cold sonnet
#

that's not gonna explain

hollow carbon
cold sonnet
#

is it from a third party library?

jade garden
hollow carbon
jade garden
hollow carbon
#

i guess

#

i am new too

slate swan
#

any good json tutorial website pls?

hollow carbon
slate swan
#

ok

smoky anvil
#

Someone who can help, how to do a giveaway bot with invite require ment?

slate swan
smoky anvil
#

ok

hollow carbon
#

What i am wrong

slate swan
hollow carbon
slate swan
#

delete one of them

hollow carbon
slate swan
#

np

hollow carbon
#

:)

winged cloud
#

what is async

maiden fable
#

!d async

unkempt canyonBOT
#

8.9. Coroutines

New in version 3.5.

winged cloud
#

and what is ctx

abstract kindle
#

how would I run a while loop while waiting for a response to a message?

maiden fable
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
winged cloud
#

thank you

abstract kindle
#

I want to run code and at the same time have bot.wait_for still going

azure depot
#

how i can make inventory command using sqlite database?
i want it to be like:

123...      | name of        | current 
                 | item player | amount of
                 | has been      | item player
                 | obtain           | have```
slate swan
#

👋

sullen pewter
#

Are there any tutorials for making ticket system?

junior verge
#

!paste

abstract kindle
#

Lol

modest plover
#

Hiya, so I gots a few issues

    @commands.slash_command()
    async def animals(self, inter, animal: AnimalsOptRand):
        if animal == "random":
            animal = random.choice(AnimalsOpt)
            print(animal)
        if animal == "duck":
            async with aiohttp.ClientSession() as session:
                async with session.get("https://random-d.uk/api/v2/random") as resp:
                    data = json.loads(await resp.text())
                    duckEmbed = disnake.Embed(
                        title = "Duck!"
                    ).set_image(
                        url = data['url']
                    ).set_footer(
                        text = "Powered by Random Duck")
                    await inter.response.send_message(embed = duckEmbed)
        elif animal == "fox":
            async with aiohttp.ClientSession() as session:
                async with session.get("https://randomfox.ca/floof") as resp:
                    data = json.loads(await resp.text())
                    foxEmbed = disnake.Embed(
                        title = "Fox!"
                    ).set_image(
                        url = data['image']
                    ).set_footer(
                        text = "Powered by Random Fox")
                    await inter.response.send_message(embed = foxEmbed)

This doesn't work, I get a KeyError
Anyone know why?

#
| Python Version: 3.10.2
Ignoring exception in slash command 'animals':
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 597, in invoke
    await call_param_func(self.callback, inter, self.cog, **kwargs)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/params.py", line 778, in call_param_func
    return await maybe_coroutine(safe_call, function, **kwargs)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/utils.py", line 561, in maybe_coroutine
    return await value
  File "/storage/emulated/0/coding/discord-bots-repo/disarray/commands/animals.py", line 43, in animals
    animal = random.choice(AnimalsOpt)
  File "/data/data/com.termux/files/usr/lib/python3.10/random.py", line 378, in choice
    return seq[self._randbelow(len(seq))]
  File "/data/data/com.termux/files/usr/lib/python3.10/enum.py", line 440, in __getitem__
    return cls._member_map_[name]
KeyError: 4

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

Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1332, in process_application_commands
    await app_command.invoke(interaction)
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/disnake/ext/commands/slash_core.py", line 606, in invoke
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 4
stuck oyster
#

I am trying to code an event that deletes a channel in a specific category every 30mins

#

can someone help me, I don't know how to start it

spice shore
boreal ravine
#

use tasks instead

stuck oyster
green bluff
#

if i put it

#

before client.run(token)

boreal ravine
#

!d discord.ext.tasks.loop read this first

unkempt canyonBOT
#

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

how do i get the contents of a discord.File as a str?

stuck oyster
boreal ravine
stuck oyster
#

yes I did

boreal ravine
#

did you read it?

stuck oyster
spring flax
#

oh my

boreal ravine
spring flax
#

use @commands.Cog.listener() first of all, you've missed the paranthesis

stuck oyster
spring flax
#

yes

stuck oyster
boreal ravine
#

now use tasks

spring flax
#

no, use it as a decorator

boreal ravine
stuck oyster
#

decorator?

#

how

spring flax
#

yes, your @commands.Cog.listener() is a decorator

#

!decorators

unkempt canyonBOT
#

Decorators

A decorator is a function that modifies another function.

Consider the following example of a timer decorator:

>>> import time
>>> def timer(f):
...     def inner(*args, **kwargs):
...         start = time.time()
...         result = f(*args, **kwargs)
...         print('Time elapsed:', time.time() - start)
...         return result
...     return inner
...
>>> @timer
... def slow(delay=1):
...     time.sleep(delay)
...     return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!

More information:
Corey Schafer's video on decorators
Real python article

spring flax
stuck oyster
#

I should put it in ()

boreal ravine
#

No

boreal ravine
spring flax
#

it starts with @ so it's a decorator

stuck oyster
#

oh wait

spring flax
#

have you done from disnake.ext import tasks?

stuck oyster
#

yes

#

those the commands have to be there?

spring flax
#

then use the decorator how kayle showed above.

stuck oyster
#

ok

#

how would I get the bot to delete a channel in a specific category

boreal ravine
#

get the category object -> get the channel -> .delete() it

stuck oyster
#

alright

abstract kindle
#

I'm running an async function as a task and I want to yield a result from it every time it loops so that I can update another function

spring flax
abstract kindle
#

How would I yield it without 'yielding' it, because it won't let me create tasks out of generator objects

boreal ravine
#

Why are you awaiting a property

stuck oyster
#

what do you mean

boreal ravine
#

why?

stuck oyster
boreal ravine
#

thats not how you get a category

stuck oyster
#

oh

boreal ravine
#

!d discord.ext.commands.Bot.get_channel this is how to get a category

unkempt canyonBOT
stuck oyster
#

thats for channels

boreal ravine
#

A category is a channel

stuck oyster
#

huh

#

so it would just be like this?

bleak karma
#

help? im trying to make a slash command but it gives me this error when syncing the commands

Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py:416> exception=Forbidden('403 Forbidden (error code: 50001): Missing Access')>
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 440, in sync_all_commands
    existing_cmds = await self.req.get_all_commands(guild_id=scope)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 332, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
boreal ravine
#

No, it's a method so call it and pass in a valid category ID

#

yes

#

but thats gonna delete the category

stuck oyster
#

oh

#

ok, How do I make it delete a specific channel maybe a unique name like (#BattBattling) only in the Closed Category

bleak karma
# boreal ravine Does your bot have the application.commands scope?

i forgot about that but theres another error

Task exception was never retrieved
future: <Task finished name='Task-1' coro=<SlashCommand.sync_all_commands() done, defined at C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py:416> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn name: String value did not match validation regex.')>
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 492, in sync_all_commands
    raise ex
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord_slash\client.py", line 472, in sync_all_commands
    existing_cmds = await self.req.put_slash_commands(
  File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 338, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: String value did not match validation regex.
#

what causes this error?

boreal ravine
boreal ravine
stuck oyster
#

because guild is not defined

boreal ravine
stuck oyster
#

yes it does

boreal ravine
#

use that then ig

stuck oyster
#

ok so if I want to do multiple name

#

correct?

slate swan
#

the iterable comes as the first positional argument

stuck oyster
#

explain in a simpler term please

boreal ravine
#

thats get

#

no

stuck oyster
slate swan
boreal ravine
#

call find again

#

with another name

stuck oyster
#

?

vale wing
#

Are you searching for text channels only or not

stuck oyster
vale wing
#

Because if so, you could use discord.utils.get cause there's no need to lower the channel name, as they are always lowercased

slate swan
#

Knock knock

vale wing
#

Who's there?

#
channel = discord.utils.get(guild.text_channels, name="kayle")```
For example
thorn ore
#

channel = guild.get_channel(channel id here)

stuck oyster
slate swan
vale wing
thorn ore
#

Yes

vale wing
slate swan
slate swan
thorn ore
vale wing
#

Anyways it is much better to get the channel by its ID

thorn ore
#

Yea

stuck oyster
#

yes it is but there will be different channels with the same name

slate swan
#

Ye that would work too

thorn ore
#

Do

channel = guild.get_channel(channel id here)
stuck oyster
vale wing
#

For different guilds?

#

Then use a database

stuck oyster
#

I want it to delete any channel with the name battbattling

stuck oyster
vale wing
#

Oh then just use a for loop

thorn ore
#

Bro what you want? Tell me problem I will tell if I know?

vale wing
#
for channel in guild.text_channels:
    if channel.name == "battbattling":
        await channel.delete()```
stuck oyster
vale wing
#

It will work even if there are multiple channels with that name

thorn ore
#

I will tell a easy code

vale wing
thorn ore
slate swan
stuck oyster
#

so when someone renames the channel to #battbattling it will delete then log it somewhere
battbattling - 1

thorn ore
#
@client.command()
async def delete(ctx, channel=ctx.message.channel):
     for c in channel:
         try:
             await c.delete()
          except:
              print(f"{c} deleted")

stuck oyster
#

no, its not supposed to be a command

thorn ore
#

Then?

thorn ore
#

Why?

stuck oyster
#

it will automatically delete

thorn ore
#

Oh

slate swan
# thorn ore Why?

It should just be channel and when u call the function u name the value

slate swan
#

Oh wait u got try mb

thorn ore
#

I did it

#

@stuck oyster

stuck oyster
#

did what?

thorn ore
#
delete_channel=[
      "Channel name here"
]

await delete_channel.delete()
slate swan
# stuck oyster did what?

But look that is going to be a problem when u make a logs channel because there is a function like on_member_ban(member) and u will try to send this to the logs but this function only excepts one argument you will need guild to get the channel name

stuck oyster
#
    @tasks.loop(seconds = 5)
    async def loop(self):
        names_tuple = "batt-done"
        for channel in self.guild.text_channels:
            if channel.name in (names_tuple):
                await channel.delete()```
#

wasn't deleted

junior verge
#

How to get membercount?

thorn ore
#

Yea what you want

junior verge
#

get the membercount, just .membercount will return the members in the server like 10

stuck oyster
junior verge
#

ty

#

how do you define that tho

thorn ore
#
@clientt.command(name='membercount')
async def membercount(ctx):
    await ctx.send(len(guild.member_count))
junior verge
#

ah ye ty

#

how do you define guild?

junior verge
thorn ore
#

It will not tell guild is not specified

#

Brrooo run codee first

junior verge
#

sure chill

thorn ore
#

Or

slate swan
thorn ore
#
@client.command(name='membercount')
async def membercount(ctx):
    await ctx.send(ctx.guild.member_count)

junior verge
#

ty\

stuck oyster
#
    @tasks.loop(seconds = 5)
    async def loop(self):
        delete_channel=[
            "batt-done",
            "sun-done"
        ]
        
        await delete_channel.delete()```
the channel is still there
junior verge
#

huh

#

its ctx.guild

thorn ore
#

Yea

junior verge
#

yeah I did that lol but code didnt update or sum

thorn ore
#
channel = "name of channel"
 
for c in channl:
     try:
          await c.delet()
      except: 
           print("{c} deleted")
tough lance
#

Bro why are you taking Len of number of guild members

junior verge
versed heart
junior verge
#
@commands.command(name='membercount', description="Returns a number of people in the server", aliases=['mc'])
    async def membercount(self, ctx):
        await ctx.send(len(ctx.guild.member_count))
slate swan
thorn ore
#

That's too easy

junior verge
#

alright

junior verge
#

Who said that lol

thorn ore
#

Bro

vale wing
#

Did you make a typo or smth

cold sonnet
#

nothing there makes sense

vale wing
#

And yeah that looks weird

thorn ore
vale wing
#

First str.delete wtf

cold sonnet
#

!d discord.TextChannel.history guess you wanna loop through this?

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
vale wing
#

Why are you iterating the string

tough lance
#

What are you even trying to do

thorn ore
#

@vale wing can't understand

cold sonnet
vale wing
#

!e py channel = "nice name" for c in channel: print(c)

unkempt canyonBOT
#

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

001 | n
002 | i
003 | c
004 | e
005 |  
006 | n
007 | a
008 | m
009 | e
thorn ore
#

!e

channel = "name of channel"
 
for c in channl:
     try:
          await c.delet()
      except: 
           print("{c} deleted") 
unkempt canyonBOT
#

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

001 |   File "<string>", line 6
002 |     except: 
003 |             ^
004 | IndentationError: unindent does not match any outer indentation level
cold sonnet
#

and you made some typos

slate swan
thorn ore
#

me?

cold sonnet
#

your computer is screaming of errors

slate swan
cold sonnet
#

maybe he wanted to delete the messages

tough lance
#

You mean channel is supposed to be a list?

cold sonnet
#

in that specific channel

vale wing
#

Maybe he meant delete all channels 😳

thorn ore
cold sonnet
vale wing
thorn ore
#

I am done

#

Bye

vale wing
#

That's simple list iteration lol

thorn ore
#

S

cold sonnet
slate swan
#
@tasks.loop(seconds = 5)
    async def loop(self):
        delete_channel=[
            "batt-done",
            "sun-done"
        ]
        for t in delete_channel:
          await bot.delete_channel(t)

idk if this really works but give it a try

thorn ore
#

K

vale wing
#

This doesn't most likely

#

Does bot even have delete_channel method

cold sonnet
#

nah

vale wing
#

You typically do it like TextChannel.delete()

cold sonnet
#

that's not it anymore

slate swan
stuck oyster
#

hm

vale wing
slate swan
vale wing
#

That's what I did

#

Why won't they just look at that lol

stuck oyster
# vale wing I have already made that thing
    @tasks.loop(seconds = 5)
    async def loop(self):
        for channel in self.guild.text_channels:
            if channel.name == "batt-done":
                await channel.delete()``` 
didn't work with `batt-done`
vale wing
#

Probably your self.guild is wrong

#

Or you didn't start the loop

tough lance
#
@tasks.loop(seconds=5)
async def loop():
    guild = bot.get_guild(Id)
    channel = discord.utils.get(guild.channels, name="batt-done")
    await channel.delete()
vale wing
#

Omg

spice shore
stuck oyster
#

guild isnt defined so I need to add self

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
vale wing
#

Probably you did something like

if condition:
    try:
        ...
      except: < issue is here
        ...```
tough lance
slate swan
stuck oyster
#

cause I won't be there to delete the channels

vale wing
#

Just use the method I suggested lol no need for such loop

tough lance
#

I think a tasks.loop would be better in this case for an async environment

spice shore
vale wing
#

What IDE are you using?

jade jolt
spice shore
vale wing
tough lance
#

No they want to delete as soon as it's named ___

vale wing
spice shore
#

Nope

#

It just shows the Error in the Console

vale wing
#

😂 wtf

#

Use VSC or PyCharm then

#

You will see all the syntax issues immediately

tough lance
#

As far as I remember replot does highlight indent errors as red lines

spice shore
#

Ehm what do i do here

vale wing
#

It is highlighted alright

#

def setup no indent

#

The content of that function should be indented

#

Also you don't put that function into the cog

#

It should be in the file but not in the cog

stuck oyster
#
    @tasks.loop(seconds = 5)
    async def loop(self):
        for channel in self.guild.text_channels:
            if channel.name == "batt-done":
                await channel.delete()```