#discord-bots

1 messages · Page 1117 of 1

eager bluff
#

this gives me an error

slate swan
#

why (?

eager bluff
#

for like the actual embed

slate swan
#

why do you have ( after the embed object?

#

thats not how it works.

#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
eager bluff
#

ohh

slate swan
#

btw i love your pfp

eager bluff
slate swan
#

Hello, I am trying to figure out how to sync my python discord bot commands to the built in command tree on discord that displays your command options when you type in the prefix. Can someone please help me?

eager bluff
slate swan
eager bluff
slate swan
#

set it to False to make them appear in different lines

#

CAPYBARAS are the best animal

#

cats supermacy.

eager bluff
#

like even if i alternated false and true

slate swan
eager bluff
slate swan
#

dpy doesnt create default slash help does it?

slate swan
slate swan
slate swan
slate swan
slate swan
#

oki you ever worked with image manipulation?

#

never

#

best place 😔

slate swan
#

ayo?lemon_glass

eager bluff
#

if i do this

#

usage and update still go on different lines

#

grrr why

slate swan
#

if you want all the fields to be on the same line

eager bluff
slate swan
eager bluff
#

its supposed to go below whois

slate swan
#

then make it true

#

ah

eager bluff
slate swan
#

wdym?

#

😅

eager bluff
#

look what happens

slate swan
#

yeah and how would you like it?

eager bluff
slate swan
eager bluff
#

and then i got this

slate swan
eager bluff
#

even tho

slate swan
#

are you trying to do something like that?

eager bluff
slate swan
eager bluff
#

exactly like this

X y
W v

eager bluff
slate swan
#

ah

eager bluff
slate swan
#

well i dont think so because it would just go the the first row if its inline

eager bluff
#

like a filler one?

slate swan
#

yep

paper sluice
eager bluff
slate swan
#

iirc you need to use \u200b

#

the zero with space idk

paper sluice
#

try these configs for iniline, False, True, False, True @eager bluff

paper sluice
#

what did u get?

eager bluff
#

its because there is something above it

#

which is not inline

paper sluice
#

oh

eager bluff
#

so it has to eb

#

false, true true

#

false true true false

slate swan
#

just inline a third field

#

and set all inline to true

eager bluff
#

yeaht thats what im doing rn

left idol
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
why do i get this error when other commands that need the same permissions works?

burnt lodge
#

just give admin

slate swan
burnt lodge
#

the bot^^

#

my bad i didnt make it clear

slate swan
#

no bot should have admin perms its pretty dangerous

#

Does anyone know how to sync bot commands to the built in commands in discord? 😅

left idol
#

not my server, cant give admin

eager bluff
#

i mean if its your bot

slate swan
#
    @commands.command(aliases = ["123", "321"])
    async def command_Forge_image(self, ctx, member: discord.Member = None):
        if ctx.author.id == 567107484850847744:

                    img = requests.get(i_background, stream = True) 
                    img = Image.open(io.BytesIO(img.content))
                    img = img.convert('RGBA') 
                    img1 = requests.get(i_frame, stream = True) 
                    img1 = Image.open(io.BytesIO(img1.content))
                    img1= img1.convert('RGBA')

                    img1M = requests.get(i_frameM, stream = True) 
                    img1M = Image.open(io.BytesIO(img1M.content))
                    img1M= img.convert('L')  

                    img.paste(img1M, (0,0)) 
                    img.save('./ImageS/kik.png') # сохранил картинку

                    embed = discord.Embed(
                        title = "123",
                        color= 0xff0000
                    )
                    file1 = discord.File("./ImageS/kik.png")

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

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

dear please tell me what is the problem

paper sluice
left idol
#

heres the roles it has for that channel and the bot role permissions

#

it was able to send embed for another command but i guess its not able to now?

#

it works in a different channel tho

slate swan
#

If you type slash “/“ right now inside of the chat, it will display options of the commands available. I would like that for my bot @paper sluice

slate swan
left idol
#

no i had it ticked

slate swan
#

I’m assuming you mean import discord from discord.ext import commands? @paper sluice

#

create em eperately

slate swan
#

Yes I am @slate swan

#

hm

#

then why subclass?

paper sluice
unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This must be called for the application commands to show up.
slate swan
#

button1 = discord.ui.Button(label=..., ...)
button2 = discord.ui.Button(label=..., ...)
like that?

#

I’ve seen that but I can’t import app_commands. I manually put the folders in aside from regular installation and it still doesn’t take.

#

how to send dm to a specific uset

#

with a if

#

id

#

!d discord.User.send

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

Sends a message to the destination with the content given.

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

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

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

ni

#

i'm afraid that I might be clueless about that

#

!d discord.ext.commands.Bot.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
paper sluice
slate swan
#

poor ryuga 😔

slate swan
slate swan
unkempt canyonBOT
paper sluice
#

maybe

slate swan
#

just read the gist 😔

#

😔 no self advertisement

paper sluice
slate swan
slate swan
#
    @commands.command(aliases = ["123", "321"])
    async def command_Forge_image(self, ctx, member: discord.Member = None):
        if ctx.author.id == 567107484850847744:

                    img = requests.get(i_background, stream = True) 
                    img = Image.open(io.BytesIO(img.content))
                    img = img.convert('RGBA') 
                    img1 = requests.get(i_frame, stream = True) 
                    img1 = Image.open(io.BytesIO(img1.content))
                    img1= img1.convert('RGBA')

                    img1M = requests.get(i_frameM, stream = True) 
                    img1M = Image.open(io.BytesIO(img1M.content))
                    img1M= img.convert('L')  

                    img.paste(img1M, (0,0)) 
                    img.save('./ImageS/kik.png') # сохранил картинку

                    embed = discord.Embed(
                        title = "123",
                        color= 0xff0000
                    )
                    file1 = discord.File("./ImageS/kik.png")

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

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

dear please tell me what is the problem

slate swan
#

:))

slate swan
paper sluice
#

i mean they can clean up some outdated stuff, there is a pinned guide from 2018

slate swan
#

🙏

slate swan
paper sluice
slate swan
velvet compass
slate swan
#

oki

slate swan
#

please im struggi=ling]

slate swan
#

plead=se

paper sluice
slate swan
#

yup

#

help

#

please

slate swan
stiff fern
#

If the only way to send modals through interaction how would I send a modal from adding a reacting to a message

slate swan
#

then just hardcode the id

#

i want to send message to mhse

#

how

#

copy your id

#

and???

paper sluice
slate swan
#

i tried it

slate swan
unkempt canyonBOT
paper sluice
slate swan
#

it sAID "int has no atribute to send"

#

its an optional return type tho

slate swan
slate swan
#

howoww

#

so fetch it or get it from cache

paper sluice
slate swan
#

oooay

slate swan
#

🗿

#

okimii said the truth for the first time

#

I'm poor 😭

#

🗿

paper sluice
#

huh lemon_pika

feral timber
#

😔

paper sluice
slate swan
#

i dont even have a dollar in my wallet, in debt😔

paper sluice
#

i dont have a wallet 😳

slate swan
#

bro🤨

slate swan
slate swan
#

and allot of it

#

you fill it with sand or what 😔

paper sluice
#

sell the dust

slate swan
#

i wish

paper sluice
#

👀

#

huh?

slate swan
#

😳

paper sluice
#

ur acting like sparky

slate swan
#

im not sparky

paper sluice
#

wait, what if ur sparky

#

damn

slate swan
#

sparky doesnt have my unique code base😩

#

and hes an amonger

stiff fern
#
        # If reacted with 'No'
        elif str(reaction.emoji) == '![No](https://cdn.discordapp.com/emojis/986643106835353691.webp?size=128 "No")':

            class rejection_modal(ui.Modal, title="Suggestion Rejected"):
                reason = ui.TextInput(
                    label=f'Suggestion:\n{self.answer_one}',
                    style=discord.TextStyle.long,
                    placeholder='Input the reason for rejection',
                    required=True,
                    max_length=500)

                answer_one = self.answer_one

                async def on_submit(self, interaction: discord.Interaction):
                    suggestion_embed = discord.Embed(
                        title='Suggestion Rejected',
                        description=f'**{self.answer_one.label}**\n{self.answer_one}\n\n**Reason**\n{self.reason}',
                        timestamp=datetime.now(),
                        color=0xef484a)  # Red

                    # Updating suggestion in staff channel
                    suggestion_embed.set_author(name=interaction.user, icon_url=interaction.user.avatar)
                    suggestion_embed.set_footer(text=f'Rejected by {user}')
                    await suggestion_message.edit(embed=suggestion_embed)

                    # Alerting user of rejected suggestion
                    await interaction.user.send(embed=suggestion_embed)


            await interaction.response.send_modal(rejection_modal()) # ERROR HERE

Can someone explain his error to me?

#

oh thats a lot

paper sluice
#

rip chat

slate swan
#

cute check

paper sluice
#

now i have to use mouse

slate swan
#

and the class being inside an if statement pfffttt

#

im sti;ll confused

#

how do i do it

slate swan
#

pl4aw

stiff fern
#

I made it smaller 😬

paper sluice
slate swan
slate swan
#

ctrl plus minus

paper sluice
slate swan
#

please help me

slate swan
eager bluff
#

oop

#

accidentally replied

slate swan
#
myid = 243434553465453

@bot.command
async def send():
  myid.send("message")
#

uel;-'

#

help

slate swan
#

i want it to send it to myself onlyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

#

oeijrhbsu

#

thats not how oop works

#

you would need to get the object by placing your id in the method. hence making a user object and then making able to send a message.

paper sluice
#

this is why learning OOP is recommended b4 jumping into discord bots

eager bluff
#

why does coolo not become the next index number? it says index list out of range

paper sluice
#

ok [1][1] is a little confusing, how about a = [1] then a[1]

eager bluff
paper sluice
slate swan
#

Ident issue, can someone help me fix it

#

!indents

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
#

Yes I’m on my phone lmao

#

spell and grammar mistake 😔

paper sluice
#

ive noticed, a lot of ppl code on their phones

slate swan
slate swan
paper sluice
slate swan
slate swan
slate swan
slate swan
slate swan
#

agriculture is the best class no cap

#

what

slate swan
paper sluice
slate swan
#

agriculture is so fun

#

Planting shi, is fun LMAO

#

one time i was riding a pig through the school

#

🙏

#

I’m in Canada stuff is so different

slate swan
#

its relevant

#

i made a discord bot out of that idea😳

paper sluice
slate swan
#

machine learning

#

Can someone just rq help me with my ident issue lmao

paper sluice
slate swan
#

💀

slate swan
tepid matrix
#

if anyone wants a professional website made for thier bot, hmu,ill make it for free, im full stack web dev looking for projects

slate swan
#

Just saying

tepid matrix
slate swan
slate swan
paper sluice
slate swan
#

😔

slate swan
tepid matrix
slate swan
tepid matrix
slate swan
#

Fix for idents

slate swan
tepid matrix
#

ppl so uptight

slate swan
#

^

paper sluice
#

Sten trying to keep this channel together, where us rebels are tearing it apart

#

anyways, lets help him out

slate swan
#

sten is hunter

#

😳

#

no hunter is smart

paper sluice
slate swan
slate swan
#

😳

slate swan
slate swan
unkempt canyonBOT
slate swan
#

😤

#

Can someone help me man please lmao

#

hun bun....I'm sure Hunter wont like you saying that name here in the server

#

he wont mind

#

mhm

#

.topic

lament depotBOT
#
**What feature would you like to see added to the library? What feature in the library do you think is redundant?**

Suggest more topics here!

paper sluice
slate swan
slate swan
#

await self._ws.close() is what youre looking for

#

😳

paper sluice
# slate swan bro

when u call library.self_desctruct it should runos.system('pip uninstall library')

paper sluice
#

life would be soo much simpler

#

you wont have to worry about that stupid bot you were making anymore

#

this should be a mandatory feature imo

slate swan
#
import pip
@bot.command()
async def self_destruct(ctx):
  for guild in ctx.bot.guilds:
    await guild.me.ban()
  pip.main(["uninstall", "discord.py"])

uwu

paper sluice
slate swan
#

why use an instance with context if you already initiated the class?(bot class)

slate swan
#

lolllll

slate swan
#

how old does a discord account need to be to remove the wumpus message? trying to write a simple func to autoban potential alts

paper sluice
slate swan
#

well...it isnt

slate swan
#

some guy is skidding my friend's business and profiting off of it

#

and made a bunch of alts to join the server to mass dm

#

cool, this isnt the correct channel

#

just thought since it was under "discord" i could get some help here xd

dire folio
#

Lol

slate swan
rapid falcon
#

hello

#

how do you guys hide the bot token from the main.py file?

rapid falcon
#

should i create a separate file for it and then get it from it?

paper sluice
slate swan
#

^

rapid falcon
#

should i only name it .env?

sullen girder
#

how do i get my bot to enter a voice channel and if he disconnects he enters again when someone speaks in chat (any people)

slate swan
#

an env file is good, a python file works too

#

and yeah .env

sullen girder
#

I tried use on_message

sullen girder
#

No in Voice call

#

In chat

slate swan
#

you mean text?

sullen girder
#

Yee

slate swan
rapid falcon
#

thanks @slate swan and @paper sluice 🙂

sullen girder
tough lance
#

Huh?

slate swan
tough lance
#

Check it message.channel is same as channel object

sullen girder
slate swan
sullen girder
#

All channels

slate swan
#

then....why would it want to join a specific channel always

sullen girder
#

Músic bot

#

It stays on voice channel

#

I tried use If but i dont know what do i put

paper sluice
#

ducky_australia havent used this emoji for some time

sullen girder
#

Eh ashley disappeared

rapid falcon
#

how can the bot delete its message?

#

a specific message

#

like a warning or smth

#

anyone? 🙂

slate swan
rapid falcon
#

wdym by fetch?

slate swan
#

!d discord.TextChannel.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.
slate swan
#

I'd use an http method myself at this point, since fetch_message makes an api call

#

bot.http.delete_message(channel_id, message_id)
lmao

#
channel = bot.get_channel(...) or await bot.fetch_channel(...)
message = await channel.fetch_message(...)
await message.delete()

while http methods be -> await bot.http.delete_message(channel_id, message_id)

oooof

stiff fern
#

I just did import discord so

#

what would be wrong with that

slate swan
#

import it from ext.commands

#

eh

stiff fern
#
from discord.ext import commands, discord

So this?

slate swan
#

wait

slate swan
#

discord.InvalidArgument should work weird

rapid falcon
#

do you know how to press enter as \n or \t etc.?

slate swan
#

press enter...?

rapid falcon
#

yes

slate swan
#

oh \n

rapid falcon
#

no not a new line

slate swan
#

\t is for a tabbed space

rapid falcon
#

yeah ik

slate swan
sullen girder
rapid falcon
#

is there one for enter?

slate swan
#

no?

rapid falcon
#

alr then

#

i need to get a channel name

#

like when the bot sends a message with the name of the channel like this: #python-discussion

#

oof

slate swan
#

!d discord.TextChannel.mention

unkempt canyonBOT
rapid falcon
#

it works then

tough lance
#

Send the channel object as is

#

The _str_ function automatically changes it

rapid falcon
#

wdym?

#

anyways

#

how to extract a ping from a message, for example:
if i ping @slate swan, i want the bot to get the ashley user ping

#

is there a way to do this?

tough lance
#

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

tough lance
#

There finally

rare saddle
#

How to get entered information via custom_id ?

rapid falcon
#

any tips?

sterile talon
#

hey, someone knows how can i sort it?

lethal moat
#
async def StartGame(interaction: Interaction, winners:int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):

this says that int object is not iterable (an error)

according to documentation it is ok
how can I fix it?

#

its the winners:int = part I think

lethal moat
cerulean folio
#

guys where should i store my token if it isn't in a variable if ima need to upload bot on repl.it?

slate swan
#

Your reaction button class cant fetch a "max_reactions" variable, cause its not given

cerulean folio
slate swan
#

If you want it easy

sullen girder
cerulean folio
#

azure is free?

slate swan
#

You could put it in the custom id

#

The button custom id

#

which library do you use

cerulean folio
#

alrightie thank you

cerulean folio
#

you have to link a credit card

cerulean folio
#

oh ok

#

for Repl.it users: where do you store your Token?
EDIT: solved thank you :)

sick birch
#
view = add_reactions(reactions=..., max_reactions=...)
#

You can pass it down again from your view to your button

#
class AddReactionsView(discord.ui.View):
  def __init__(self, max_reactions: int):
    super().__init__(...) # regular view initialisation
    self.add_button(ReactionButton(max_reactions)) # notice how we're passing it down to the button?
    ...

class ReactionButton(discord.ui.Button):
  def __init__(self, max_reactions: int):
    self.max_reactions = max_reactions
    super().__init__(...) # regular button initialisation
    ...

  async def callback(self, interaction: discord.Interaction):
    print(self.max_reactions) # you have access to max_reactions here
    ...
peak loom
#

How can I make reaction roles?

sullen girder
#

how do i get my bot to enter a voice channel and if he disconnects he enters again when someone speaks in text channel (any people)

#

I tried but dont work

peak loom
# sullen girder

Try, ```py
@client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
@client.command()
async def leave(ctx):
await ctx.voice_client.disconnect()

cerulean folio
sage otter
sullen girder
#

Like

async def on_message(message):
    channel = ctx.author.voice.channel
    await channel.connect()```?
sick birch
#

You might wanna put in a check because not everyone that sends a message is going to be in a voice channel

median widget
#

can someone give me tips on how i would make a bot repeat exactly what i say in a diferent channel

#

so i can talk as the bot kinda

#

and it would go to another channel

slate swan
#

just make an on message and fetch the channel once and then for each message it gets redirected to the channel you just fetched

rare saddle
#

How to get the first message in a channel?

slate swan
#

!d discord.TextChannel.history

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/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
sick birch
#

or cyan or whatever

slate swan
#

Robin keep defending the best letter in the alphabet aka R🙏

sick birch
#

you got it boss

slate swan
#

🙏

spice adder
#

getting an error for inconsistent use of tabs and spaces in indentation in all the red areas, not sure what I need to change because it looks right to me

        @client.command()
        @commands.has_role('Staff')
        async def reason(ctx, msgID: int, *, arg):
            msg = await client.get_channel(876688282552008734).fetch_message(msgID)
            embeds = msg.embeds
            if embeds:
                textcontent = msg.content
                newembed = embeds[0].copy()
                newembed.description =str("📄 **Reason:**\n" + arg)
                await msg.edit(content = textcontent, embed = newembed)
            else:
                 await ctx.send("Message has no embed.")
                 await ctx.message.delete()
                
        @reason.error # <- name of the command + .error
        async def reason_error(ctx, error):
            if isinstance(error, commands.MissingRole):
                await ctx.send("You do not have the required permissions to use this command: `Staff`")
devout iris
#

hia

#

how can i delete messages from specific user?

#

for example

!delete @devout iris 20

sick birch
#

Would that delete the last 20 messages by that user?

devout iris
pliant gulch
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
pliant gulch
#

It has a check parameter, use that to filter out the specific user

#

It could be a lambda that takes one arg, eg user then check if that user is the same one as the one given when invoking the command

devout iris
#

hmm

#

check=user, right?

sick birch
#

check has to be a function

devout iris
#

i'm confused, lol

#

could you give me a basic example?

dull terrace
#

my bot with 1051 servers is ranked #1823 7739monkathink how many bots have more than 30k servers then

#

oh, 532 bots have 10k+ servers

peak loom
sage otter
peak loom
dusky pine
#

most of the time they copy it without thinking

#

what do you expect will happen when you send a snippet of code without explaining anything

maiden fable
#

@sick birch congrats on project leads role!

dusky pine
#

wasn't he already project lead

smoky cedar
#

I'm having a weird issue that I think is discord library related

#

I have a bot, follows artists on spotify, and pings new releases

#

Task loops to check for new releases every 10 minutes. Before I would occasionally receive a JsonDecodeError, which upon being raised, caused my loop to start working indefinitely

#

So I went ahead and used tasks.loop(minutes=10, reconnect=True), I added the reconnect parameter since from what I understand, should restart the loop despite exceptions

#

However, now I'm seeing a new issue that occurred hours into the bot being online. I got
TypeError: sleep() got an unexpected keyword argument 'loop'

Once this happens, program is awol on making more spotify requests. But responds to other slash commands that don't require spotify calls

sick birch
sick birch
sick birch
#

Also makes sense that happened after you set reconnect=True as that's what that kwarg does

smoky cedar
#

But I thought using that reconnect parameter would make the task resume from scratch

sick birch
#

Proper error handling would fix that most likely

smoky cedar
hushed galleon
#

do you have the full traceback of that error?

sick birch
smoky cedar
hushed galleon
#

asyncio.sleep's loop kwarg was removed in python 3.10 so your version of spotify might be incompatible with 3.10

#

that is assuming sleep() refers to asyncio.sleep()

smoky cedar
#

Sorry, gonna send img since I can't seem to copy over my ssh terminal

smoky cedar
maiden fable
#

Ah the Spotify lib

#

It's causing the error

smoky cedar
#

Hmm. Potential solutions that don't involve forking and pushing my own updates Thonk

#

Well, I can avoid calling retry in the first place somehow...?

#

But is it the reconnect that's causing that to happen or is that totally unrelated?

hushed galleon
#

reconnect= affects how dpy will handle your function when a connection error occurs, i.e. exponential backoff

smoky cedar
#

Kk, so unrelated

#

Just weird that I never saw this issue prior to implementing it

#

I suppose I may just have to catch the exception and return None

hushed galleon
#

looking at spotify's source you happened to have been ratelimited in your case

maiden fable
slate swan
#

,yes I did

maiden fable
#

!d discord.Role.mention

unkempt canyonBOT
maiden fable
#

I mean, u get the role and use the mention property to mention the role...

spice adder
#

Having a strange issue

class BanLogs(commands.Cog):
    def __init__(self, client):
        self.client = client
        guild = client.get_guild(507364684924452896)

        @commands.command()
        @commands.has_role('Staff')
        async def reason(self, ctx, msgID: int, *, arg):
            msg = await client.get_channel(876688282552008734).fetch_message(msgID)
            embeds = msg.embeds
            if embeds:
                textcontent = msg.content
                newembed = embeds[0].copy()
                newembed.description =str("📄 **Reason:**\n" + arg)
                await msg.edit(content = textcontent, embed = newembed)
            else:
                await ctx.send("Message has no embed.")
                await ctx.message.delete()

        @reason.error
        async def reason_error(self, ctx, error):
            if isinstance(error, commands.MissingRole):
                await ctx.send("You do not have the required permissions to use this command: `Staff`")

def setup(client):
    client.add_cog(BanLogs(client))
``` when I have the commands decorator inline with `self.client = client`, none of my commands can be found (i.e. 
`Ignoring exception in command None: discord.ext.commands.errors.CommandNotFound: Command "reason" is not found`, and when it's inline with `def __init__` , it comes back with `"client" is not defined`
#

I'm just not sure what I oughta do to fix that, and I was wondering if anyone could give some insight on it, any help is greatly appreciated

hushed galleon
#

role mentions are formatted as <&ID>, however im not aware if github allows you to customize the message sent with it

hushed galleon
slate swan
#

@sick birch what are the projects youre leading anyways?lemon_raised_eyebrow

slate swan
hushed galleon
#

doing alright, had some fun writing an async lib for battleye rcon

spice adder
slate swan
hushed galleon
slate swan
# slate swan ,yes I did

you should be just storing the id instead of Context itself, because context becomes invalid after some time, like a update in message, message getting deleted etc...

spice adder
#

Hmm

hushed galleon
#

you should reference client in your command using ctx.bot or self.client as you have defined in init

spice adder
#

Alrighty, thank you, that's very helpful

slate swan
slate swan
#

if you want to acess ctx in a view, ill recommend passing it in the view's init dunder and making it an attribute of the view instead of making it an attribute of bot

spice adder
#
class BanLogs(commands.Cog):
    def __init__(self, client):
        self.client = client
        deltarune = client.get_guild(507364684924452896)

    @commands.command()
    @commands.has_role('Staff')
    async def reason(self, ctx, msgID: int, *, arg):
        msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
        embeds = msg.embeds
        if embeds:
            textcontent = msg.content
            newembed = embeds[0].copy()
            newembed.description =str("📄 **Reason:**\n" + arg)
            await msg.edit(content = textcontent, embed = newembed)
        else:
            await ctx.send("Message has no embed.")
            await ctx.message.delete()

    @reason.error # <- name of the command + .error
    async def reason_error(self, ctx, error):
        if isinstance(error, commands.MissingRole):
            await ctx.send("You do not have the required permissions to use this command: `Staff`")
```hmm, if this is what you were meaning, it worked, but it's not responding to anything aside from the message edit, I.e. no ctx.send or ctx.message.delete
full valley
#
Traceback (most recent call last):
  File "/Users/grayson/Documents/6Mans/cas_v9.py", line 1, in <module>
    import discord
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/__init__.py", line 20, in <module>
    from .client import Client, AppInfo, ChannelPermissions
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/client.py", line 38, in <module>
    from .state import ConnectionState
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/state.py", line 36, in <module>
    from . import utils, compat
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/compat.py", line 32
    create_task = asyncio.async
                          ^
SyntaxError: invalid syntax

Process finished with exit code 1

Any ideas?

slate swan
visual island
visual island
full valley
#

pycharm

slate swan
#

or the interaction channel itself

visual island
slate swan
#

imagine asking for help in here and dpy server simultaneously 😔

#

Ye ye ik

#

totally not checking which guild is better

slate swan
jagged adder
#

if i want to load a @bot.command to run code in a seperate file instead on continuing on below, how would i go about redirecting the code? i think thats the kinda thing a cog is used for tho i have no experience with them

slate swan
#

but their toxicity-

jagged adder
slate swan
#

least you could do is make a Command in one and add it to the bot in another

slate swan
jagged adder
#

as far as i was aware u cant import a 'command'

slate swan
#

and dirty, and could be broken

jagged adder
#

ah

slate swan
#

there arent any ways unless you write logic functions and import them from other files and call them under your command passing in required arguments, that's even more messier

#

cogs are 100% authentic to use

jagged adder
#

isnt too much to learn how to use em is there

slate swan
jagged adder
#

ive had a brief google but need to look into it more i spose

slate swan
#

iirc

jagged adder
#

alr

slate swan
#

as ash said, just use cogs

#

in case you're interested in "how"

#

hi, gm sarth 👋

#

gm Sparky

#
interaction.client.get_channel(e).fetch_message(my_msg.id)
``` sarth ^
slate swan
#

k

spice adder
#
class BanLogs(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    @commands.has_role('Staff')
    async def reason(self, ctx, msgID: int, *, arg):
        await ctx.message.delete()
        msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
        embeds = msg.embeds
        if embeds:
            textcontent = msg.content
            newembed = embeds[0].copy()
            newembed.description =str("📄 **Reason:**\n" + arg)
            await msg.edit(content = textcontent, embed = newembed)
        else:
            await ctx.send("Message has no embed.")
``` everything seems to working as intended here except for the ctx.send
#

Any idea why that might be?

slate swan
#

no errors? that means the message msg has embeds

spice adder
#

Hmm

slate swan
spice adder
#

I tried it on a message sent by myself in the channel

#

Not one by the bot, so that's why I'm confused

slate swan
#

it is a valied channel id + integer

spice adder
slate swan
slate swan
# slate swan Sarth ^

oh, thats wierd, you have access to your bot variable right? try using bot.get_channel

#

if that doesn't work you will need to fetch the channel

paper sluice
#

it wont just send Message has no embed

slate swan
#

In my code,
It gets the channel

#

And the channel1 variable in it gets the channel’s id

#

oh so e is a channel itself?

#

yah

#
channel1 = dono[str(interaction.guild.id)]["channel"]

        e = client.get_channel(channel1)
#

Nextcord dev?

#

oh so you would do e.fetch_message

slate swan
#

mhm k lemme try

slate swan
#

ik 2 of them, Epic and vco

slate swan
#

And yah
It is a “host” button in giveaway donation

#

So it is easier to host the giveaway

#

ASnyanwave oh, thats noice

slate swan
#

ryuga

paper sluice
#

ya?

slate swan
#

uwu

#

💀

#

ignore the message!

#

😔 it sends the PRESENCE payload to the gateway not "gateway event to the gateway"

slate swan
#

the text is poorly punctuated 😔

slate swan
slate swan
slate swan
dusky pine
#

use grammarly

slate swan
dusky pine
#

this text is grammatically correct

#

but it's wordy, and hard to read

slate swan
#

totally my gist moment

slate swan
#

grammarly?

#

no

#

or maybe I could make a pull req

dusky pine
#

at this point just pay a person with an english degree to fix it

vocal snow
#

ask andy he'll use esoteric language which noone will understand but it will sound fancy

slate swan
#

zeffo delete your message 😔

vocal snow
#

hi ashley

full valley
#

Anyone remember how to fix the certification error

dusky pine
slate swan
vocal snow
#

:D

full valley
#

yeah

vocal snow
#

Getting [SSL: CERTIFICATE_VERIFY_FAILED] on Python 3 on OS X?
Navigate to your Applications/Python 3.X/ folder and double click the Install Certificates.command to fix this.
Happy coding!

slate swan
#

andy's gist would probably be the most readable one

full valley
#

ty

dusky pine
#

who's andy lol

vocal snow
#

our deity

slate swan
#

nullptr/typedef

#

andy simps smh

dusky pine
#

their name sounds hot 😍

slate swan
#

.....

#

ya'll need to visit a therapist 😔

#

no u

dusky pine
#

nah i dunno what youre talm bout

#

everyone simps for andy

slate swan
#

!ot

unkempt canyonBOT
slate swan
#

ow, anyways ill go before someone runs..

#

nvm

shrewd apex
#

👋

slate swan
#

i still wonder if that emoji is a slapping one....

dusky pine
vocal snow
slate swan
#

^

shrewd apex
#

smh i was just saying 'hello'

slate swan
#

lmao

vocal snow
#

I wonder when Pydis admins are going to rename this channel to #ot3-discord-bots

dusky pine
#

special non-changing ot

slate swan
#

no surprise why this is the 2nd most active channel

dusky pine
#

just okimii's flirting area

slate swan
#

😍

shrewd apex
#

ofc ryuga applies routine revives for keeping it alive

grim oar
#

Okifynvwwami

shrewd apex
grim oar
#

I had an intercourse with okingfrmi

slate swan
#

....

#

whos that

grim oar
#

Your mum

slate swan
#

😔

#

lmaoooo

dusky pine
#

bro

slate swan
#

okimii that gist could be written in a better way ngl

#

too wordy and confusing and repeating

vocal snow
#

"could be return"

slate swan
#

eh

#

lmao

#

im down

#

just !d discord.Activity the users who ask how to set status 😩

#

lmao

vocal snow
#

!d discord.Activity

unkempt canyonBOT
#

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

• [`Game`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Game "discord.Game")

• [`Streaming`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Streaming "discord.Streaming")
vocal snow
#

they won't understand shit from this !

slate swan
#

🗿

slate swan
slate swan
#

😭

#

I don't mind if my bot makes request to change status multiple times

grim oar
#

don't mind when the bot gets ratelimited too

shrewd apex
#

isnt it fine to make a task loop for that? or just put it in commands.Bot

dusky pine
#

assert dominance, set status in on_message

shrewd apex
#

or have i been doing it wrong till date

grim oar
shrewd apex
#

ic

slate swan
slate swan
grim oar
#

reconnects can happen multiple times within the cooldown period bor

dusky pine
slate swan
#
bot = commands.Bot(...)
bot.presence_changed = False

@bot.listen("on_ready")
async def uwu():
  if not presence_changed:
    await bot.change_presence(...)
    bot.presence_changed = True

easy

dusky pine
slate swan
#

me

dusky pine
#

all my homies use bot.event

slate swan
#

all my homies make an event system

#

i use listen so I can name all my functions uwu or smth

#

i forgor to tell im using hikari and that event gets triggered only once.

dusky pine
#

uwu

slate swan
#

uwu

shrewd apex
#

uwu

grim oar
#

:tomstaring:

dusky pine
#

damn you nova

#

ruined the chain 😔

slate swan
#

nova should be banned

shrewd apex
#

broke the streak👀

grim oar
#

I should be unalive but no one has managed to make it happen

slate swan
#

!ot

unkempt canyonBOT
slate swan
grim oar
#

Didn't ask but ok

slate swan
#

ok

dusky pine
#

oki ^~^

slate swan
grim oar
#

That means presence payloads are sent and received from the gateway!!

#

🥵

#

I forgor if that's true tho, what okavtrremi said

#

😳

vocal snow
#

okavtrremi

dusky pine
#

it's kind Sir "Okimii" III Jr.

unkempt canyonBOT
#

disnake/gateway.py line 748

async def change_presence(```
slate swan
#

it uses DiscordWebsocket.send which sends a str to the gateway

#

how does that still matter, the websocket is already ready.

unkempt canyonBOT
#

disnake/gateway.py lines 726 to 728

async def send(self, data: str, /) -> None:
    await self._rate_limiter.block()
    await self.socket.send_str(data)```
slate swan
#

on_ready gets fired only after the websocket is ready and connected to discord

shrewd apex
#

maybe there are times when websocket needs to reconnect to discord pithink

slate swan
#

yeah thats why the on_ready may get triggered multiple times

#

but there's no way that on_ready is getting triggerd and the bot is not connected with gateway

unkempt canyonBOT
#

discord/state.py lines 585 to 586

self.dispatch('connect')
self._ready_task = asyncio.create_task(self._delay_ready())```
slate swan
#

@slate swan I got questions

slate swan
#

the only reasons i see not doing stuff in on ready is that it gets triggered multiple times, cache issues and some limitations

shrewd apex
#

i think they meant if it reconnects then there will be multiple reqs send for on_ready?

slate swan
#

which you can prevent using wait_until_ready

slate swan
#

and no i can't use the activity kwargs in bot because i need to get something from cache

slate swan
# slate swan about?

why do you got disnake examples in the gist, like it's just the name of the lib that has changed, makes the gist look a bit more cluttered

slate swan
# slate swan pardon?

it sends a gateway event not a request to be exact
the client is connected to the gateway?

#

the client would send a event payload to the gateway so ofc it would be connected.

#

thats the point, its already exchanging events... so whats the issue with sending one?

grim oar
#

the ratelimits

slate swan
#

20 times in 5 seconds

#

and yeah ratelimit is the thing i totally agree with, but I dont understand the getting disconnected from gateway yet.

slate swan
grim oar
#

I think I read somewhere what can cause disconnection, I think it's in rd*nny

dusky pine
#

why did you censor it

grim oar
#

yes

dusky pine
#

what

slate swan
#

mhm

#

but its a tiny detail i kinda wanted to point out as well

paper sluice
spice adder
# paper sluice show code
        @client.command()
        @commands.has_role('Staff')
        async def reason(ctx, msgID: int, *, arg):
            msg = await client.get_channel(876688282552008734).fetch_message(msgID)
            embeds = msg.embeds
            if embeds:
                textcontent = msg.content
                newembed = embeds[0].copy()
                newembed.description =str("📄 **Reason:**\n" + arg)
                await msg.edit(content = textcontent, embed = newembed)
            else:
                await ctx.send("Message has no embed.")
                await ctx.message.delete()``` Sorry Im late wah
slate swan
#

this screams attribute error

spice adder
#

? the get_channel part works, as well as the msg.edit

dusky pine
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
spice adder
#

The part that isn't working is the ctx.send, even when the message has no embeds it won't send anything

slate swan
#

that was my mistake i forgot the method was their

shrewd apex
#

print embeds and check

slate swan
#

it always returns a list iirc

#

if its empty the list would be empty and would have a falsy value making the else get triggered

#

yeah and if there's no embed it should trigger the else part

#

yup

#

and its not message_content intent as he probably invoked the command itself lol

#

they are using fetch_message so that won't matter anyways

#

yup

#

well idk im going to sleep😴

slate swan
#

is it like that in ur file too

spice adder
#

Ah shit wait that's from the old one where I accidentally used client

#

I deeply apologize

#
class BanLogs(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    @commands.has_role('Staff')
    async def reason(self, ctx, msgID: int, *, arg):
        await ctx.message.delete()
        msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
        embeds = msg.embeds
        if embeds:
            textcontent = msg.content
            newembed = embeds[0].copy()
            newembed.description =str("📄 **Reason:**\n" + arg)
            await msg.edit(content = textcontent, embed = newembed)
        else:
            await ctx.send("Message has no embed.")

    @reason.error # <- name of the command + .error
    async def reason_error(self, ctx, error):
        if isinstance(error, commands.MissingRole):
            await self.ctx.send("You do not have the required permissions to use this command: `Staff`")
#

Hope that explains the wonky indentation

slate swan
#

add else: raise error at the end of that error handler

#

and retry the command

spice adder
#

Got it, thanks for directing me!

#

Was able to see the error after that and fixed it

lethal moat
#
async def StartGame(interaction: Interaction, winners: int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
Traceback (most recent call last):
  File "c:\Users\Harshit\Desktop\raffle bot\main.py", line 29, in <module>
    async def StartGame(interaction: Interaction, winners: int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 2043, in decorator
    result = slash_command(name=name, description=description, guild_ids=guild_ids,
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 1245, in decorator
    app_cmd = ApplicationCommand(
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 773, in __init__
    self._guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
TypeError: 'int' object is not iterable
#

according to the documentation I did nothing wrong

spice adder
#

Also, this is a bit disconnected from my last question, but is there a way to query the audit logs for a specific user's unban reason in on_member_unban?

slate swan
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
livid hinge
spice adder
#

Ah, pretty much just so it goes away immediately after being ran

livid hinge
#

oh

#

the message the command runs with ?

spice adder
#

Mhm

livid hinge
#

gotcha

spice adder
# unkempt canyon

Hmm, I see how to get the user, target, action, and total entries, but would getting the reason be as simple as

async for entry in guild.audit_logs(limit=1, action=discord.AuditLogAction.unban):
  reason = (f"{entry.reason}")
#

Or is that just an oversimplification

spice adder
#

And then I'm not sure how that'd fit into something like this

    # unban logs
    @commands.Cog.listener()
    async def on_member_unban(self, guild, user):
        username =  str(user)
        userid = str(user.id)
        textcontent = str(f"{userid}")
        async for entry in guild.audit_logs(user=user, limit=1, action=discord.AuditLogAction.unban):
          reason = (f"{entry.reason}")
        unbanembed = discord.Embed(
                  title=f"{username} was unbanned",
                  description=f"📄 {reason}",
                  color=0x2ecc71)
        unbanembed.timestamp = datetime.datetime.utcnow()
        unbanembed.set_author(name="Action: Unban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135738379784192/900265836210696212.gif")
        unbanembed.set_footer(text="$reason [MessageID] New Reason")
        modlog = self.client.get_channel(876688282552008734)
        await modlog.send(content = textcontent, embed = unbanembed)
slate swan
#

dpy is so effing weird

lethal moat
#
Ignoring exception in on_guild_available
Traceback (most recent call last):
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 415, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 1907, in on_guild_available
    if (await guild.rollout_application_commands(
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\guild.py", line 3230, in rollout_application_commands
    await self.register_new_application_commands(data=guild_payload)
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\guild.py", line 3244, in register_new_application_commands
    await self._state.register_new_application_commands(data=data, guild_id=self.id)
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\state.py", line 736, in register_new_application_commands
    await self.register_application_command(app_cmd, guild_id)
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\state.py", line 752, in register_application_command
    raw_response = await self.http.upsert_guild_command(self.application_id, guild_id, payload)
  File "C:\Users\Harshit\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\http.py", line 337, in request
    raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.0.name: Command name is invalid

Absolutely no clue what is causing this (nextcord slash commands)
the command names are the same as the function names

#

and my code is correct according to documentation

slate swan
cerulean folio
#

hi guys !
do u know how to get someone's bio with a bot? i need this person to be on same server

lethal moat
#
@bot.slash_command(name="startgtb", guild_ids=[guild_id], description="Starts the game of guessing the balance")
async def startgtb(interaction: Interaction, winners: int = SlashOption(name="Winners", description="How many winners will there be?", required=True)):
slate swan
#

ok and

#

just show the command names, not whole of it

cerulean folio
lethal moat
#

startgtb
stopgtb
guess

slate swan
cerulean folio
#

okie thanks Ashley ZhongHeart

slate swan
vocal snow
spice adder
#
    @commands.Cog.listener()
    async def on_member_unban(self, deltarune, user):
        async for entry in deltarune.audit_logs(user=user, limit=1, action=discord.AuditLogAction.unban):
            reason = (f"{entry.reason}")
            username =  str(user)
            userid = str(user.id)
            textcontent = str(f"{userid}")
            unbanembed = discord.Embed(title=f"{username} was unbanned", description=f"📄 **Reason:**\n{reason}", color=0x2ecc71,)
            unbanembed.timestamp = datetime.datetime.utcnow()
            unbanembed.set_author(name="Action: Unban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135738379784192/900265836210696212.gif")
            unbanembed.set_footer(text="$reason [MessageID] New Reason")
            modlog = self.client.get_channel(876688282552008734)
            await modlog.send(content = textcontent, embed = unbanembed)
``` alright, I put it in like this, but it says unexpected indent at line 52 (`unbanembed = discord.Embed[...]`)
lethal moat
cerulean folio
slate swan
#

use any of those

spice adder
#

<> moment ehe

slate swan
#

too much to do, so I though that i'd remove em when they'll embed lmao

spice adder
lethal moat
spice adder
slate swan
slate swan
#

at line 52

lethal moat
spice adder
vocal snow
shrewd apex
#

there is a extra ,

vocal snow
#

If there is a lowercase variant of any letters used, you must use those

shrewd apex
#

remove the ,

spice adder
#

I'm thinking it may have to do with the async for... part, but I'm not sure where I'd move that to

slate swan
#

that shouldn't matter

spice adder
#

^ and without it, same error

slate swan
spice adder
spice adder
#

Sure

#
import discord
from discord.ext import commands
import re, datetime, json
from requests import get

class BanLogs(commands.Cog):
    def __init__(self, client):
        self.client = client
        deltarune = client.get_guild(507364684924452896)

    @commands.command()
    @commands.has_role('Staff')
    async def reason(self, ctx, msgID: int, *, arg):
        await ctx.message.delete()
        msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
        embeds = msg.embeds
        if embeds:
            textcontent = msg.content
            newembed = embeds[0].copy()
            newembed.description =str("?? **Reason:**\n" + arg)
            await msg.edit(content = textcontent, embed = newembed)
        else:
            await ctx.send("Invalid Message.")

    @reason.error # <- name of the command + .error
    async def reason_error(self, ctx, error):
        if isinstance(error, commands.MissingRole):
            await self.ctx.send("You do not have the required permissions to use this command: `Staff`")

    @commands.command()
    @commands.has_role('Staff')
    async def censor(self, ctx, msgID: int):
        await ctx.message.delete()
        msg = await self.client.get_channel(876688282552008734).fetch_message(msgID)
        embeds = msg.embeds
        if embeds:
            textcontent = msg.content
            newembed = embeds[0].copy()
            newembed.title =str("[CENSORED NAME] was banned")
            await msg.edit(content = textcontent, embed = newembed)
        else:
            await ctx.send("Invalid Message.")

    # unban logs
    @commands.Cog.listener()
    async def on_member_unban(self, deltarune, user):
        async for entry in deltarune.audit_logs(user=user, limit=1, action=discord.AuditLogAction.unban):
            reason = (f"{entry.reason}")
            username =  str(user)
            userid = str(user.id)
            textcontent = str(f"{userid}")
            unbanembed = discord.Embed(title=f"{username} was unbanned", description=f"📄 **Reason:**\n{reason}", color=0x2ecc71,)
            unbanembed.timestamp = datetime.datetime.utcnow()
            unbanembed.set_author(name="Action: Unban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135738379784192/900265836210696212.gif")
            unbanembed.set_footer(text="$reason [MessageID] New Reason")
            modlog = self.client.get_channel(876688282552008734)
            await modlog.send(content = textcontent, embed = unbanembed)

    # ban logs
    @commands.Cog.listener()
    async def on_member_ban(self, deltarune, user):
        username =  str(user)
        userid = str(user.id)
        textcontent = str(f"{userid}")
        banreason = await deltarune.fetch_ban(user)
        newreason = re.sub('(?i)(.*#\d{4}):\s*',  '', banreason.reason)
        banembed = discord.Embed(title=f"{username} was banned", description=f"📄 **Reason:**\n{newreason}", color=0xe74c3c)
        banembed.timestamp = datetime.datetime.utcnow()
        banembed.set_author(name="Action: Ban", icon_url="https://cdn.discordapp.com/attachments/881835799547609109/959135500386574367/510502447895281685.png")
        banembed.set_footer(text="$reason [MessageID] New Reason")
        #banembed.add_field(name="?? User ID:", value=f"{userid}", inline=True)
        modlog = self.client.get_channel(876688282552008734)
        await modlog.send(content = textcontent, embed = banembed)

def setup(client):
    client.add_cog(BanLogs(client))
fierce sonnet
vocal snow
#

you did it in the screen shot but not here

spice adder
#

Ah, I changed it before a bit

#

My bad, let me edit that rq

spice adder
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ExtensionFailed: Extension 'cogs.BanLogs' raised an error: IndentationError: unexpected indent (BanLogs.py, line 52)
spice adder
#

KomiEyes

vocal snow
#

that's weird

#

which command is causing this?

spice adder
#

on_member_unban

vocal snow
#

no, the error you send is a Command Invoke Error

#

do you have a command that loads the extension?

spice adder
#

Hmm

#

I do, that's what's showing that error

#

Since it won't let me reload it if there's an error in the code

vocal snow
spice adder
#

Nope, not at all

crisp drift
#

Remove that line and repaste it

#

@vocal snow disgustedface

spice adder
crisp drift
#

clan

vocal snow
#

kai !!!

vocal snow
crisp drift
#

ikr, sometimes that happens to me, removing the line and repasting it works

vocal snow
#

sounds like something nova would do ngl

crisp drift
crisp drift
spice adder
#

I have

#

Error no longer pops up, but neither do any messages

lone egret
#

new to discord.py, not entirely sure how to handle this error

#

discord.ext.commands.errors.CommandNotFound:

dusky pine
lone egret
#

okay i guess

crisp drift
spice adder
#

Oh yeah, didn't notice that part lmao

lone egret
#

on_command_error..thanks

vocal snow
spice adder
#

True, I wrote that on mobile back when I used replit

crisp drift
#

Try to print the entry to see what u get

heavy folio
vocal snow
#

and casting that string to a string

crisp drift
#

ded

slate swan
#

Is it possible to store something a user sent like:

@bot.command 
async def store(ctx,*,message):
    await set_msg(ctx.author,ctx)
   
    user = await get_message(ctx.author,ctx)
    
    user[str(ctx.author.id)][“message”] = message

    await ctx.send(“Done 👍”)
stiff gorge
#
class BasicView(discord.ui.View):
    def __init__(self, ctx: commands.Context, timeout: optional[int] = None):
        super().__init__(timeout=timeout)
        self.ctx = ctx

cogs.fun' raised an error: NameError: name 'optional' is not defined

paper sluice
#

its Optional u need to import it from the typing library

#

you can also do int | None if ur on python3.10

stiff gorge
#

ohk ty

last mica
slate swan
last mica
#

Yeah can

slate swan
#

does somebody knows I want to get the server-id in a different function which does ctx, like ctx.guild.id but I want it without ctx

unkempt canyonBOT
#

@slate swan Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!

slate swan
slate swan
#

I tried this:

@bot.command()
async def set_id(ctx):
  async with ctx.typing():
      server_id= ctx.guild.id
      id_psss = server_id```
and then I tried to access it in other functions but it was returning None
slate swan
#

you have to create a botvar

slate swan
#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

slate swan
#

^

#

ok

#

will this work:

@bot.command()
async def set_id(ctx):
  async with ctx.typing():
      server_id= ctx.guild.id
      bot.id_psss = server_id```
and then I can access it by bot.id_psss
slate swan
slate swan
#

@slate swan IT WORKED , TYSM

#

welcome

robust fulcrum
slate swan
#

I mean, there's a lot of ways of using it.

#

from discord.commands import slash_command

robust fulcrum
slate swan
robust fulcrum
#

Yes

robust fulcrum
#

Maintainer of dpy is back so me use it

slate swan
#
@commands.Cog.listener(name="on_member_remove")
        @commands.guild_only()
        async def fm(member):
            await member.ban(reason="User left while freeloader mode was on.")
``` this should ban the member who leaves right?
slate swan
#

mhm k

robust fulcrum
#

How can we get discord channel in input?

slate swan
#

arg: discord.TextChannel

lyric apex
#

How to get sticker url by the bot

slate swan
#

!d discord.Client.fetch_sticker

unkempt canyonBOT
#

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

Retrieves a [`Sticker`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Sticker "discord.Sticker") with the specified ID.

New in version 2.0.
slate swan
#

!d discord.Sticker.url

unkempt canyonBOT
lyric apex
#

Sticker Id how to get that?

slate swan
#

or do you mean on discord?

unkempt canyonBOT
lyric apex
#

I wanna steal the sticker using that

slate swan
lyric apex
#

But what if the bot isn't there

slate swan
#

(test)

slate swan
#

all you can do is get it bytes using the cdn maybe

#

sarth,yk how to store a message in json file if possible

tacit token
#
capy=[
    "https://cdn.pixabay.com/photo/2018/03/12/10/39/mammal-3219344__480.jpg",
    "https://upload.wikimedia.org/wikipedia/commons/a/a2/Hydrochaeris_hydrochaeris.jpg"
]
capyfact=["A kapibarák a világ legnagyobb rágcsálói.","A fogaik soha nem hagyják abba a növekedést.","Csoportban élnek.","Egyedi vokalizációjuk van.","Növényevők.","Saját kakijukat is megeszik.","Remek ülőhelyek kisebb állatoknak.","Nagyon jó úszók.","Képesek aludni a vizen.","35 km/h-val képes futni.","A capybarákat a többi állat ülőhelynek használja.","Nagyon szociális állatok."]


@commands.guild_only()
@client.command(name="capy",aliases=["Capybara","Capy"])
async def capy(ctx):
    embed=discord.Embed(description=f"{random.choice(capyfact)}")
    embed.set_image(f"{random.choice(capy)}")
    await ctx.send(embed=embed)

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Command' has no len()

lyric apex
#
await create_sticker(*, name, description, emoji, file, reason=None):```