#discord-bots

1 messages · Page 1092 of 1

shrewd apex
#

yeah thats fine but there should be reason why it dosent work rightpithink

#

ok so i went for a crude approach ||atleast it works||

    view.message = await ctx.send()
    await view.wait()
    for item in view.children: item.disabled = True
    await view.message.edit(view=view)
granite parcel
#

adding multiple partial emoji in discord server?

shrewd apex
#

partial emoji?

granite parcel
#

yeah

#

!d discord.PartialEmoji

unkempt canyonBOT
#

class discord.PartialEmoji```
Represents a “partial” emoji.

This model will be given in two scenarios:

• “Raw” data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")

• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.reactions "discord.Message.reactions")...
maiden fable
unkempt canyonBOT
#

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

Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
granite parcel
maiden fable
unkempt canyonBOT
#

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

Creates a [`Sticker`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Sticker "discord.Sticker") for the guild.

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

New in version 2.0.
slate swan
#

Does timeout has a time limit?

mortal thistle
#

ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)

#

how do I fix it?

granite parcel
mortal thistle
#

my first line is from discord.ext import commands

vale wing
#

I am asking you to check if it works

mortal thistle
granite parcel
#
import discord
from discord.ext import commands```
mortal thistle
#

ok

maiden fable
unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
maiden fable
#

Yes

shrewd apex
#

hunter u know how to post reqs or upload using python? or requests lib...

slate swan
#

ghost ping owo

slate swan
#

oh what was it?

#

nothing leave it

slate swan
vale wing
#

If I parse IDs to test_guilds of Bot constructor (disnake), will it sync the commands for other guilds or nah

slate swan
#

yeah 28 days

#

ohh

#

then role mute better

slate swan
shrewd apex
#

sarth

vale wing
#

Ok is there any way to speedup the sync for certain guilds but make it sync the other commands for the rest of guilds

slate swan
#

wots the error?

shrewd apex
#

no error

#

then function dosent run on timeout at all

vale wing
#

And did you try subclassing

slate swan
#

do you call the disabled function?

shrewd apex
#

no it's just a rudimentary bot so the error should show

shrewd apex
vale wing
#

Assigning functions isn't a good idea, subclass View instead

shrewd apex
#

yeah subclassing is fine but it's just a small button reaction part a tick and a cross

vale wing
#

Better practice + better looking + more readable + less flooding + most likely will work

slate swan
vale wing
#

No I mean like make some guilds sync like they are test ones but still sync the commands for other guilds

shrewd apex
#

also i should find out at least what is going wrong right?

vale wing
#

Not command-specific

vale wing
shrewd apex
#

do u think like it could be a bug or some problem with the dpy lib i can't think of any other reason

vale wing
#

Why not just do this

class View(discord.ui.View):
    async def on_timeout(self):
        ...

view = View(timeout=15)```
shrewd apex
#

i did that now

dim sentinel
#

people

#

ModuleNotFoundError: No module named 'discord'

#

why doesnt this work

vocal snow
latent yarrow
#
Traceback (most recent call last):
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 467, in _actual_conversion
    return converter(argument)
TypeError: ABCMeta.__new__() missing 2 required positional arguments: 'bases' and 'namespace'

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

Traceback (most recent call last):
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
    raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".```
#

this is my Error when i run my command

#

here is my command

#
@commands.has_permissions(kick_members=True)
async def mute(ctx, member=discord.Member,reason="No reason"):
    guild=ctx.guild
    mutedrole=discord.utils.get(name="Muted")

    if not mutedrole:
        await ctx.send(f"No Muted Role Found in {ctx.guild}..Creating One Now")
        await ctx.send("Wait..")
        await guild.create_role(name="Muted")
        await ctx.send("Done...")

     if member == ctx.author:
        em1=discord.Embed(title="Mute Err",description=f"{ctx.author} You can't mute Yourself",colour=discord.colour.random())
        await ctx.send(embed=em1)
        for channel in guild.channels:
            await channel.set_permissions(mutedrole, speak=False, send_messages=False, read_message_history=False, read_messages=False)
            em2=discord.Embed(title="**Sucsessfully Muted**",description=f"{member.mention} Has been Muted",colour = discord.colour.random())
            em2.add_field(name="Reason",value={reason},inline=False)
            em3=discord.Embed(title="**You have been Muted**",description=f"{member.mention} Has been Muted in {ctx.guild}",colour = discord.colour.random())
            em2.add_field(name="Reason",value={reason},inline=False)
            await ctx.send(embed=em2)
            await member.add_roles(mutedrole, reason=reason)
            await member.send(embed=em3)```
#

this is my command

#

@hot plaza

#

help

#

pls @hot plaza

#

anyone help

shrewd apex
#
Ignoring exception in command mute:
Traceback (most recent call last):
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 467, in _actual_conversion
    return converter(argument)
TypeError: ABCMeta.__new__() missing 2 required positional arguments: 'bases' and 'namespace'

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

Traceback (most recent call last):
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
    return await self.do_conversion(ctx, converter, argument, param)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
    return await self._actual_conversion(ctx, converter, argument, param)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
    raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".
#
@client.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member=discord.Member,reason="No reason"):
    guild=ctx.guild
    mutedrole=discord.utils.get(name="Muted")

    if not mutedrole:
        await ctx.send(f"No Muted Role Found in {ctx.guild}..Creating One Now")
        await ctx.send("Wait..")
        await guild.create_role(name="Muted")
        await ctx.send("Done...")

     if member == ctx.author:
        em1=discord.Embed(title="Mute Err",description=f"{ctx.author} You can't mute Yourself",colour=discord.colour.random())
        await ctx.send(embed=em1)
        for channel in guild.channels:
            await channel.set_permissions(mutedrole, speak=False, send_messages=False, read_message_history=False, read_messages=False)
            em2=discord.Embed(title="**Sucsessfully Muted**",description=f"{member.mention} Has been Muted",colour = discord.colour.random())
            em2.add_field(name="Reason",value={reason},inline=False)
            em3=discord.Embed(title="**You have been Muted**",description=f"{member.mention} Has been Muted in {ctx.guild}",colour = discord.colour.random())
            em2.add_field(name="Reason",value={reason},inline=False)
            await ctx.send(embed=em2)
            await member.add_roles(mutedrole, reason=reason)
            await member.send(embed=em3)
#

it is discord.utils.get(ctx.guild.roles, name='Muted')

shrewd apex
#

also do
member: discord.Member, *, reason

placid verge
#

btw ur code is wrong

#
await member.add_roles(mutedrole, reason=reason)
shrewd apex
#

mine?

placid verge
#

no not urs

shrewd apex
#

yeah that part too well i didn't see all of it

placid verge
#

u should probably do smth like this```py
mutedrole = await guild.create_role(name="Muted")

vale wing
#

Also please format your code

#

It's pain to read

stiff gorge
#
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'os' has no attribute 'evniron'
    @commands.hybrid_command(aliases=['shorteen'])
    async def bitly(self,ctx, *, link):
      bitlykey = os.evniron['bitly_key']
      async with aiohttp.ClientSession() as session:
        async with session.get(f'https://api-ssl.bitly.com/v3/shorten?longUrl={link}&domain=bit.ly&format=json&access_token={bitlykey}') as req:
          r = await req.read()
          r = json.loads(r)
          new = r['data']['url']
          em = discord.Embed(title='Shorten Link',
                             color=0x2f3136)
          em.add_field(name='Shortened link', value=new, inline=False)
          await ctx.send(embed=em)
#

i have imported os why do i get this error

slate swan
#

its env not evn

#

is there a way to get the client.user.default_role?

scarlet aurora
#

check_role = discord.utils.get(user.guild.roles) will this return the NAME of the rank?

dim sentinel
#

so i need to a word from user

scarlet aurora
dim sentinel
#

then a desired number of times it to be repeated

#

i can't get it

#

can someone help with it?

#
@spi.command()
async def ping(ctx,*,pong,number):
    await ctx.send(pong*number)
#

help would be appreciated

slate swan
#

or check_role = discord.utils.get(user.guild.roles, id = int)

scarlet aurora
#

now I want to get the role name

scarlet aurora
#

pretend I don't know the name of the role

#

i want to know what role this person has

slate swan
#

oh

shrewd apex
scarlet aurora
#

ty

slate swan
#
for role in user.roles:
   return role.name```
slate swan
scarlet aurora
#

how can I check if a specific role is among the persons role(s)

dim sentinel
scarlet aurora
dim sentinel
scarlet aurora
#

so for example, if you type !pong 10

#

it sends pong 10 times?

dim sentinel
#

yes, I want it to work like that.

scarlet aurora
#
@bot.command()
async def ping(ctx, number = 1):
  for i in number:
    print("pong")
#

hold on

#

lemme test it

#

actually u test it

dim sentinel
#

yeah on that

scarlet aurora
#

!e @bot.command()
async def ping(ctx, number = 1)
for i in number:
print("pong")

unkempt canyonBOT
#

@scarlet aurora :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     async def ping(ctx, number = 1)
003 |                                    ^
004 | SyntaxError: expected ':'
dim sentinel
#

woops

scarlet aurora
#

!e @bot.command()
async def ping(ctx, number = 1)
for i in number:
print("pong")

unkempt canyonBOT
#

@scarlet aurora :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 2
002 |     async def ping(ctx, number = 1)
003 |                                    ^
004 | SyntaxError: expected ':'
scarlet aurora
#

!e @bot.command()
async def ping(ctx, number = 1):
for i in number:
print("pong")

unkempt canyonBOT
#

@scarlet aurora :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
scarlet aurora
#

ok it works

#

test it

dim sentinel
#

which one works

stiff gorge
#

how to make the uptime show like this <t:1624385691:R>

    @commands.hybrid_command()
    async def uptimeee(self,ctx):
      uptime = datetime.utcnow() - start_time
      hours, remainder = divmod(int(uptime.total_seconds()), 3600)
      minutes, seconds = divmod(remainder, 60)
      days, hours = divmod(hours, 24)
      await ctx.send(f"** I have been online for  `{days}` Days, `{hours}` Hours, `{minutes}` Minutes, `{seconds}` Seconds.**")
scarlet aurora
#
@bot.command()
async def ping(ctx, number = 1):
  for i in number:
    print("pong")```
slate swan
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
torn sail
#

Style is R

scarlet aurora
#

@dim sentinel lemme know if it works

slate swan
#

is there a way to get client(my bot) role? the main/default one?

dim sentinel
odd mango
#

hey, in my help command i define my command signature like thispy signature = self.helpcommand.get_command_signature(command)
it returns whole command syntax like the following

slate swan
#

!d discord.Guild.self_role @slate swan

unkempt canyonBOT
#

property self_role```
Gets the role associated with this client’s user, if any.

New in version 1.6.
odd mango
#

how do i define command and syntax differently

scarlet aurora
odd mango
dim sentinel
# scarlet aurora all u do is >ping 2103
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not iterable
scarlet aurora
#
@bot.command()
async def ping(ctx, num: 1):
  for range(num):
    print("pong")```
slate swan
#

number is undefined, and youre looking for range(num)

dim sentinel
scarlet aurora
#
    @commands.command()
    @commands.is_owner()
    async def promote(self, ctx, user: discord.Member = None):

        roles = []

        for role in user.roles:
            roles.append(role.name)

        Assault_Marine = discord.utils.get(user.guild.roles, name='Assult Marine')
        Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')


        if user is None:
            await ctx.send("Choose someone to promote")

        else:
            if 'Assault Marine' in roles:

                await user.remove_roles(Assault_Marine)
                await user.add_roles(Seeker_Marine)

                await ctx.send(f"Sucsesfully promoted ``{user}``")``` Can someone tell me why this wont work?
scarlet aurora
odd mango
#

how do i define a!pokestat and <pokemon> separately? anyone?

unkempt canyonBOT
#
Missing required argument

code

lyric apex
#

Bytes To File?

#

Is that possible

slate swan
#
with open("uwu.jpg", "wb") as f:
  f.write(BytesObject)

''' async '''

import aiofiles

async with aiofiles.open("uwu.jpg", "wb") as f:
  await f.write(BytesObject)
slate swan
#

traceback*

scarlet aurora
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
slate swan
#

it's better to move the user is None to the top
and instead of i (in the image below) use a list comprehension which may be slightly faster

roles = [role.name for role in user.roles]
and it's good if you name the parameter user to member as it is gonna be an instance of discord.Member and not discord.User for which the usage of user as a parameter name would have been suitable

maiden fable
slate swan
scarlet aurora
#
Traceback (most recent call last):
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\llVll\Desktop\Luna Bot\cogs\utils.py", line 100, in promote
    await user.remove_roles(Assault_Marine)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 822, in remove_roles     
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

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

Traceback (most recent call last):
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
slate swan
#

nice, Assault_Marine is None

maiden fable
#

Assault_Marine role is None

#

Not Seeker_Marine

slate swan
#

my bad, sorry hunter

mortal thistle
#
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
radiant junco
#

how would i get the message content of a message that a user replied to?
for example,

if i sent this message
and then replied to the message on top with a command
how would the bot get the first message

slate swan
radiant junco
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

mortal thistle
maiden fable
slate swan
#

it couldnt find such folder meaning your installation is corrupted

mortal thistle
#

oh

#

thanks for the guide guys

#

I was struggling with this since evening

stable leaf
#

I am making a starboard on my bot but it doesn't work (i'll send code)

slate swan
#

shouldn't you have sent it along with the message-

stable leaf
#
@client.event
async def on_raw_reaction_add(payload):
    emoji = payload.emoji
    guild = client.get_guild(payload.guild_id)
    channel = await guild.get_channel(payload.channel_id)
    message = await channel.get_message(payload.message_id)

    if emoji.name == "⭐️":
        async with client.db.cursor() as cursor:
            await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
            data = await cursor.fetchone()
            if data:
                starData = data[0]
                channelData = await guild.get_channel(data[1])
                for reaction in message.reactions:
                    if reaction.emoji == "⭐️":
                        if reaction.count >= starData:
                            embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
                            await channelData.send(embed=embed)
#

the error is on line 5 TextChannel can not be awaited

slate swan
#

channelData = await guild.get_channel...

remove the await.

stable leaf
#

then i get another error

crisp drift
#

get message isnt a coro neither

stable leaf
#

on line 6 message does not have get_message()

slate swan
#

!d discord.abc.Messageable.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
stable leaf
#

and if i remove that i'll get no errors and the code doesn't work

slate swan
#

you first need to differentiate between normal methods and coroutines get_xs in discord.py are normal functions and don't need to be awaited
fetch_xs are coroutines/awaitables

lyric apex
#
Union[discord.Emoji, discord.PartialEmoji]``` 
what is this
slate swan
unkempt canyonBOT
#

typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.

To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Using that shorthand is recommended. Details...
lyric apex
#

NycQtpie

slate swan
#

where do you need it?

lyric apex
#

In code?

stable leaf
#

@slate swan how can i fix it then?

slate swan
stable leaf
#

ok

slate swan
lyric apex
slate swan
#

is that a command argument typehint?

slate swan
stable leaf
#

so i need to change it to await fetch_message(payload.message_id)

lyric apex
slate swan
lyric apex
stable leaf
slate swan
lyric apex
#

Ohk

stable leaf
#

?

crisp drift
#

Also you dont need to use partialemoji since it will use the convert method of EmojiConverter from your argument @lyric apex

slate swan
#

there's a seperate converter for PartialEmoji isn't it

stable leaf
#

await channel.fetch_message(payload.message_id)

crisp drift
#

Yes but whats the point of parsing a partialemoji

slate swan
#

indeed, its of no use unless you are trying to access emojis which the bot cannot see.

slate swan
stable leaf
#

sure

#
@client.event
async def on_raw_reaction_add(payload):
    emoji = payload.emoji
    guild = client.get_guild(payload.guild_id)
    channel = await channel.fetch_message(payload.message_id)
    message = await channel.get_message(payload.message_id)

    if emoji.name == "⭐️":
        async with client.db.cursor() as cursor:
            await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
            data = await cursor.fetchone()
            if data:
                starData = data[0]
                channelData = await guild.get_channel(data[1])
                for reaction in message.reactions:
                    if reaction.emoji == "⭐️":
                        if reaction.count >= starData:
                            embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
                            await channelData.send(embed=embed)
slate swan
#

Which lib

#

notice your channel variable defination, variables and methods don't come out of thin air. its bot/guild.get/fetch message

crisp drift
#

channel = await channel

slate swan
#

What

crisp drift
#

You don't define channel

stable leaf
#

isee

vale wing
#

lowerCamelCase is not for python

#

snakes_are_cooler

stable leaf
#
@client.event
async def on_raw_reaction_add(payload):
    try:
        emoji = payload.emoji
        guild = client.get_guild(payload.guild_id)
        channel = guild.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)

        if emoji.name == "⭐️":
            async with client.db.cursor() as cursor:
                await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
                data = await cursor.fetchone()
                if data:
                    starData = data[0]
                    channelData = await guild.get_channel(data[1])
                    for reaction in message.reactions:
                        if reaction.emoji == "⭐️":
                            if reaction.count >= starData:
                                embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
                                await channelData.send(embed=embed)
    except Exception as e:
        print(e)
vale wing
#

Nested if

#

Complex conditions exist

slate swan
#

add print statements after each action to see where it stops working

stable leaf
#

i think there is something wrong with this

vale wing
#

Just debug

stable leaf
vale wing
#

Yes

#

It's not a coro

slate swan
#

yes it is not an awaitable as mentioned 3 times above.

stable leaf
#

idk what that means

vale wing
#

Not awaitable expression

#

Coro is coroutine, you can read about some asynchronous programming concepts in asyncio docs

#

!d asyncio

unkempt canyonBOT
#

Hello World!

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

asyncio.run(main())
```...
stable leaf
vale wing
#

Create a breakpoint in that event and run a debug session

stable leaf
vale wing
#

Pycharm has very convenient debug imo

crisp drift
#

str(reaction.emoji) for your condition @stable leaf

stable leaf
#

ok

crisp drift
#

Well would be str(emoji)

stable leaf
#

where?

crisp drift
#
if str(emoji) == "⭐️":```
stable leaf
#

ok

#

this works

stable leaf
#
@client.event
async def on_raw_reaction_add(payload):
        emoji = payload.emoji
        print("emoji")
        guild = client.get_guild(payload.guild_id)
        print("guild")
        channel = guild.get_channel(payload.channel_id)
        print("channel")
        message = await channel.fetch_message(payload.message_id)
        print("message")

        if str(emoji) == "⭐️":
            print("1")
            async with client.db.cursor() as cursor:
                print("2")
                await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
                print("3")
                data = await cursor.fetchone()
                print("4")
                if data:
                    print("5")
                    starData = data[0]
                    print("6")
                    channelData = guild.get_channel(data[1])
                    print("7")
                    for reaction in message.reactions:
                        print("8")
                        if reaction.emoji == "⭐️":
                            print("9")
                            if reaction.count >= starData:
                                print("10")
                                embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
                                print("11")
                                await channelData.send(embed=embed)
                                print("12")
shrewd apex
#

str(reaction.emoji)

vale wing
#

It stops on 1 or what

stable leaf
vale wing
#

Or message

crisp drift
#

reaction.emoji == "⭐️":

#

Do the same than the first condition

vale wing
#

@stable leaf btw do you have an error handler

stable leaf
#

yes

#

traceback

#

only thing i have

#
if str(message.emoji) == "⭐️":
AttributeError: 'Message' object has no attribute 'emoji'
crisp drift
#

...

stable leaf
#

error

slate swan
#

Bruh

crisp drift
#

str(reaction.emoji)

#

thats it really

stable leaf
#

then i have syntax error

stable leaf
slate swan
#

!d discord.Message.reactions

unkempt canyonBOT
vale wing
#

Your emoji is emoji not the message.emoji (it doesn't exist)

stable leaf
#

so what then

vale wing
stable leaf
#

i am confused

crisp drift
slate swan
slate swan
#

youll understand more

vale wing
stable leaf
vale wing
#

See 16 warnings

#

Most of them are about naming convention pretty sure

stable leaf
#

but those are not for this one

vale wing
#

That's just code style, telling you how to do it right

crisp drift
#

sam, i mentioned you thrice for your check kekw

stable leaf
#

still the 1 syntax error

crisp drift
#

show your loop part

stable leaf
#

it printed it

vale wing
#

Does the if condition get passed

stable leaf
#

no

#

it stops right there

vale wing
#

Weird

#

Well try comparing it to the unicode character

stable leaf
#

ok

crisp drift
#

The problem comes from his loop part, first check passed he needs to use str() function again

stable leaf
#

i forgot how 😦

#

\⭐

vale wing
#

!e print("\u2b50")

unkempt canyonBOT
#

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

slate swan
#

How can I fix this?

AttributeError: 'Message' object has no attribute 'context'
vale wing
#

This

stable leaf
#

to 8

crisp drift
vale wing
stable leaf
#

and that is the same

#

so i just need to do there \u2b50

#

yes

#

thx to everyone for letting me waste your time

slate swan
#

thanks

stable leaf
lyric apex
#

Oh god

velvet compass
#

Got close to automute due to mentions lol

tawdry perch
#

What's the limit?

maiden fable
#

Rip

#

prolly 6

#

since there were 5 mentions

tawdry perch
#

let me try real quick /j

maiden fable
#

Haha

paper sluice
velvet compass
#

imagine pinging every moderator / helper / admin / owner

paper sluice
#

imagine not living on earth

short silo
#

Imagine being banned and unable to get help

simple kettle
#

Is it possible to give your bot a gif pfp

west shuttle
#

Hi.
i have this code:

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        await self.find_or_insert_user(message.author)
        ctx = await self.bot.get_context(message)
        if ctx.command is not None:
            return
        if message.author.bot is True or message.guild is None:
            return
        await self.db.execute(
            "UPDATE warns set for_add = for_add + 1 where user_id = ? and guild_id = ?",
            (message.author.id, message.guild.id),
        )
        await self.db.commit()

Its not adding up

scarlet aurora
#
    @commands.command()
    async def promote(self, ctx, user: discord.Member = None):

        if user is None:
            await ctx.send("Choose someone to promote")

        roles = [role.name for role in user.roles]

        Assault_Marine = discord.utils.get(user.guild.roles, name='Assault Marine')
        Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')

        if user is None:
            await ctx.send("Choose someone to promote")

        else:
            if 'Assault Marine' in roles:

                await user.remove_roles(Assault_Marine)
                await user.add_roles(Seeker_Marine)

                await ctx.send(f"Sucsesfully promoted ``{user}``")``` This still does not work, also there is no traceback, it just does not remove the rank and add the new rank, do you know why this is happening @slate swan
slate swan
shrewd apex
#
    @commands.command()
    async def promote(self, ctx, user: discord.Member = None):
        if user is None: return await ctx.reply("Choose someone to promote")
        roles = [role.name for role in user.roles]
        Assault_Marine = discord.utils.get(user.guild.roles, name='Assault Marine')
        Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')
        if 'Assault Marine' in roles:
             await user.remove_roles(Assault_Marine)
             await user.add_roles(Seeker_Marine)
        else: await user.add_roles(Assault_Marine)
        await ctx.send(f"Sucsesfully promoted ``{user}``")
maiden fable
#

The last time iirc Assault Marine role was None

shrewd apex
#

hmm?

maiden fable
#

The error

shrewd apex
#

oh

scarlet aurora
#

it's cuz I spelt assault wrong

slate swan
#

this seems like a single guild command, i wonder why don't they use IDs

scarlet aurora
#

it works now, no traceback

shrewd apex
#

for my bot i have custom roles for each level like mee6 they can set however they want

maiden fable
shrewd apex
maiden fable
#

Yea just made a PR

shrewd apex
#

i remember i once did pip freeze > requeirments.txt

maiden fable
#

Nice

shrewd apex
#

and a min later i was like where is my txt

maiden fable
#

Nice

#

Would love to see when someone runs the ot tag

heady sluice
#

!ot

unkempt canyonBOT
vale wing
maiden fable
#

Nice

vale wing
#

Tbh that happens pretty often

maiden fable
#

Understandable

slate swan
#

😳 thats why you use poetry and let it configure all the stuff itself.

maiden fable
#

Lol

maiden fable
#

that is the official discord docs

vale wing
#

People with several layouts can relate

shrewd apex
#

ur a contributor there?

maiden fable
#

No

shrewd apex
#

owner?

maiden fable
#

No

shrewd apex
#

...

maiden fable
vale wing
slate swan
#

ah, fair

scarlet aurora
#

where can I find the list of permissions for running bot commands?

shrewd apex
#

u guys know how to upload a file online to a cloud bin and get link for that file the file is an image

shrewd apex
vale wing
#

Should I write a wrapper for discord API in java (JDA sucks imo)

wanton steeple
maiden fable
#

Don't use 3rd party libs

shrewd apex
maiden fable
scarlet aurora
#

like to run a bot command

slate swan
wanton steeple
shrewd apex
#

its not screenshot its a pil image

paper sluice
shrewd apex
vale wing
maiden fable
#

Lmao I agree with u

shrewd apex
slate swan
shrewd apex
#

imgur has a python wrapper ?

maiden fable
#

U can use aiohttp

vale wing
#

Aiohttp exists but ok

slate swan
#

they do have an api so

maiden fable
#

!pypi imgur-python

unkempt canyonBOT
paper sluice
#

!pip imgur-python

unkempt canyonBOT
maiden fable
#

Nice

vale wing
#

Sus

shrewd apex
maiden fable
#

Tho its not updated anymore

shrewd apex
vale wing
#

Just use aiohttp it's cool

maiden fable
#

Nice the official imgur lib hasn't been updated since 2017

#

I agree with Evenifix

paper sluice
#

its sync as well

maiden fable
#

these libs ain't async

vale wing
#

Just thought about that

shrewd apex
#

aiohttp is alright but idk how to post files or upload them nor do i know any site for that ._.

slate swan
#

!pip asyncgur

unkempt canyonBOT
vale wing
#

DEPRECATED

maiden fable
#

Nvm sorry

maiden fable
vale wing
#

Let's make a new wrapper for that

maiden fable
#

WHY tf did u have to do that

vale wing
#

That lib is from 2020 tho

paper sluice
#
assert response.success == True and response.status == 200

sus

vale wing
#

Most likely got old enough

maiden fable
#

Indeed

maiden fable
shrewd apex
slate swan
#

pQuack i just store the image's bytes in a remote db

shrewd apex
#

i need it as link tho lemme tell u why coz discord bots dont allow file attachment editing

#

so rn i dump the image in a dump channel then take the attachment url and use it in embed

shrewd apex
#

but it causes a delay like arnd a second

maiden fable
#

__import__("sys").path.insert(1, ".") any comments?

slate swan
shrewd apex
#

wdym the image is diffrent everytime

maiden fable
#

@shrewd apex why not upload the image to a log channel or smth then save the url in the db and then use the url everytime u need to upload (show) the image

slate swan
slate swan
shrewd apex
#

yeah it a character walking on a map what do u expect position changes

maiden fable
#

Nice, u r making a game

slate swan
#

smh

maiden fable
shrewd apex
#

and every user has a character and their xy axes

maiden fable
shrewd apex
#

i dont think i am so good at graphics to do that

maiden fable
#

Just use pixel art ezzz

left idol
#

in pycord is this not a valid way to remove roles in a list?

for role in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    oldroles = discord.utils.get(ctx.guild.roles, name=role)
    await player.remove_roles(oldroles)
shrewd apex
maiden fable
#

Sure ig

left idol
#

i dont think my command is doing anything

maiden fable
#

Nice

#

Show the code @left idol

left idol
#

this is the only part that isn't doing anything

#

no errors or anything

#

since remove_roles takes in Roles i used get to get the role

slate swan
stiff gorge
#

how to make the uptime command show like this <t:1624385691:R>

slate swan
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
west shuttle
#

mmm

slate swan
#

!d discord.Guild.get_role saves you from utils.get

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
stiff gorge
slate swan
#

this is not a javascript server.

#

get(category) is returning undefined which does not have any such property you used, and discord.gg/djs is where this belongs to

left idol
#
rnames = []
for role in player.roles:
    rnames.append(role.name)
trole = discord.utils.get(ctx.guild.roles, name=team)
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    for role in [983770855161094224, 983770930834714685]:
        oldroles = ctx.guild.get_role(role)
        await player.remove_roles(oldroles)
    await player.add_roles(trole)
elif rnames not in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    await player.add_roles(trole)

i tried to take the for loop out from before and use id to print old roles which works, it prints out the roles one at a time however when implemented it doesn't do anythin?

maiden fable
#

Nice, JS errors

slate swan
left idol
#

hmmmm

quaint epoch
#

it haunted me for a solid 2 weeks

left idol
#

wait what do you mean

slate swan
slate swan
# left idol wait what do you mean

try

rnames = [role.name for role in player.roles]

[await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if ['Tokyo Fart Sniffers', 'Baltimore Bughas'] in rnames]

await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
#

I know that looks a bit messy but I was just too lazy to type

maiden fable
#

Why first remove then add...

left idol
slate swan
left idol
#

i want to remove roles in a list and then give them their new one

#

reteaming a player

slate swan
shrewd apex
shrewd apex
#

i tried in two way one was to read binary and then bytearray

maiden fable
#

with open(..., "rb") as file ?

shrewd apex
#

and other i just opened the image as pil

#

both same error

#
\dacite\core.py", line 75, in from_dict
    raise MissingValueError(field.name)
dacite.exceptions.MissingValueError: missing value for field "id"
maiden fable
#

Nice

#

That is why u use the raw api

slate swan
quaint epoch
maiden fable
#

?

unkempt canyonBOT
#

Image.tobytes(encoder_name='raw', *args)```
Return image as a bytes object.

Warning

This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use [`save()`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save "PIL.Image.Image.save"), with a BytesIO parameter for in-memory data.
quaint epoch
#

nice

maiden fable
#

FastAPI is hella weird 💀

slate swan
#

!ot

unkempt canyonBOT
maiden fable
#

Nice

#

Won't be surprised if ot is the most used tag but would be surprised if it ain't

slate swan
#
rnames = [role.name for role in player.roles]
#does the same thing as 
rnames = []
for role in player.roles:
  rnames.append(role)
await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))

this basically is a role adding while getting the Role object inside the add_roles
this is equivalent to

uwu_role = discord.utils.get(ctx.guild.roles, name=team)
await player.add_roles(uwu_role) #ofc how can my examples not be uwu

then comes the main part

[await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if ['Tokyo Fart Sniffers', 'Baltimore Bughas'] in rnames]

is if I break it down to simple words, is just a for loop
await player.remove_roles(ctx.guild.get_role(role)) gets the role as well as removes it from the player (though this is not a good practice, preferably make a getch. a getch is a logic which fetches stuff if the same query result was not found the in the cache for which get methods are responsible)

for role in [role_ids] is equivalent to a for loop as you can see
if [role_names] in rnames just checks if the role names are in rnames and in that case, removes the role from the player after getting the Role object

reading that list comprehension in simple words - if role_names are not in rnames, then, player.remove_roles -> role, while role is iterated through role_ids

#

did I spam or what

slate swan
maiden fable
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

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

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
slate swan
maiden fable
slate swan
#

so an Image.py, with an Image class looli seems like java stuff

shrewd apex
#

same error still

maiden fable
#

Use aiohttp @shrewd apex

#

the wrapper is prolly outdated

#

I can help u with aiohttp if u have any issues

slate swan
#

Hunter is so kind

shrewd apex
#

i see will try tom u mean using the api directly?

maiden fable
#

Your wish

shrewd apex
#

seems thats the best way

maiden fable
#

Tho aiohttp gonna make yr life easier imho

#
alpine cove
#

what r we talking about?

maiden fable
#

Imgur API

shrewd apex
#

yeah i normally try with ready made wrappers first if they fail well u gotta do it on ur ownpithink

alpine cove
#

yea never used it

alpine cove
#

yea

maiden fable
shrewd apex
#

i see

shrewd apex
slate swan
#

ok

maiden fable
# alpine cove wdym?

Discord API is more difficult if u wanna try using the Raw API from scratch since it involves reconnecting, ready and so on

maiden fable
slate swan
#

and what does it need by ready

#

why would you use aiohttp if youre only gonna use the REST api?

slate swan
slate swan
#

because you dont need it lol

#

creating a bot

slate swan
maiden fable
#

@shrewd apex try out this example and send us the result

drifting arrow
#

how do I run my bot through cmd line?

slate swan
#

dpy only uses aiohttp because of the gateway an in this case the only usage here is the REST api, no?

maiden fable
#

python main.py

shrewd apex
maiden fable
alpine cove
slate swan
slate swan
alpine cove
#

ehhh

slate swan
#

lamo

maiden fable
slate swan
slate swan
alpine cove
maiden fable
#

Nice, best of luck with that @slate swan

slate swan
#

smh

slate swan
maiden fable
#

I'mma just go

slate swan
#

ash is on the same page 🙏

#

what

#

how do you always drag me in

#

and why

alpine cove
slate swan
#

guess not

maiden fable
slate swan
shrewd apex
#

if i have an async function and a class with sync function and i initialise the class in the command and someone else runs the same command will the class content for the first guy to run the command get overwritten as well?

slate swan
#

i would still use aiohttp / httpx for making requests in an async environment, especially when its one of the dependencies of library im already using instead of using a blocking requests lib

slate swan
slate swan
#

they are making a bot so..

shrewd apex
slate swan
#

then youll be fine

slate swan
#

discord canary releases updates like crazy

slate swan
unkempt canyonBOT
#

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

001 | 1
002 | 2
slate swan
slate swan
maiden fable
#

1 GB RAM and still lagging 💀

slate swan
#

my discord goes boom

maiden fable
slate swan
maiden fable
#

same with ptb

maiden fable
slate swan
#

lol

maiden fable
#

DiscordCanarySetup.exe*

alpine cove
slate swan
#

yep the difference is, you can have canary and another instance at the same time, but not publictestbeta and another instance

maiden fable
#

Really?

slate swan
#

why not

maiden fable
#

Why not just use aiohttp

slate swan
# slate swan why not

I swear I've barely used asyncio, I always forget about the create_task method, don't call me out on that now, like seriously

#

ok

slate swan
maiden fable
maiden fable
#

U don't call the func inside the run in exec func

slate swan
#

sarth or hunter make an intents system for nakano im lazylemon_smirk

twilit ruin
#

thats too funny

maiden fable
slate swan
slate swan
twilit ruin
slate swan
twilit ruin
#

imagine whats going through that dude's head rn

unkempt canyonBOT
#

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

001 | <string>:6: DeprecationWarning: There is no current event loop
002 | uwu
maiden fable
slate swan
twilit ruin
#

is a friends screensht

alpine cove
slate swan
#

i dont wanna deal with bytewise operations

slate swan
maiden fable
#

@slate swan u ever used FastAPI?

slate swan
#

nope, not yet

maiden fable
maiden fable
slate swan
#

i never made something which would use that

slate swan
unkempt canyonBOT
#

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

001 | <string>:6: DeprecationWarning: There is no current event loop
002 | uwu
maiden fable
#

PyLance wanna have a meeting with u

slate swan
maiden fable
#

Still dk why they removed the get_event_loop method

slate swan
#

i think create_task works better in asher's case, since he doesnt actually need to wait for the function to return a value

maiden fable
#

Yea

slate swan
slate swan
slate swan
maiden fable
maiden fable
#

idk someone here had an issue with that before

slate swan
#

time to dig into the src and look for an internal private variable looli

slate swan
maiden fable
slate swan
#

bot.loop, or any other way round

maiden fable
#

@slate swan it will still block the whole event loop if u call the function lol

maiden fable
#

¯_(ツ)_/¯

#

BTW @shrewd apex what IDE do u use?

alpine cove
maiden fable
#

Add in a time.sleep bruh

shrewd apex
maiden fable
slate swan
maiden fable
slate swan
#

you just said bot.loop raises an error...

maiden fable
#

Ah

#

I said iirc

#

Idk someone had an issue with it before

slate swan
#

no comments

maiden fable
#

Cannot find the msg

shrewd apex
#

was it me i asked abt pil regarding this b4?

maiden fable
#

No, it was an error someone had a few days ago regarding bot.loop prolly it was smth else then

pliant gulch
#

to_thread also works

#

A little bit cleaner looking

shrewd apex
#

i see

paper sluice
pliant gulch
#

Maybe unsafe though, with how discord.py works internally

maiden fable
#
    try:
        book = await loop.run_in_executor(None, parse_ebook, request.name)
    except Exception as e:
        return Response(e, 500)

Nice this doesn't wanna work

#

Lmao the error is still raised even after the try except for some reason

paper sluice
#

what error?

maiden fable
#

AttributeError

alpine cove
#

what book?

maiden fable
pliant gulch
#

Does it error if you use get_running_loop

#

It should as long as it isn’t called before the bot is started

maiden fable
#

its not a bot

pliant gulch
#

Oh ok

paper sluice
maiden fable
#

I am raising the error myself to test out the try except

paper sluice
#

that try except will and should only work if book = await loop.run_in_executor(None, parse_ebook, request.name) fails

slate swan
maiden fable
#

Yea it raises an error in sync functions

slate swan
maiden fable
#

Ryuga clarified

slate swan
#

maybe because its closed

pliant gulch
#

Discord.py will raise error when loop isn’t started

slate swan
#

how could I code some kind of ping logger, so what do I need to use for that? like who pinged, channel and add the message link as a button

pliant gulch
maiden fable
#

Hm

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
maiden fable
#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
#

thanks

odd mango
#

hey, i modified the default minimal help command and get this now, how can i get rid of [command=None]

rare saddle
#

Please tell me what to do?

quaint epoch
unkempt canyonBOT
quaint epoch
#

are you sure those are valid emojis

tacit token
#
@client.event
async def on_message(message):
    if message.author.guild_permissions.manage_messages:

But the console write the use not has permission etc.. how can i make it ignore the error?

#

because this problem spam my console

quaint epoch
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
quaint epoch
#

hmm

tacit token
#

yes, i have this

#

wait a sec

#

but this spam my console

quaint epoch
#

!d discord.ClientUser

unkempt canyonBOT
#

class discord.ClientUser```
Represents your Discord user.

x == y Checks if two users are equal.

x != y Checks if two users are not equal.

hash(x) Return the user’s hash.

str(x) Returns the user’s name with discriminator.
quaint epoch
#

i have an idea

#

add py if message.author.id == bot.user.id: return at the top of your on_message func

rare saddle
quaint epoch
odd mango
tacit token
rare saddle
odd mango
#

theres no a!help in there, what its currently showing is default

#

i dont want [command=None] there

quaint epoch
quaint epoch
#

show the line where you get each commands name

#

then just do command_name.split(" ")[0]

odd mango
#
    def format_command_help(self, no, command):
        signature = self.helpcommand.get_command_signature(command)
        syntaxcommand = signature.split(" ")[0]
        syntaxinput = signature.split(" ")[1]
        docs = self.helpcommand.get_command_brief(command)
        return f"{no}. **{syntaxcommand}** `{syntaxinput}`\n{docs}"```
quaint epoch
#

it added a colon at the beginning

#

what a second

#

wait*

odd mango
#

thats not a problem

#

its fine only lol

quaint epoch
rare saddle
quaint epoch
odd mango
#

i dont get individual command names, it gets all commands at once

quaint epoch
# odd mango ```py def format_command_help(self, no, command): signature = self.h...

do py def format_command_help(self, no, command): signature = self.helpcommand.get_command_signature(command) syntaxcommand = signature.split(" ")[0] syntaxinput = signature.split(" ")[1] docs = self.helpcommand.get_command_brief(command) return f"{no}. **{syntaxcommand}** `{syntaxinput}`\n{docs}" if syntaxinput != "[command=None]" else return f"{no}. **{syntaxcommand}**\n{docs}"

odd mango
#

i do want <pokemon> though

rare saddle
odd mango
#

if i do that i wont see [command=None], but i wont see <pokemon> either

quaint epoch
#

edited

odd mango
#

OHH

odd mango
#

makes a lot of sense now, thanks a lot

quaint epoch
odd mango
#

what is that

quaint epoch
#

not the message object

rare saddle
odd mango
#

lmao

quaint epoch
# rare saddle

send the content you want to send, like "Hello world" or whatever

odd mango
#

send {hacker}

maiden apex
#

!paste

dull terrace
#

comparison of the first thing i wrote vs a rewrite, can you tell which is which just visually doge_kek

quaint epoch
#

i can totally tell the difference in the code

maiden apex
#

hey, can someone help me solving this error message ?

Ignoring exception in command ibf:
Traceback (most recent call last):
  File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\arsbu\Documents\CODE\PKbot\test.py", line 72, in ibf
    if abs(functions_product(i) - goal) < float(pr):
TypeError: unsupported operand type(s) for -: 'float' and 'str'

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

Traceback (most recent call last):
  File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for -: 'float' and 'str'
quaint epoch
maiden apex
dull terrace
rare saddle
#

This is if something does not work in embed

quaint epoch
#

after reviewing prs i learnt to NEVER trust when the person that requested the pr also says the rewrite is nicer

quaint epoch
#

or name=f'''{hacker}'''

#

just keep changing quotes till it works 👍

slate swan
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: unsupported operand type(s) for -: 'str' and 'float'
slate swan
#

Dear, tell me what is wrong. I don't think he sees the timeS variable, but why?

    @commands.has_role(982744620792426537)
    @commands.command(name = "мут", aliases = ["замутить", "muut"])
    async def command_ban(self, ctx, member: discord.Member, reason, time: int, *, time1):

        try:
            mute = discord.utils.get(ctx.message.guild.roles, name ="Мут")
            await ctx.channel.purge(limit = 1)
            await member.add_roles(mute)

            if time > 0:
                if time1 == ["m", "M", "м", "М"]:
                    timeS = time * 60
                    time2 = 60
                if time1 == ["h", "H", "ч", "Ч"]:
                    timeS = time * 3600
                    time2 = 3600
                if time1 == ["d", "D", "д", "Д"]:
                    timeS = time * 86400
                    time2 = 86400
            else:
                time = 'До разбирательств'
            
            memberName = member.name 
            memberTag = member.discriminator 
            author = ctx.author.name 
            tag = ctx.author.discriminator 

            embed = discord.Embed(
                title=(f"Был забанен {memberName}#{memberTag}"),
                color= 0xff0000
            )

            embed.set_footer(
                text="| Правительство SK",
                icon_url= ctx.guild.icon_url,
            )

            file1 = discord.File("./ImageS/mut.png") 

            embed.set_image(url='attachment://mut.png')

            date = datetime.datetime.today() 

            await ctx.send(file=file1, embed=embed)
            os.remove("./ImageS/mut.png")

            if timeS > 0:
                await asyncio.sleep(timeS)
                await member.remove_roles(mute)
        
        except discord.Forbidden:   return
#

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

odd mango
#

@quaint epoch i got it right, thanks a lot. but heres another problem 😂

slate swan
odd mango
#

my buttons work fine, just says interaction failed everytime i press them

quaint epoch
odd mango
#

i mean they scroll and everything

quaint epoch
#

i'd say defer the action/check your call backs

maiden apex
swift pumice
#
@bot.command()
async def avatar( ctx , member: discord.Member=None):
    if member is None:
        member = ctx.author
    await ctx.send(member.avatar.url)```
#

i want that my bot will show the avatar but it wont? what will i do

slate swan
swift pumice
#

like the discord avatar

slate swan
swift pumice
#

ok thx

slate swan
#

!d discord.Embed.set_image

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
odd mango
slate swan
swift pumice
#

everything

slate swan
#

bro

swift pumice
#

pls tell

odd mango
#

just fix the indents

slate swan
#

it wont always send anything lol

#

and you can use or

maiden apex
#

and i now get this error ```C:\Users\arsbu\Documents\CODE\PKbot\testpy\Scripts\python.exe C:/Users/arsbu/Documents/CODE/PKbot/test.py
Ignoring exception in command ibf:
Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\arsbu\Documents\CODE\PKbot\test.py", line 13, in ibf
goal = float(goal.content)
AttributeError: 'str' object has no attribute 'content'

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

Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'content'

odd mango
#

they just had messed up indents thats all

slate swan
slate swan
heady sluice
slate swan
#

🙂

odd mango
#

fair

#

i thought they would add an else statement for member arg

heady sluice
#

I already don't like not having
member = member or ctx.author

slate swan
#

?

heady sluice
#

I don't think the embed is necessary

#

but member = member or ctx.author is cool

odd mango
#

i am struggling with buttons, my buttons do the work but gives interaction failed error

slate swan
# slate swan timeS wouldnt be assigned only if the condition is true in your nested if tree

I wrote (.123 @slate swan reaction 1 m) but it still gives an error

    @commands.has_role(982744620792426537)
    @commands.command(name = "123")
    async def command_mutes(self, ctx, member: discord.Member, reason, time: int, *, time1):

        try:
            mute = discord.utils.get(ctx.message.guild.roles, name ="Мут")
            await ctx.channel.purge(limit = 1)
            await member.add_roles(mute)
            
            if time > 0:
                if time1 == ["m", "M", "м", "М"]:
                    timeS = time * 60
                    time2 = 60
                if time1 == ["h", "H", "ч", "Ч"]:
                    timeS = time * 3600
                    time2 = 3600
                if time1 == ["d", "D", "д", "Д"]:
                    timeS = time * 86400
                    time2 = 86400
            else:
                time = 'До разбирательств'

            if time > 0:
                await asyncio.sleep(timeS)
                await member.remove_roles(mute)

        except discord.Forbidden:   return
odd mango
#

how do i fix i t

slate swan
#

how can i connect the bot to a website to make a dashboard?

faint zinc
slate swan
#

yep

odd mango
#

so my question is simply how can i get rid of this annoying "Interaction failed" thingy? Everything works well, and the buttons also do work. Once the button finished loading, and the action got performed, it simply says "Interaction failed" for no reason

torn sail
#

await interaction.response.defer()

odd mango
torn sail
#

There won’t be any message

odd mango
#

oh?

torn sail
#

For deferring button interactions

odd mango
torn sail
#

How are u making the buttons?

odd mango
#

sec

#
    @ui.button(emoji='⏮️', style=discord.ButtonStyle.gray)
    async def first_page(self, button, interaction):
        await self.show_page(0)

    @ui.button(emoji='◀️', style=discord.ButtonStyle.gray)
    async def before_page(self, button, interaction):
        await self.show_checked_page(self.current_page - 1)

    @ui.button(emoji='🗑️', style=discord.ButtonStyle.gray)
    async def stop_page(self, button, interaction):
        self.stop()
        if self.delete_message_after:
            await self.message.delete(delay=0)

    @ui.button(emoji='▶️', style=discord.ButtonStyle.gray)
    async def next_page(self, button, interaction):
        await self.show_checked_page(self.current_page + 1)

    @ui.button(emoji='⏭️', style=discord.ButtonStyle.gray)
    async def last_page(self, button, interaction):
        await self.show_page(self._source.get_max_pages() - 1)```
torn sail
odd mango
#

uh

#

no understand

karmic marsh
#

is there a specific discord server for coding discord bots?

#

like not just a subset of the python server?

full lily
#

there is

#

well

#

There's a discord.py one, and each of the other libraries also have one

#

@karmic marsh

torn sail
karmic marsh
#

yeah

#

I'd love a link

torn sail
#

They are async tho

full lily
#

oh it's in the channel desc also

odd mango
#

do one and show me how?

#

NOT HOE

torn sail
#

Uh I’m on phone so idk how to new line for a code block

odd mango
#
@ui.button(emoji='⏮️', style=discord.ButtonStyle.gray, await interaction.response.defer())```
#

are you telling me to do this

#

cause this aint making any sense to me

torn sail
odd mango
#

ohhhh

#
    @ui.button(emoji='⏮️', style=discord.ButtonStyle.gray)
    async def first_page(self, button, interaction):
        await self.show_page(0)
        await interaction.response.defer()```
#

like this?

torn sail
#

Yes but if show_page Is a slow function then you should defer before it

odd mango
#

got it

#

yeah it is a slow one

#

thanks a lot i will go try it and lyk

torn sail
#

👍

odd mango
# torn sail 👍

now it aint even turning the page, and the interaction error remains untouched 😂

torn sail
#

Huh

odd mango
#

2.0

torn sail
#

When did u last install

#

Because there was a big change

odd mango
#

yesterday

torn sail
#

Then swap button and interaction in the function parameters

odd mango
#

oh o.o

odd mango
#

its working awesome now

torn sail
#

👍

odd mango
#

how did you know the changes though

#

do you camp git repo 😂

torn sail
#

I also check the weekly updates in the discord.py server

odd mango
#

oh wait, i do this

    async def interaction_check(self, interaction):
        """Only allow the author that invoke the command to be able to use the interaction"""
        return interaction.user == self.ctx.author```
for obvious reasons
#

so if someone other than author reacts

#

will they see interaction failed or not

#

o.0

torn sail
#

They would see interaction failed

#

I usually just send an ephemeral message and return false

odd mango
#

how do i make an invisivble

#

yeah that stuff

torn sail
#

interaction.response.send_message(…, ephemeral=True)

odd mango
#

got it

#

ty

left idol
#

@slate swan thank you for the explanation but it still doesn't look like its working:

rnames = [role.name for role in player.roles]
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    [await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if ['Tokyo Fart Sniffers', 'Baltimore Bughas'] in rnames]
    await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
elif rnames not in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
torn sail
left idol
#

I’m trying to check if the user has any of those roles and if they do remove them

torn sail
#

but you should assign ['Tokyo Fart Sniffers', 'Baltimore Bughas'] to a varaible before to not create a list a lot more times than needed

karmic marsh
#

bruh

#

I'm already struggling with this and I've barely done anything

#

why does ```py
TOKEN = os.getenv('DISCORD_TOKEN')
client.run(TOKEN)

not work when ```py
client.run(ndjislIFNUISndjskd.etc.etc)

works just fine?

#

I have a file called .env that contains this:

# .env
DISCORD_TOKEN={"ndjislIFNUISndjskd.etc.etc"}
#

it doesn't give me any errors, it just doesn't do anything

narrow grail
karmic marsh
#

uhh...

#

okay then. It works now lmao

left idol
torn sail
#

also instead of ctx.guild.get_role(role) you can just use discord.Object(id=role) because remove_roles jsut needs the id

left idol
#

ye got it to work, thank you!

#

but on another topic, when i use interaction.defer() and then a long task followed by at the end interaction.message.edit, why does it say the application did not respond?

#

i have to interaction.followup.send()?

rocky trench
#

U need to await interaction.defer() if I'm right

torn sail
#

at least in slash commands

slate swan
#

I wanted to ask does anyone know how I can import the name of a text data into my responses

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.

slate swan
#

but the inport from a text data

#

not as a hole big code

slate swan
#

I was able to fix the problem myself

karmic marsh
#

is there a disnake discord server?

#

I'm running into this issue:

SyncWarning: Failed to overwrite commands in <Guild id=983259662411501578> due to 403 Forbidden (error code: 50001): Missing Access
  warnings.warn(
steep drift
#

So, I had a question that was trying to be solved in #help-cheese, so can someone try and finish helping me. Thank you if so.

torn sail
karmic marsh
#

yeah... looks like I was supposed to put that in the url

final pumice
#

is split() still a method of message

fading marlin
#

in message.content, yes

karmic marsh
#

y'all use disnake?

#

I can't figure out how to get the current guild of the bot

#

or rather, iterate through the list of connected guilds and ID one by name

final pumice
karmic marsh
#

this should work but it doesn't:

#
guild = disnake.utils.get(disnake.Client.guilds, name=GUILDNAME)
steep drift
slate swan
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:
flint isle
#

Ignoring exception in command search:
[{'text': "This is just a regular little gummy bear,\xa0\nand I've decided to destroy it. To do this\xa0\xa0", 'start': 0.24, 'duration': 5.68}, {'text': "I just have to get a vial, and I'll add a small\xa0\namount of something called potassium chlorate.\xa0\xa0", 'start': 5.92, 'duration': 5.68}, {'text': 'After that I just have to heat it up,\xa0\nuntil it all melts into a nice goop.', 'start': 12.32, 'duration': 4.24}, {'text': 'At this point it should be pretty good, and I\xa0\ncan carefully drop in the poor little gummy bear.', 'start': 19.52, 'duration': 5.36}, {'text': 'Almost immediately the potassium chlorate started\xa0\nripping it apart, and oxidizing it into water,\xa0\xa0', 'start': 28.64, 'duration': 6.32}, {'text': "and CO2 gas. Within just several seconds\xa0\nthough the reaction's already done,\xa0\xa0", 'start': 34.96, 'duration': 5.12}, {'text': 'and my little gummy bear, no longer exists.', 'start': 40.88, 'duration': 2.96}]
Traceback (most recent call last):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\youtube.py", line 21, in lnk
    check = json.load(transcript)
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'

my code:


    @commands.command(name="search")
    async def lnk(self, ctx, youtube_vid, term):
        video_id = youtube_vid
        transcript = YouTubeTranscriptApi.get_transcript(video_id)
        print(transcript)
        keyval = term
        check = json.load(transcript)
        if keyval in check:
            print('Found term in:')
            print(f'check')
fading marlin
#

why're you using json.load?

flint isle
# fading marlin why're you using json.load?

im using a guide to search json arrays and thats what is shows
EX

Example-1: Search key in simple JSON data
The following script shows how to search if a particular key exists in a JSON string or not. Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, ‘in’ operator is used to search the key.

#!/usr/bin/env python3

# Import json module
import json

# Define json data
customerData ="""{
    "id": "3425678",
    "name": "John Micheal",
    "email": "john@gmail.com",
    "type": "regular",
    "address": "4258 Poplar Chase Lane, Boise, Idaho."
}"""

# Input the key value that you want to search
keyVal = input("Enter a key value: \n")

# load the json data
customer = json.loads(customerData)
# Search the key value using 'in' operator
if keyVal in customer:
    # Print the success message and the value of the key
    print("%s is found in JSON data" %keyVal)
    print("The value of", keyVal,"is", customer[keyVal])
else:
    # Print the message if the value does not exist
    print("%s is not found in JSON data" %keyVal)
fading marlin
#

get_transcript doesn't return a JSON object?

#

it returns a list of dictionaries

flint isle
#

it does return json

#

so its unneeded?

fading marlin
#

yes, it's unneeded, check the docs/source code of get_transcript

flint isle
#

ok so removing that dropped the error but im trying add functionality to search the json
i have an example of the json output


[{'text': "This is just a regular little gummy bear,\xa0\nand I've decided to destroy it. To do this\xa0\xa0", 'start': 0.24, 'duration': 5.68}, {'text': "I just have to get a vial, and I'll add a small\xa0\namount of something called potassium chlorate.\xa0\xa0", 'start': 5.92, 'duration': 5.68}, {'text': 'After that I just have to heat it up,\xa0\nuntil it all melts into a nice goop.', 'start': 12.32, 'duration': 4.24}, {'text': 'At this point it should be pretty good, and I\xa0\ncan carefully drop in the poor little gummy bear.', 'start': 19.52, 'duration': 5.36}, {'text': 'Almost immediately the potassium chlorate started\xa0\nripping it apart, and oxidizing it into water,\xa0\xa0', 'start': 28.64, 'duration': 6.32}, {'text': "and CO2 gas. Within just several seconds\xa0\nthough the reaction's already done,\xa0\xa0", 'start': 34.96, 'duration': 5.12}, {'text': 'and my little gummy bear, no longer exists.', 'start': 40.88, 'duration': 2.96}]