#discord-bots

1 messages · Page 1105 of 1

stiff fern
#

Bc I dont like having the _ in command name but if I dont it'll error in the code

sick birch
#

Not possible, I don't think spaces are allowed in argument names

#

You shouldn't be using globals in the first place

#

Unless you mean a bot variable

stiff fern
#

Alright no biggy

#

second question,

#

you should be able to use load_extension on cogs inside a cog itself right

sick birch
#

Well, I suppose you can

stiff fern
#

Because I'm trying to /unload a cog thats already loaded because it loads with the bot in the main.py file but it returns an error saying it isnt loaded

#

But when I try to load it, it now tells me it could not be loaded

sick birch
#

hmm

stiff fern
#

Even tho I can still use the commands inside said cog

#

I dont know if its because of how I organized my files or if that matters or what

#

Whats the syntax to refer to files in the same directory

#

or do you need to specify that

#

Like if I wanted to do something to another file in the same folder I should just be able to refer to the file by its name

#

Or do I need to do like \filename or something

stiff fern
#

Needed to change how I was typing the file name

left idol
#
@stats.error
async def stats_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        if ctx.author.id == 92786442891169792:
            args = (player)
            kwargs = {}
            await ctx.invoke(ctx.command, *args, **kwargs)
        else:
            msg = f'Try again in {round(error.retry_after)}s'
            await ctx.respond(msg, ephemeral = True)

in pycord am i using invoke incorrectly? i want it so if i use the command that has argument player: discord.User, i override the cooldown

fading marlin
#

you're probably looking for ctx.command.reinvoke

slate swan
#

No, however I think there’s a special character

stiff fern
#

what is this special character

#

Im just trying to get rid of the _ that shows up in the command line

#

which doesnt make sense to me why I would be able to name it if that name isnt used for it

slate swan
#

Scroll down a bit

#
        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png")
        embed.set_image(url='attachment://Выбери Профессию.png')

        await ctx.send(f"{e_iron}{e_organic}{e_wood}{e_details}{e_batteries}{e_shards}", file = file1, embed = embed, view=Counter(ctx.author.id))

Dear, tell me why the picture is on top of the embed and not in it

#

my·Call()

#

U could use that dot

stiff fern
#

oo

#

I like it, graci

slate swan
fading marlin
unkempt canyonBOT
#

@discord.app_commands.rename(**parameters)```
Renames the given parameters by their name using the key of the keyword argument as the name.

This renames the parameter within the Discord UI. When referring to the parameter in other decorators, the parameter name used in the function is used instead of the renamed one.

Example:

```py
@app_commands.command()
@app_commands.rename(the_member_to_ban='member')
async def ban(interaction: discord.Interaction, the_member_to_ban: discord.Member):
    await interaction.response.send_message(f'Banned {the_member_to_ban}')
stiff fern
#

graci

fading marlin
#

wait no nvm

#

I'm blind

slate swan
#

I have it spelled correctly

heady sluice
#

symbols probably

stiff fern
#

Question, so I have the specific error inside of my on_command_error event but instead of using the message for it, it uses else: and raises the error even tho the error codes match where the yellow line is

heady sluice
#

oh and _ just read

heady sluice
#

it does not seem like it

stiff fern
#

Im using

bot.tree.on_error = self.on_command_error

in my init

#

It still uses it, it just used else: instead of the isinstance extensionalreradyloaded

heady sluice
#

hm, no idea about the on_error in the CommandTree

#

shouldn't it be on_command_error there too

#

is this just like unnecessary confuser

stiff fern
#

it was because originally I had an event but it wasnt working properly

#

I mean, its on command error so it makes sense to me

#

its just w/out the client event

#

built differently

slate swan
#

how can i make my bot show in it's game activity how many servers it's in?

stiff fern
#

wym game activity

sage otter
#

!d discord.Client.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
narrow grail
#

no, this only sends the guy who interacted with a direct message, but i want to let it send a message to a certain user

#

like me

sage otter
# narrow grail like me

So like you can fetch your user object using discord.Interaction.client.fetch_user and you can just call the discord.User.send method on that.
Example:

interaction = ... # Interaction obj here
user = await interaction.client.fetch_user(idhere)
await user.send("whats up pimps")
heady sluice
#

no members intents? 🥺

sage otter
#

?

heady sluice
#

with members intents get_user's better

#

👍

sage otter
#

I dont assume everyone has intents so AMshrug

heady sluice
#

yeah but people that do have intents will end up fetching anyways

stiff fern
#

@sick birch hey robin, a quick question

so remember how I used

bot.tree.on_error = self.on_command_error

for the error event but it only responds to app_commands errors, I.E CommandInvokeError instead of the discord.ext.commands errors which are the ones I need it to respond to bc CommandInvokeError is to general, do you know how I would change that

heady sluice
#

if they dunno

sick birch
slate swan
#
async def on_member_join(memeber):
    welcomebed = discord.Embed(
        colour = (discord.Colour.black()),
        title = 'i worked',
        description = f' i worked'
    )
    await memeber.send(embed=welcomebed)```
stiff fern
#

ye Im using slash commands

slate swan
#

i was wondering why

heady sluice
#

it's not a command

#

it's an event

sage otter
#

you dont need to wrap that method btw

slate swan
heady sluice
#

it triggers when someone joins

sick birch
heady sluice
#

you need members intents for it

sage otter
#

you can just make it colour=discord.Colour.black()

slate swan
stiff fern
heady sluice
stiff fern
#

Im getting both errors, yellow is what I need it to respond too, red is what it is responding to

sick birch
#

Ah I think I see

stiff fern
#

So it responds to app_commands.errors but not commands.error

slate swan
sick birch
#

CommandInvokeError is picking up and encapsulating ExtensionAlreadyLoadedError

stiff fern
#

ye its like prioritizing

#

Do you know how I fix that

sick birch
#

Get the original using error.original

heady sluice
#

I wanna speak like that too

stiff fern
#

On the isinstance(error.original, ...)?

slate swan
#

@heady sluice yep same issue, just added intents to my code

heady sluice
#

show how

sage otter
#

Robins english is honestly really good for not being from the US.

heady sluice
#

or UK

sick birch
heady sluice
#

why don't you include the UK

slate swan
#

wait, something is missing up via my color, just wait 1 moment and let me fix this

sick birch
heady sluice
#

what the

slate swan
#

can anyone send the kwargs for ctx send

sick birch
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.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
potent spear
#

ah, it's a channel, mb

sick birch
heady sluice
#

it would've been discord.abc.Messageable

potent spear
#

yeah, I hate that it doesn't autocomplete tbh

heady sluice
heady sluice
sick birch
#

😔

sage otter
#

does Color.default() return a black color?

#

if not you can just set color to 0x000000

heady sluice
#

shouldn't default be gray

#

discord-theme gray

#

topic
What happens to a View after you delete the message it was sent with?
Does it timeout?

sage otter
heady sluice
#

looks normal to me idk I'm not racist

sage otter
#

...?

heady sluice
narrow sparrow
#

💀

cedar stream
#

So basically discord is slowly eliminating the need for bots

heady sluice
#

please help my sleep schedule

stiff fern
#
if command_name != 'critical' or 'core':

Can you do something like this or do you need to write command_name twice

heady sluice
#

does the View live after the message was deleted?

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
stiff fern
#

rip

heady sluice
#

best looking and most useless one:

if any(favourite_fruit == fruit for fruit in ("grapefruit", "lemon")):
stiff fern
#

Confused on why its saying cogs.corecogs when it should just be cogs.core

#

Is core like a name you cant use?

sick birch
#

You leaked your token, might wanna regen it

stiff fern
#

yea i do that like every 10m no worries

sick birch
stiff fern
#

What can someone actually do with ur token, just recode your bot basically?

#

grief ur server

narrow grail
sick birch
#

They can do anything you can

#

I just have to use your token in my bot.run()

stiff fern
#

Good thing its just in some test server that I just use to test bots 😂

#

Hmm its still doing it

#

Oh I forgot a ,

#

derp

sick birch
#

that would make sense

stiff fern
#

yup lol

sick birch
#

The cogs. from the previous one would leak into it

stiff fern
#

Is there a way to check if a cog is already loaded/unloaded without actually loading/unloading it since that would give an error

sage otter
#

i could be wrong tho

sage otter
unkempt canyonBOT
sage otter
#

you could look at this

stiff fern
#

dont really understand that, I was just going to use a try except statement

stiff fern
# unkempt canyon

Is this suppose to be like

if cog:
  # Then extention is loaded?

@sage otter

sage otter
#

no you literally just check if the name of the cog that you want to see is loaded or not is in the mapping's keys

stiff fern
#

What is mapping's keys

sick birch
#
if "cogs.cog_name" in bot.cogs:
  # cog is loaded
sage otter
#
if not "cogname" in bot.cogs.keys():
    #if this condition passes. The cog isnt loaded
#

i hate you Robin

stiff fern
#

Ooh

sick birch
#

lol

sick birch
#

beat you to it + better

sage otter
#

Literally took me an hour to write that because im like mentally drained rn

sick birch
#

Nah it's good, both work

narrow grail
cerulean folio
#

Don't be mean to me I know I'm stupid but I'm leaning LMAO

@client.event
async def on_message(message):
  prefix = (message.content.split(' ')[0]).lower()
  msg = message.content.split(' ')[1:]

I kinda have a feeling this is REALLY bad XD

#

But I don't know what approach I should use, if you guys have suggestions

fading marlin
fading marlin
#

you're welcome, happy coding!

stiff fern
#
    initial_extensions = [
        'cogs.suggestion',
        'cogs.ping',
    ]
    
    @app_commands.command(name='load', description='Enable a command')
    @app_commands.describe(command_name="Command name")
    async def load(self, interaction: discord.Interaction, command_name: str):
        if command_name in ['all', '*']:
            for ext in self.initial_extensions:

                # If cog not loaded
                if ext not in self.bot.cogs:
                    await self.bot.load_extension(ext)

Is there something obviously wrong with this portion of code, I'm trying to script the command to work with 'all' or '*' to run on all extensions inside the initial_extensions list, and the script doesn't break it or anything but it gives me very broad errors that dont really tell me whats wrong with it

slate swan
#

You're looking at the wrong command, looks like unload is causing issues

stiff fern
#

That's just the command I used to test it but it'll do the same for load as well

#

its all basically copy paste in terms of code

#
    # Disables a command
    @app_commands.command(name='unload', description='Disable a command')
    @app_commands.describe(command_name="Command name")
    async def unload(self, interaction: discord.Interaction, command_name: str):
        if command_name in ['all', '*']:
            for ext in self.initial_extensions:

                # If cog loaded
                if ext in self.bot.cogs:
                    await self.bot.unload_extension(ext)

                unload_embed = discord.Embed(
                    title='Commands Unloaded',
                    description=f'All available commands have been successfully **unloaded**.',
                    timestamp=datetime.now(),
                    color=0x49ba8b)  # Green

                unload_embed.set_footer(text='All Commands Disabled')
                await interaction.response.send_message(embed=unload_embed, ephemeral=True)

        elif command_name not in ['main', 'core']:
            await self.bot.unload_extension(f'cogs.{command_name}')

            unload_embed = discord.Embed(
                title='Command Unloaded',
                description=f'The requested command has been successfully **unloaded**.',
                timestamp=datetime.now(),
                color=0x49ba8b)  # Green

            unload_embed.set_footer(text='Command Disabled')
            await interaction.response.send_message(embed=unload_embed, ephemeral=True)

        elif command_name in ['main', 'core']:
          # more stuff here just didnt paste

heres unload tho

sick birch
#

You probably meant to unindent the interaction.response.send_message(...)

slate swan
#

He beat me by a second

sick birch
#

haha, we knew exactly what to look for

slate swan
#

That for loop was trouble

sick birch
#

I knew there was some responding to interaction inside loops going on

stiff fern
#

o

#

yup that fixed the error ty

stiff fern
#

initial_extensions = [
        'cogs.suggestion',
        'cogs.ping',
    ]
    
    # Disables a command
    @app_commands.command(name='unload', description='Disable a command')
    @app_commands.describe(command_name="Command name")
    async def unload(self, interaction: discord.Interaction, command_name: str):
        if command_name in ['all', '*']:

            for ext in self.initial_extensions:
                # If cog loaded
                if ext in self.bot.cogs.keys():
                    print(ext)
                    await self.bot.unload_extension(ext)

I dont think my for loop for unload command isnt working properly because its not printing ext and its not disabling the command/returning any errors

slate swan
#

cogs.keys() return the Cog names, not their extension path, so you "if ext in ...." will never be True @stiff fern

stiff fern
#

How does it return it? Wouldnt it be a list or something

#

@slate swan

slate swan
stiff fern
#

Right

#

oh

#

yea

#

Im doing it right then

#

ext is the cog name?

#

Is it suppose to be w/out the cogs.

slate swan
#

cog.suggestion can't be a cog name.

#

its the path of file.

stiff fern
#

so its just suggestion

slate swan
#

class MyCog(commands.Cog):
``` here MyCog is the cog name
stiff fern
#

gottcha

slate swan
#

if you do something like ```py
class MyCog(commands.Cog, name="potato")

stiff fern
#

🙏

#

Do you know how I would remove the first 4 characters of the file name then so it would match up, I know I can do like ext[-3] but that would remove the last 3 I believe or something like that?

slate swan
#

!e print("654321"[3:])

stiff fern
#

!e print("654321"[:4])

unkempt canyonBOT
#

@stiff fern :white_check_mark: Your eval job has completed with return code 0.

6543
stiff fern
#

Oh you reverse the :

slate swan
#

here you go

stiff fern
#

graci

stiff fern
#

Anyone know why the # isn't working for comments?

#

oh nvm I think it does work it just doesnt look like it

cerulean folio
#
def check(m, message):
    return m.author == message.author
msg = await client.wait_for('message', check=check)

This whole thing is inside a function, in a file, that I'll call from another file. How can I pass message to check please?

slate swan
#

it should be on_message instead of message ig

#

ig

cerulean folio
#

oh no no not that one. I means message the variable, not 'message' the argument

slate swan
cerulean folio
#

oh uhm... ok

#

lemme see

cerulean folio
#

I'll try something

cerulean folio
gaunt ice
#

can we get the dms messages of the user and bot

#

anyone?

slate swan
#

Hey I have like 9 buttons is there any callback that calls when any one of them of the buttons is clicked

#

I mean to say 9 buttons but 1 callback

slate swan
slate swan
# slate swan Yeah
class View(ui.View):
    async def callback_for_all(self, button, interaction):
        ...

    @ui.button(...)
    async def foo(self, button, interaction):
       await self.callback_for_all(button, interaction)

    @ui.button(...)
    async def bar(self, button, interaction):
       await self.callback_for_all(button, interaction)
``` ez
slate swan
#

or use the discord.ui.Button method and set thr callback of all buttons to a single function

#

okay

left idol
#
@stats.error
async def stats_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        if ctx.author.id == 92786442891169792:
            args = (player)
            kwargs = {}
            await ctx.invoke(ctx.command, *args, **kwargs)
        else:
            msg = f'Try again in {round(error.retry_after)}s'
            await ctx.respond(msg, ephemeral = True)

in pycord am i using invoke incorrectly? i want it so if i use the command that has argument player: discord.User, i override the cooldown

slate swan
#

it's ctx.command.invoke isnt it

#

its not documented

#

ctx.invoke is a thing too

#

weirded

#

but that's not how you pass args and kwargs pichu

#

man just literally copy pasted it from the docs

#

nvm

slate swan
left idol
#

i thinkthats what im confused about?

#

how would i define it in this error

#

from my command

devout iris
#

Hello i want to ping everyone who has @role role. How to do it?

slate swan
#

you can't access command arguments in error handler. thats not how discord.py is designed

slate swan
slate swan
unkempt canyonBOT
slate swan
#

!d discord.Role.mention ...?

unkempt canyonBOT
devout iris
left idol
#

how could i then instead make it so when i use a command, i dont get a cooldown?

pliant gulch
unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function...
slate swan
#

how can i disable all buttons is a view without disabling them one by one?

slate swan
#

the message got deleted by by the bot

slate swan
#

ohk thanks

#

finnaly i have done with my tic tac toe game

#

doesn't stopping the view just stops listening for interaction, the buttons don't change right

#

ye

#

!d discord.ui.View.stop

unkempt canyonBOT
#

stop()```
Stops listening to interaction events from this view.

This operation cannot be undone.
slate swan
#
if (self.but1.disabled and self.but2.disabled and self.but3.disabled and self.but1.emoji == "❎" and self.but1.emoji == "❎" and self.but3.emoji=="❎") or (self.but4.disabled and self.but5.disabled and self.but6.disabled and self.but4.emoji == "❎" and self.but5.emoji == "❎" and self.but6.emoji=="❎") or (self.but7.disabled and self.but8.disabled and self.but9.disabled and self.but7.emoji == "❎" and self.but8.emoji == "❎" and self.but9.emoji=="❎") or (self.but1.disabled and self.but5.disabled and self.but9.disabled and self.but1.emoji == "❎" and self.but5.emoji == "❎" and self.but9.emoji=="❎") or (self.but3.disabled and self.but5.disabled and self.but7.disabled and self.but3.emoji == "❎" and self.but5.emoji == "❎" and self.but7.emoji=="❎") or (self.but1.disabled and self.but4.disabled and self.but7.disabled and self.but1.emoji == "❎" and self.but4.emoji == "❎" and self.but7.emoji=="❎") or (self.but2.disabled and self.but5.disabled and self.but8.disabled and self.but2.emoji == "❎" and self.but5.emoji == "❎" and self.but8.emoji=="❎") or (self.but3.disabled and self.but6.disabled and self.but9.disabled and self.but3.emoji == "❎" and self.but6.emoji == "❎" and self.but9.emoji=="❎"):

💀

#

ugh

#

any idea

#

how can i do it better or its fine

slate swan
#

i was not getting any idea

#

so i did this 💀

maiden fable
#

Please, for the love of God and sanity and PEP 8, use a different line for each condition

slate swan
#

uh ok

maiden fable
#

Or take this to #esoteric-python before someone gets a stroke in this channel after seeing that if statement

slate swan
#

lol

dapper stirrup
#

Good morning, or evening guys...
I use module mcstatus

And have a simple line of code,

server = JavaServer.lookup("palmproject.joinserver.ru")
status = server.status()```

It works okay, and then I use it to:

@bot.event
async def on_ready():
while True:
palmus = "Players: ", status.players.online
palmus = str(palmus)
await bot.change_presence(activity=discord.Game(name=palmus))
await sleep(15)


It works correctly, but why bot shows not Players:3(it's not smile lol), it shows... (on the image)

How to have bot status ``Players: 2``?

||about changing activity i found information here https://stackoverflow.com/questions/59126137/how-to-change-activity-of-a-discord-py-bot||
maiden fable
slate swan
#

set a task to change it every time instead

dapper stirrup
slate swan
#

then?

dapper stirrup
#

how to have Players: 0, not ('Players', 0)

#

?

slate swan
#
async def on_ready():
 while True```
the sound alone is haunting me
slate swan
maiden fable
#

Ah

maiden fable
#

Nah ignore that

slate swan
#

palmus[0]
palmus[1] <- returns thr number of players

maiden fable
#

Will return 0 Players are online

dapper stirrup
#

i sec

slate swan
#

set a task....

maiden fable
#

That too

dapper stirrup
#

oh ve just read about tuple, useful thing😎

slate swan
#
from discord.ext import commands, tasks

def server_lookup():
     server = JavaServer.lookup("")
     return server.status()

@tasks.loop(seconds=15)
async def status_c():
     #wait until ready
     status = await bot.loop.run_in_executor(None, sever_lookup) #same as server.status() but not blocking
      ...
#

okay I hate autocorrect

#

dickord wht

#

autocorrect

dapper stirrup
dapper stirrup
#

NameError: name 'tasks' is not defined

#

what..

slate swan
#

from discord.ext import tasks

dapper stirrup
#

thx

maiden fable
#

nice import u got there btw

dapper stirrup
cerulean folio
#
return (',\n').join(imgs)

someone knows why the result is correct in console but bot messes it up? D:

maiden fable
slate swan
#

oh wait no im blind

cerulean folio
cerulean folio
maiden fable
#

Weird

#

can u show yr whole code?

slate swan
maiden fable
#

Works for me

#

@cerulean folio

cerulean folio
#

this is crazy

bright palm
cerulean folio
#
https://via.placeholder.com/300.png,/nhttps://via.placeholder.com/300/09f.png,/nhttps://via.placeholder.com/300/09f/fff.png,/nhttps://via.placeholder.com/728x90.png,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.jpg,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.png,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.jpg,/nhttps://pp.vk.me/c624121/v624121992/3cf22/YRIx_w-QySg.jpeg

I'm getting this from the bot lol

bright palm
#

Yeah you can see the ,/n

cerulean folio
#

yes but I did \n in my program

#

and the result is correct in console

bright palm
#

Have you reloaded the command if you made any changes?

cerulean folio
#

reloaded?

slate swan
#

use a for loop ? if that doesnt work

cerulean folio
#

I stopped the bot and launch it back

#

wait i'll delete pycache folders ><

bright palm
#

Can you show the full code

cerulean folio
#

ohhhhh !!!

#

I know the problem ! XD

maiden fable
#

What an issue 😔

#

What is the issue?

cerulean folio
#

I'm so stupid !

#

I coded the bot to store data in a dictionnary

#

so obviously \n won't work !

maiden fable
#

Ah

cerulean folio
#

no it's now fine

#

thanks a lot guys tho XD

slate swan
cerulean folio
slate swan
#

😐

slate swan
#

create_task doesn't wait for a result

slate swan
gaunt ice
#

can i get a message from dms of a user through the bot

#

if yes can someone give an example

slate swan
slate swan
gaunt ice
#

okimmi

gaunt ice
slate swan
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.
gaunt ice
#

ohh

slate swan
#

you can also use an attr of the Member class

#

!d discord.Member.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.
gaunt ice
#

okk

#

tyy

slate swan
slate swan
slate swan
slate swan
slate swan
#

im not sure if create_task will return it, unsure

slate swan
#

it returns a Task object

slate swan
#

exactly, that's the point

#

mhm thats nice

left idol
#

how many fields can i have in one embed line?

slate swan
#

3 in a row

#

25 fields total in an embed

left idol
#

alright

#

going back to what i asked earlier as well, is there no way to disable cds for specific users?

#

in pycord

slate swan
#

you can do that for sure, but im not aware of "how" atm, need to check source code

left idol
#

alright, thank you!

slate swan
#

well, one way is using dynamic cooldowns

#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
short silo
#

bruh we can give more than 25 with basic_autocomplete in utils

slate swan
slate swan
slate swan
slate swan
#

smh I'll just stop visiting this channel instead

#

easier

short silo
placid skiff
halcyon topaz
slate swan
placid skiff
#

pip install git+https://github.com/Rapptz/discord.py

placid skiff
spring flax
#

I think I saw that on disnake master, the automod was added. Has anyone used it? If so what does it look like?

placid skiff
#

uhm no they didn't add an automod integrated D_D

#

the last great change were released on 7 May

#

with a bug fix a few days after

#

||this morning i can't fuckin write||

flint coral
slate swan
placid skiff
#

!rule 7

unkempt canyonBOT
#

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

placid skiff
#

there is a telegram community for aiogram, you can ask there for help

keen grove
#

hi guys

#

so im making a bot and it's not coming online

#

shows me this on the terminal

#

oh nvm

placid skiff
keen grove
#

ah there

#

i got this in

vocal snow
keen grove
#

aight

#

rn?

#

run*

slate swan
vocal snow
keen grove
#

omg not here bruh

vocal snow
#

one parenthesis, multiple parentheses

slate swan
#

well doesnt parenthesis refer to the pair?

maiden fable
vocal snow
slate swan
maiden fable
vocal snow
#

exactly. so much easier

short silo
# maiden fable What does this mean?

I mean, we can build a list for larger than 25 options though we can provide different input than the autocomplete list, but that's easily manageable

maiden fable
#

Ah, yea that's a hacky way haha

keen grove
#

its not coming online

#

:/

short silo
maiden fable
#

And this is more of a bug imho, than a proper way to do so

heavy folio
#

it's basically codeblock with syntax highlighting

#
Text : 1

yaml

#

you don't, you can use \n

#

or just make a docstring (but be sure to use inspect.cleandoc on it since docstrings include indents)

placid skiff
#

yaml is not widely use with python, btw there is some example:

name: my_project
version: 1.0
commands:
  test_command:
    command_name: test
    description: just a test
    parameters: None
short silo
#

When we set a category's perms and then create channels under it. Do we have to use something to sync the perms with the category or is it automatic ?

potent spear
short silo
#

Guess i will have to try then

#
role_Bot: discord.Role = await GUILD.create_role(name="Bots",color= Colour.yellow(),hoist=True,permissions=Permissions.administrator)

what might i be doing wrong

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'flag_value' object has no attribute 'value'
visual island
devout iris
#

How can i check member invites?

placid skiff
#

you mean if he has an invite link or to get when a member joins with an invite to detect which member invited him?

polar scroll
cloud dawn
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

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

This function returns the class instance to allow for fluent-style chaining.
regal pulsar
#

show us your code

slate swan
#

wth

regal pulsar
#
@bot.command()
async def status(ctx):
    embed = discord.Embed(footer = "test" , title = "Status Checker" , description=f"The Bot Is Online ") , Timestamp=datetime.datetime,utcnow  set_footer(*, text= "test", icon_url=None)
    await ctx.send(embed=embed)
slate swan
#
@bot.command()
async def status(ctx):
  embed = discord.Embed(title = "Status Checker",
                        description=f"The Bot Is Online")
  embed.set_footer( text="Test")
  await ctx.send(embed = embed)
regal pulsar
#

^

frozen patio
#

It’s ok

#

I remember when I was learning you’re fine 😅

full lily
#

you're getting that error because you tried to read json from a file that was empty

maiden fable
#

Add {} to the JSON and the error gonna go away

regal pulsar
#

as long as something’s there

full lily
#

are you running low on space?

misty stream
#

i have a question i want to kick a tagged member out of the channel but if i run this it kicks everyone out of the channel

@commands.command(name='Kick')
    async def Kick(self, ctx, membertokick : discord.Member):
        guild = ctx.guild
        user = membertokick
        await ctx.channel.set_permissions(user, read_messages=False, manage_channels=False, manage_messages=False, manage_permissions=False)
        await user.move_to(None)
        await ctx.channel.purge(limit=1)
        await ctx.send(f"Kicked {user} for you")

what am i doing wrong ?

placid skiff
heady sluice
#

why remove from a voice channel

misty stream
heady sluice
#

but the command's used in a text channel?

misty stream
#

its used in the voice text channel

dull terrace
#

is there any reason why this message would stop updating

status_channel = client.get_channel(948495137846210571)
status_message = await status_channel.fetch_message(948496382254264360)

while True:
    await status_message.edit(content=content, components=dev_components)
    await asyncio.sleep(600)``` ![7739monkathink](https://cdn.discordapp.com/emojis/960314142030442566.webp?size=128 "7739monkathink")
misty stream
dull terrace
#

do you have to re-fetch the message every few hours or something

heady sluice
#

oh you'll probably check for that later I see

dull terrace
#

well it's not editing it after a few hours-days randomly

heady sluice
#

oh after days

#

maybe monkaHmm
I won't say anything cuz I don't know

#

even BlackBull's question, there has to be something that went wrong in the implementation of voice channel text channels

misty stream
# heady sluice even BlackBull's question, there has to be something that went wrong in the impl...
if before.channel is None and after.channel is not None:
        if after.channel.id == config.CustomChannelLobby:
            guild = member.guild
            name = 'Custom Channels'
            category = discord.utils.get(member.guild.categories, name=name)
            overwrites = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False, manage_channels=False, manage_messages=False, manage_permissions=False),
            member: discord.PermissionOverwrite(read_messages=True, manage_channels=True, manage_messages=True, manage_permissions=True)
            }
            channel = await guild.create_voice_channel(member.name, category=category, overwrites=overwrites)
            await member.move_to(channel)
            await channel.send(f"I Created this channel for you {member.mention}")
#

seems allright ?

heady sluice
#

yes

misty stream
#

then i still dont know what i am doing wrong Xd

heady sluice
#

the everyone role isn't able to read messages when the channel is created

#

is that intended

misty stream
#

yes

#

its a private channel where i need to invite people to

#

and i want to be able to kick them out of it too

heady sluice
#

I actually have a bot that does the same thing lmao

misty stream
#

well private voice chat

#

nice !

slate swan
#

Bro why just why

#

I literally told u with paragraphs

heady sluice
#

but in my bot you can rename the voice channel with a command and set it to private with a command

#

and these stuff are stored

misty stream
#

no my stuff isnt stored Xd

heady sluice
#

my internet went off so many times my database went offline and I can't get it online again

misty stream
#

oof

heady sluice
#

so the bot ain't running

misty stream
#

yeah i am planning to make a webdashbord soon

#

but im not verry good with py yet

slate swan
#
class vacancies(discord.ui.View):
    def __init__(self, id, ctx):
        super().__init__()
        
        self.id = id
        e_iron = discord.utils.get(ctx.guild.emojis, name="iron") 

        @discord.ui.button( label=f'{e_iron}', style=discord.ButtonStyle.red, row=1)
        async def coun(self, interaction: discord.Interaction, button: discord.ui.Button):
            
                button.label = "123"
                await interaction.response.edit_message(view=self)

Dear, tell me why it gives an error?

#

It takes 2 arguments

#

But 1 was given

#

@slate swan this

#

U cant do like this.

#

make the decorator indent same as init method

#

Lol

#

Oh, how do you write it all down?

#

Yeah

#

Also

#

it's emoji

#

Not label

#

!d discord.ui.Button.emoji

unkempt canyonBOT
slate swan
#
class vacancies(discord.ui.View):
    def __init__(self, ctx.author.id, ctx):
        super().__init__()
        
        self.id = id
        e_iron = discord.utils.get(ctx.guild.emojis, name="iron") 

        @discord.ui.button( label=f'{e_iron}', style=discord.ButtonStyle.red, row=1)
        async def coun(self, interaction: discord.Interaction, button: discord.ui.Button):
            
                button.label = "123"
                await interaction.response.edit_message(view=self)
                
    @commands.command(aliases = ["Вакансии", "вакансии"])
    async def vacancies(self, ctx: commands.Context):
        
        with open("./Эмодзи/Ресурсы/Железо.png", "rb") as image:
            iron_1 = image.read()
            iron = bytearray(iron_1)
        await ctx.guild.create_custom_emoji( name = "iron", image = iron)
        e_iron = discord.utils.get(ctx.guild.emojis, name="iron") 
embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png")
        embed.set_image(url='attachment://Выбери Профессию.png')

        await ctx.send(f"{e_iron}{e_organic}{e_wood}{e_details}{e_batteries}{e_shards}", file = file1, embed = embed, view=vacancies(ctx.author.id))

        await asyncio.sleep(0,1)
        await ctx.guild.delete_emoji(e_iron)

I write a command, it creates a button and an emoji. The emoji is for the button name. ID so that only the author of the command can press the button

regal pulsar
#

lmao

slate swan
#

Although if the command is immediately entered by 2 people, I think the bot will get confused in the name and give an error. really, as I was advised, I will make separate servers for emoji😅
Thank you all

balmy bobcat
#

hello, is it possible that a discord.py bot sends a message when my play activity changes?

balmy bobcat
#

I can't find anything on the internet

cloud dawn
#

My answers are amazing lol

balmy bobcat
cloud dawn
unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.

This is called when one or more of the following things change:

• status

• activity

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

i think you need presence intent for that too

balmy bobcat
#

thank you very much !!

cloud dawn
#

And member intents.

balmy bobcat
#

I was looking for this

#

Don't worry about intents

livid hinge
balmy bobcat
#

I have intents = discord.Intents.all()

cloud dawn
#

Like a true coder has.

livid hinge
#

ofc have to enable it in bot setting too (tho i think you'd be gettimg an error if you hadn't)

slate swan
#

does anybody know how can I check if the arg is not a member arg

unkempt canyonBOT
#

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

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

if isinstance(member, Member): you did like this?

cloud dawn
slate swan
#

ok

livid hinge
#

you probably need a type hint on the parameter too

cloud dawn
#

The typehint is also a converter.

slate swan
# cloud dawn Could you show what you've got so far?

Code:

async def avator(ctx,member:discord.Member=None):
  if isinstance(member, commands.MissingRequiredArgument):
    if isinstance(member, commands.errors.MemberNotFound):
        #Mycode
    else:
      embed=discord.Embed(title="Error",description="Opps, There arg is not a member")
      await ctx.send(embed=embed)```
livid hinge
#

def thing(ctx, member: Union[str,Member,None]) or something

cloud dawn
cloud dawn
#

Well since you made it an optional argument you need to remove the whole MissingRequiredArgument and error msg.

livid hinge
#

yeah the converters are pretty nice

cloud dawn
livid hinge
#

it's supposed to be a member or nothing ?

slate swan
#

ahh, its not working leave it

balmy bobcat
#
@client.event
async def on_presence_update(before,after):
    channel=client.get_channel(986077790296231997)
    await channel.send(f"New activity: {after.name} , {after.activity.name}")
#

tried this but not working

livid hinge
#

wait not obj == Member actually

cloud dawn
#

What have you changed? I will code a bit for you for a small example.

slate swan
#
@client.command()
async def balance(ctx):
  await open_account(ctx.author)

  users = await get_bank_data()

  wallet_amt = users[str(users.id)]["wallet"]
  bank_amt = users[str(users.id)]["bank"]

  em = discord.Embed(title=f"{ctx.author.name}'s balance", color = discord.Colour.dark_theme())
  em.add_field(name = "Wallet", value = wallet_amt)
  em.add_field(name = "Bank", value = bank_amt)
  await ctx.send(embed=em)

error:

Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'id'
slate swan
balmy bobcat
#

no, I get nothing

#

not an error, nor a message

cloud dawn
slate swan
#

but still not working so I left it

#

np

cloud dawn
#

Okay, if you ever want to pick it up there are enough helpers here.

cloud dawn
balmy bobcat
#

Yeah, normally everything is fine

cloud dawn
balmy bobcat
#

intents = discord.Intents.all()
client = commands.Bot(command_prefix="m?",description="Mascarpone", intents=intents)
balmy bobcat
cloud dawn
# cloud dawn try to make it a listener
@client.listen()
async def on_presence_update(before,after):
    channel = client.get_channel(986077790296231997)
    await channel.send(f"New activity: {after.name} , {after.activity.name}")
cloud dawn
balmy bobcat
#

I'll try this

#

no change unfortunately :(

#

no error, no message

cloud dawn
#

I can't think of anything atm maybe some other underlying issue here, I gotta eat as well parents are screaming.

balmy bobcat
#

no prob, thank you still! bon appetit

cloud dawn
#

@sick birch You got some time?

cloud dawn
slate swan
#
    @commands.command(aliases = ["Вакансии", "вакансии"])
    async def vacancies(self, ctx: commands.Context):
        
        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png")
        embed.set_image(url='attachment://Выбери Профессию.png')

        await ctx.send(file = file1, embed = embed, view=vacancies(ctx.author.id))

Dear, tell me why the picture is not inside the embed

regal pulsar
#

if you want an image in the embed use

#

!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.
slate swan
slate swan
dull terrace
#
with BytesIO() as image_binary:
    img.save(image_binary, "PNG")
    image_binary.seek(0)
    file = disnake.File(fp=image_binary, filename="image.png")```
#
embed.set_image(url="attachment://image.png")```
slate swan
slate swan
dull terrace
#

and send the file

slate swan
#

k

#
async def open_account(user, ctx):

  user = await get_bank_data()

  with open("mainbank.json","r") as f:
    user = json.load(f)

  if str(user.id) in user:
        return False
  else:
    user[str(ctx.author.id)] = {}
    user[str(ctx.author.id)]["wallet"] = 0
    user[str(ctx.author.id)]["bank"] = 0

  with open("mainbank.json","w") as f:
    json.dump(user,f)
  return True

async def get_bank_data():
  with open("mainbank.json","r") as f:
    user = json.load(f)
  return user
``` k?
dull terrace
#

missed this line if str(user.id) in user:

dull terrace
#

also you could just do user[str(ctx.author.id)] = {"wallet": 0, "bank": 0} to save lines

slate swan
#

Error says all

#

await open_account(ctx.author,ctx)

#

Try this

slate swan
balmy bobcat
#

I think it's better to use message as an argument instead of ctx

#

if tou went to send a message, type message.channel.send

#

if you want the author, type message.author

slate swan
#

literally read the last line

#

No space left on device

sick birch
#

The error is kind of self explanatory

sick birch
#

Your device has no more storage space left

#

That's exactly what the error is saying

slate swan
#

your host wont allow you to write more data in your server's storage

sick birch
#

Delete files you don't use anymore

slate swan
#

Idk what he didn't understand

balmy bobcat
slate swan
#

.

#

!d discord.ext.commands.Context.author , ctx.author

unkempt canyonBOT
slate swan
#

Ur works. You always help me thanks@slate swan

#

pleasure

#

..

#

i think you meant to write users which is a dict, instead of user

#

yes sir

#

yeah it gotta be users

maiden fable
#

I hate the fact that deta.sh has no code editor 😔

maiden fable
slate swan
#

k

#

Remove users

#

Error knowledge is must

#

ye

#

Add {} to mainbank.json

#

i did

#

Can u show

#

uh maybe put them in one line like {}

#

💀

slate swan
#

Default is set to read

shrewd apex
#

isnt normal file opening and closing sync and u need aiofiles for async?

slate swan
#

beg & balance works but my wallet isnt updated

#

it should add the amount i got in beg command

balmy bobcat
#

can I share my problem here or should I create a thread not to flood

shrewd apex
#

did u dump the file

#

after editing

slate swan
balmy bobcat
#
@client.event
async def on_member_update(before,after):
    channel=client.get_channel(986077790296231997)
    await channel.send(f"New activity (on_member_update): {after.name} , {after.activity}")

The bot detects when I start a game but after.activity returns my custom status and not the game I'm playing

shrewd apex
#

why don't u just print the after object which prolly a dict then see what u need

slate swan
#

there can be more than 1 activity

#

!d discord.Member.activities check all of them for your game

unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

slate swan
#
@discord.ui.button( emoji = f"{e_shards}", style=discord.ButtonStyle.secondary, row=3)

how to make a button inactive?

#

what library are you using?

shrewd apex
#

disabled=True

#

in kwargs

slate swan
#

oh thanks

shrewd apex
# slate swan what library are you using?

i have a bot command which send image to a channel and uses that link in an embed so what do u think is the limit before bot gets rate limited for spamming message in a channel

balmy bobcat
# slate swan !d discord.Member.activities check all of them for your game

thank you very much!

New activity (on_member_update): Noémimolette 🍰 , (<CustomActivity name='Every day I wake up, then I start to break up' emoji=<PartialEmoji animated=False name='🍰' id=None>>, <Activity type=<ActivityType.playing: 0> name='Baba Is You' url=None details=None application_id=576482762446602270 session_id=None emoji=None>, <Spotify title='Scarlet Forest' artist='Toby Fox' track_id='4zLEqCe2KCWBJLKN3RyWAG'>)

I do find my game inside of it "ActivityType.playing: 0" but how can I display that?

slate swan
shrewd apex
#

ic

slate swan
#

dump(json, file)

manic wing
slate swan
#

💀

slate swan
shrewd apex
slate swan
#

It is

slate swan
#

load and loads both exist, loads loads a dictionary from a string.

shrewd apex
#

in the tutorial?

shrewd apex
#

i thought u were telling loads instead of dump...

slate swan
#

mypy making me feel worse kek

shrewd apex
#

just json.dump

slate swan
#

!d json.dump

unkempt canyonBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").

The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.

If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
shrewd apex
#

and json here is ur dict

#

not the json module

slate swan
shrewd apex
slate swan
shrewd apex
#

ic why send a pillow thenpithink

slate swan
#

I'm on bed

shrewd apex
#

oh

slate swan
#

he wants to image manipulate us 🙉

#

..

shrewd apex
slate swan
#

Just bored tbh

shrewd apex
#

mhm

slate swan
#

This channel description should be set to don't know python? coding a bot? , don't worry we are here to help

shrewd apex
#

🤣

maiden fable
#

@shrewd apex I got another idea to prevent making a paginator!

shrewd apex
maiden fable
#

I can show the information on a jinja template instead 👀

shrewd apex
#

ok

#

u tried with modals?

slate swan
#

I got a new cmd idea :D

#

Modals question answers

maiden fable
shrewd apex
#

u don't write it down or save somewhere👀

maiden fable
#

The last time I used those were like 1-2 years ago

#

And they were saved in my old laptop
For some reason they weren't saved to my google ac

slate swan
maiden fable
#

Nvm made a new account

#

The convo is finished anyways, thanks for that

balmy bobcat
#

by the way do you know why on_member_update sends the same message twice?

maiden fable
#

cz u got two on_member_update events?

dapper dragon
#

ჰეყ

#

How i can connect WSGI serveR?

maiden fable
#

remove the port kwarg

balmy bobcat
maiden fable
#

do u have any cogs?

#

prolly two bot instances running

slate swan
maiden fable
balmy bobcat
#

I don't have any cog nor listener

maiden fable
#

Prolly double bot instances

slate swan
maiden fable
#

NameError: name 'uwu' is not defined

slate swan
#

what should I do I am doing this:

    embed=discord.Embed(title="Error",description="Opps, There was no member")
    await ctx.send(embed=embed)```
but its still giving that error
slate swan
maiden fable
#

check for error lol

slate swan
#

no

maiden fable
#

Nice

slate swan
#

see now I edited it

shrewd apex
#

...

maiden fable
#

Its still the same?

slate swan
slate swan
maiden fable
#

Then what does yr event looks like?

uncut jacinth
#

Hey guys anyone know why these buttons listed above each other?

slate swan
#

This is giving me error:

    embed=discord.Embed(title="Error",description="Opps, There was no member")
    await ctx.send(embed=embed)```
it still gives me this error
balmy bobcat
uncut jacinth
maiden fable
uncut jacinth
#

These

slate swan
balmy bobcat
uncut jacinth
#

discord_components

shrewd apex
maiden fable
uncut jacinth
maiden fable
#

Open Command Prompt

#

And search for the process named Python

shrewd apex
#

strange

slate swan
# uncut jacinth discord_components

create a nested list

buttons = [
  [
    Button(...),
    Button(...)
  ], #this list is the first row
  [
    Button(...),
    Button(...),
  ], #this is the second row
]
uncut jacinth
#

Ok

shrewd apex
#

it changes with format in componentspithink ?

slate swan
#

.....

#

@maiden fable
This is the correct:
This is giving me error so tell me how to fix it:

  embed=discord.Embed(title="Error",description="Opps, There was no member")
  await ctx.send(embed=embed))```


it still gives me the MissingRequiredArguement error
shrewd apex
#

yes Ashley is smort

#

the nesting ic

slate swan
slate swan
# maiden fable Show the whole event dude

ok:

async def avator(ctx,member:discord.Member):
  if isinstance(member, commands.MissingRequiredArgument):
    embed=discord.Embed(title="Error",description="Opps, There was no member")
    await ctx.send(embed=embed)
  userAvatarUrl = member.avatar_url
  embed=discord.Embed(title=member.display_name+"'s"+" Avator")
  embed.set_image(url=userAvatarUrl)
  await ctx.channel.send(embed=embed)```
slate swan
slate swan
#

wtf

shrewd apex
#

...

slate swan
#

😔 ay wtf, that goes in the error handler.

shrewd apex
#

i was mind blown literally nothing left

maiden fable
#

And @slate swan's too

slate swan
# slate swan ok: ```@bot.command(name='avator') async def avator(ctx,member:discord.Member): ...
@bot.command(name='avator')
async def avator(ctx,member:discord.Member):
  userAvatarUrl = member.avatar_url
  embed=discord.Embed(title=member.display_name+"'s"+" Avator")
  embed.set_image(url=userAvatarUrl)
  await ctx.channel.send(embed=embed)

@avatar.error
async def avatar_error(ctx, error):
  if isinstance(error, commands.MissingRequiredArgument):
    embed=discord.Embed(title="Error",description="Opps, There was no member")
    await ctx.send(embed=embed)
#

and fix the command spellings

maiden fable
slate swan
#

its avatar not avator

slate swan
maiden fable
#

No, I mean kill

slate swan
#

I was being sarcastic but OKAY

slate swan
balmy bobcat
#

killing py.exe killed python.exe

#

now I launch my file once again

maiden fable
#

Cool

#

Wait @balmy bobcat

#

before launching, check if there are any other python processes

balmy bobcat
maiden fable
#

Cool

balmy bobcat
#

still sends me the same message twice

slate swan
#

looli just reset ur bot token

maiden fable
#

Yea

#

But that isn't gonna help if yr IDE is running the script twice

slate swan
#

yeah the file runs, but the bot wont be responding twice

#

🚶‍♂️ just use the terminal while running code tbh

#

Yeah

slate swan
balmy bobcat
#

still sends message twice yet I did reset the token, closed my IDE and launched it from terminal

slate swan
#

can i see the code?

balmy bobcat
#

I'll just send the part that matters since my code is 400 lines long

import discord
from discord.ext import commands

intents = discord.Intents.all()
client = commands.Bot(command_prefix="m?",description="Mascarpone", intents=intents)

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game('m?info_mascarpone'))
    msc_channel=client.get_channel(986077790296231997)
    await msc_channel.send("Coucou! Me voila allumée!")
    await msc_channel.send("Nous sommes le {0} et il est {1}.".format(current_time[:itime],current_time[itime:]))

@client.event
async def on_member_update(before,after):
    if after.id == 475686699381424128:
        channel=client.get_channel(986077790296231997)
        listeactivite = str(after.activities)
        if "touhou" in str(listeactivite).lower():
            await channel.send("J'en connais une qui joue à Touhou :joy_cat:") 

client.run(TOKEN)
balmy bobcat
slate swan
slate swan
#

or is the member_update event erroring?

#
@commands.slash_command(description="help")
async def tests(ctx):
   await ctx.send(":hmm: Help \n> :hmm: Misc \n> :hmm: features \n> :hmm: Commands \n> :hmm: Fun \n> :hmm: Invite\n``Type _<command> for more info.")
``` my code
balmy bobcat
#

discord_slash* mb

balmy bobcat
#

(sorry for being french)

slate swan
balmy bobcat
slate swan
#

use some fork, or discord.py v2.0, discord-py-slash-command is outdated

lucid nebula
#

do anyone here know all possible arguments for the data dictionary requests.post(url, json=data) when sending discord messages using webhooks? or just embeds properties and profile pictures

stiff fern
#

Is there an API for app_commands because I can't find anything and Im trying to figure out some stuff lol

slate swan
#

does somebody know how can I fix this error:

Error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'append'

Code:

async def cdcmd(ctx,cmd:str):
  server_id= ctx.guild.id
  file_name = f"servers_cmds\\{server_id}.yml"
  if cmd == "avator":
    with open(file_name, 'r+') as f:
      content = yaml.safe_load(f)
      content["avator_cmd"]["D_Channels"].append([ctx.channel.id])
      f.seek(0)
      yaml.dump(content, f)
      embed=discord.Embed(title="Command Enabled",description="**Avator Command Has Been Disabled For This Channel**")
      await ctx.send(embed=embed)
      f.truncate()```
balmy bobcat
#

I guess content["avator_cmd"]["D_Channels"] is NoneType

slate swan
slate swan
lucid nebula
#

not yet, but ty for help

ruby lava
slate swan
lucid nebula
errant fern
#

Hey... My discord bot doesnt run in discord threads :\
Does anyone know why this happens... Are there any workaround?

balmy bobcat
#

I did some research, and on_member_update fires twice because my bot is on two different guilds: is there any way to avoid this?

slate swan
#

How do I make global command to check if a certain category iD and it doesn’t work in dms

ruby lava
stiff fern
#

Does anyone know the api for discord ui, like I'm able to make textinputs but are there other inputs for a dropdown for example?

slate swan
#

inputs dont work in dropdowns

#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
slate swan
#

does somebody know how can I check if serverid is not in this key, I tried this:

if server_id not in data["avator_cmd"]["D_Channels"]:

its a yaml file

#
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
    async def exit(self, ctx):
        
            await ctx.message.delete()

Dear, tell me why it gives an error?

sick birch
#

Button's don't take ctx

#

!d discord.ui.button

unkempt canyonBOT
#

discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
sick birch
#
async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):
  ...
upbeat ruin
#

@slate swan put the information into an array and then check if not in

stiff fern
#

is manage_server not the name for the manage server permission?

upbeat ruin
#

like read the file, and put the informations into an array?

stiff fern
slate swan
stiff fern
#

are u reading it

slate swan
#

yes

stiff fern
#

u dont know how to put the results into an array?

upbeat ruin
#

i guess i'm to stupid to understand your question

stiff fern
#

im smart enough to understand his question im just to stupid to fix it lol

slate swan
#

wait

stiff fern
#

is there an api for all the permission names

#

for has_permissions

#
    @app_commands.command(name='load', description='Enable a command')
    @app_commands.describe(command_name="Command name")
    @app_commands.checks.has_permissions(manage_server=True)
    async def load(self, interaction: discord.Interaction, command_name: str):

It says manage_server isn't a valid permission 😐

slate swan
#

@stiff fern I am trying to check if ctx.channel.id not in white_servers: and the white_servers is an array in the yaml file
and here how the variable it made:
white_servers = data["avator_cmd"]["D_Channels"]

stiff fern
#

homie i cant even get command checks to work, i doubt i can help you lol

stiff fern
#

yes

slate swan
#

oh

slate swan
upbeat ruin
#

uhm, maybe try casting channel_id to str

slate swan
#

ok

slate swan
upbeat ruin
#

can you like print white_servers to see if that is correctly read ?

slate swan
#

ok

#
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
    async def exit(self, interaction: discord.Interaction, button: discord.ui.Button):

Dear, what to write to delete the message?

slate swan
#

but idk why is it not working when I try to compare it

upbeat ruin
slate swan
#

ok

upbeat ruin
#

the double brackets is the problem

slate swan
#

oh

upbeat ruin
#
array = [[1], [2]]

if 1 in array:
  print("in")
slate swan
#

how do I fix it but in the yaml it like this:

  D_Channels:
  - - 962655220750491661```
upbeat ruin
#

uhm what does your yaml give you back when you add multiple ids?
is it like [[0][1]]?

slate swan
#

@upbeat ruin ?

upbeat ruin
upbeat ruin
#

in the for part

slate swan
#

ok

upbeat ruin
#

thats the fun part of a high level language 😮

#

is there a way to send a message, with the username/ userid ?

slate swan
#

If I get a reaction to a message, how do I delete that reaction?

#
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
    async def exit(self, interaction: discord.Interaction, button: discord.ui.Button): 

Dear, what to write to delete the message?

upbeat ruin
#

datetime.datetime.now(datetime.timezone.utc) ?

upbeat ruin
#

so now how do i send user messages that didn't message the bot ? 😄

keen grove
#

hii

#

so basicallyi got no errors in my code

#

but the bot isn't coming on again

upbeat ruin
# slate swan huh wdym?

lets say i have guids or usernames, is there a possibility to send messages or do they have to be in a specific server/group ?

maiden fable
#

You gotta have at least one mutual guild with the user to send DMs

#

in short, the user gotta be in bot.users

slate swan
#
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.secondary, row=4)
    async def exit(self, interaction: discord.Interaction, button: discord.ui.Button): 
       await interaction.response.delete()

Dear, what to write to delete the message?

upbeat ruin
slate swan
#

I enter a command and a message with a button is displayed. I click on the button and this message is deleted

maiden fable
#

!d discord.Interaction.original_message

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

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

Repeated calls to this will return a cached value.
upbeat ruin
maiden fable
#

U need members intent

slate swan
maiden fable
#

Ah

#

U first gotta reply to the msg before deleting

#

smth like interaction.response.defer()

round knoll
#

hello, how do i convert this boring discord "live" notification (for twitch) into a richer notification, including the category (game) streamed, title of stream and maybe the thumbnail too

#
@loop(seconds=90)
async def check_twitch_online_streamers():
    channel = bot.get_channel(966493808869138442)
    if not channel:
        return

    notifications = get_notifications()
    for notification in notifications:
        await channel.send("We are now live at https://www.twitch.tv/stream")
slate swan
upbeat ruin
maiden fable
#

Nice

maiden fable
upbeat ruin
#

just to wrap some stuff up:
the bot and i are in the same discord server, how do i send myself messages without messaging the bot?

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**.
maiden fable
#

!d discord.Guild.get_member

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
maiden fable
#

Uh huh?

#

yea

vale sierra
#

hello, i have this error with this part of my codes, can someone help me please ? thanks

upbeat ruin
slate swan
potent spear
slate swan
#

or use the Context class

maiden fable
potent spear
maiden fable
#

at least u know about some OOP and objects

#

for?

#

ig

slate swan
#

the member argument is None

upbeat ruin
maiden fable
#

members intent

slate swan
#

you should do member = member or ctx.author after the function signature

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

as hunter said^

vale sierra
#
@commands.command()
    async def stats(self, ctx, member: discord.Member=None):
        if member is None: member = ctx.author

        async with self.bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (ctx.guild.id, member.id)) as cursor:
            data = await cursor.fetchone()
            exp = data[0]

        async with self.bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id,)) as cursor:
            rank = 1
            async for value in cursor:
                if exp < value[0]:
                    rank += 1

        lvl = int(math.sqrt(exp)//self.bot.multiplier)

        current_lvl_exp = (self.bot.multiplier*(lvl))**2
        next_lvl_exp = (self.bot.multiplier((lvl+1)))**2

        lvl_percentage = ((exp-current_lvl_exp) / (next_lvl_exp-current_lvl_exp)) * 100

        embed=discord.Embed(title=f"**:bar_chart: Statistiques**", color=0xFF8100, timestamp=ctx.message.created_at)
        embed.add_field(name="Niveau :", value=str(lvl))
        embed.add_field(name="Expérience :", value=f"{exp}/{next_lvl_exp}")
        embed.add_field(name="Rang :", value=f"{rank}/{ctx.guild.member_count}")
        embed.add_field(name="Progression :", value=f"{round(lvl_percentage, 2)} %")

        await ctx.reply(embed=embed)
```  Hello, i have this error with this code, dont know how to fix it thanks for helping me :)
slate swan
#

after the function signature

#

not the top of your code lmao

slate swan
vale sierra
slate swan
#

how can I make every such time the presence change

#

try it with a loop but it doesn't change

#

embed = discord.Embed(
title = "Шахтер",
description= "123""321",
color= 0x19ff19
)
Dear, tell me how to write so that 123 is on one line and 321 on the other?

sick birch