#Basic Pycord Help

1 messages · Page 3 of 1

sour flint
#

I see most bots have a slash command name with a space is it possible in pycord? if so how

#

like this

rugged lodgeBOT
#

Here's the slash groups example.

sour flint
#

ty

daring valve
eager lintel
#

thank you

subtle moth
#

does pycord have anything equivalent to discord.py's discord.ext.commands.Bot.setup_hook function?

cyan violet
#

.rtfm user.created_at

sly karmaBOT
cyan violet
#

.rtfm discord.member

cyan violet
#

Where can I find the stuff like joined_at, created_at etc.

shell radish
#

It’s right there

daring grove
#

what requirements would I need to put in requirements.txt to make sure this doesnt happen?

heavy sky
#

py-cord

daring grove
#

like this?

heavy sky
daring grove
#

ah

#

that does make sense

grim estuary
#

Hello. How to place several embeds at once in one message?

little cobalt
grim estuary
#

Thank you

little cobalt
grim estuary
grim estuary
#

How to access the everyone role?

little cobalt
#

Why?

grim estuary
#

I need to assign permissions to the everyone role

grim estuary
#

Is it possible to make some kind of cooldown when pressing a button?

bitter meteor
#

how do i see the id of user who pressed the button?

bitter meteor
#

thanks

#

and how do i put parameter in view?

glossy latch
#

hey who can help me ?

#

i have a code for recording voice call

#

and it doesn't work

heavy sky
#

And what doesn't work with it?

glossy latch
#

yup

heavy sky
#

What error?

glossy latch
#
import discord
from discord.ext import commands

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

connections = {}


async def finished_callback(sink, channel: discord.TextChannel, *args):
    recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
    await sink.vc.disconnect()
    files = [
        discord.File(audio.file, f"{user_id}.mp3")
        for user_id, audio in sink.audio_data.items()
    ]
    await channel.send(
        f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files
    )


@bot.command()
async def start(ctx: commands.Context):
    """Record your voice in MP3 format!"""
    voice = ctx.author.voice

    if not voice:
        return await ctx.send("You're not in a vc right now")

    guild_id = ctx.guild.id
    if guild_id in connections:
        vc = connections[guild_id]
    else:
        vc = await voice.channel.connect()
        connections[guild_id] = vc

    sink = "mp3"
    vc.start_recording(
        sink,
        finished_callback,
        ctx.channel,
    )

    await ctx.send("The recording has started in MP3 format!")


@bot.command()
async def stop(ctx: commands.Context):
    """Stop recording."""
    guild_id = ctx.guild.id
    if guild_id in connections:
        vc = connections[guild_id]
        vc.stop_recording()
        del connections[guild_id]
        await ctx.message.delete()
    else:
        await ctx.send("Not recording in this guild.")




bot.run("token")

Ignoring exception in command start:
Traceback (most recent call last):
  File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped    
    ret = await coro(*args, **kwargs)
  File "c:\Users\rayen\OneDrive\Bureau\over power bots\newlibrarieslearning\record.py", line 38, in start
    vc.start_recording(
  File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\voice_client.py", line 734, in start_recording 
    raise RecordingException("Must provide a Sink object.")
discord.sinks.errors.RecordingException: Must provide a Sink object.

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

Traceback (most recent call last):
  File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RecordingException: Must provide a Sink object.```
#

@heavy sky

heavy sky
#

Just as the error says, you need to provide a sink object to start_recording(). Instead of just passing sink, you can pass discord.sinks.WaveSink

#

Also, take a look at the audio receiving example:

rugged lodgeBOT
#

Here's the audio recording example.

heavy sky
#

To use MP3 you can also use discord.sinks.MP3Sink

plush escarp
#

hey I have a button that should send a paginator. The button is created in side a class. I get TypeError: Paginator.send() missing 1 required positional argument: 'ctx' I was wondering what context I need to put as an argument

glossy latch
bitter meteor
#
class GameView(discord.ui.View):
    def __init__(self,idd,b):
        super().__init__()
        self.value = None
        self.id = int(idd)
        
    @discord.ui.button(label="1", row=0, style=discord.ButtonStyle.green)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        if interaction.user.id == self.id:
            self.value = True
            self.stop()
            
    @discord.ui.button(label="2", row=0, style=discord.ButtonStyle.danger)
    async def button2(self, select: discord.ui.Select, interaction: discord.Interaction):
        if interaction.user.id == self.id:
            self.value = False
            self.stop()```
i have this view what is the line of code that disables specific button ?
heavy sky
grim estuary
#

How to send second message via interaction.response.send_message?

heavy sky
grim estuary
valid panther
#
    owner = SlashCommandGroup(
        name="cowner",
        description="Commands owner",
        checks=[
            commands.is_owner().predicate
        ]
    )

If I create this group of commands only the owner of the bot will be able to use them, but will the command be visible to all users?

grim estuary
#

How to access the everyone role?

lofty parcel
#

.rtfm Guild.public_role

sly karmaBOT
#

Target not found, try again and make sure to check your spelling.

lofty parcel
#

Close enough

lofty parcel
sly karmaBOT
grim estuary
#

Thank you

plush escarp
#

what context do I need to put in Paginator.send

#

it doesnt let me send it without context

lofty parcel
plush escarp
lofty parcel
#

Then the interaction

#

And you'd use paginator.respond

round heart
#

Anyone using mypy? I've never used it before, but the primary author on a bot we're working on is, and seeing a bunch of weird errors about discord.Option for slash commands:

use discord.Option[...] instead of discord.Option(...)

For this reason, he wants to move to decorators for slash commands ... which I think are super-unreadable, so I'm trying to avoid it 🙂 -- Anyone know why mypy is whining about instantiating a the Option class? Why would it suggest braces?

little cobalt
round heart
#

decorators for function calls are much more difficult to read for me, so I'm hoping to keep function definition if possible.

#

But anyway, still trying to understand why mypy would complain about instantiating a class.

little cobalt
#

@fleet cedar havent you tried mypy?

plush escarp
#

is it possible to send a modal through a modal?

#

like when one modal is completed it opens a new one

fleet cedar
fickle salmon
stray pasture
#

I am trying to send a file but I get a errors about embeds. I am confuse

#
Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "D:\Documents\bot discord\timed_role\timeRoleBot.py", line 164, in on_application_command_error
    await handler.handle()
  File "D:\Documents\bot discord\timed_role\exceptions\ExceptionHandler.py", line 48, in handle
    return await self._handle_unknown()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role\exceptions\ExceptionHandler.py", line 30, in _handle_unknown
    await self.ctx.respond(embed=embed)
  File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\commands\context.py", line 286, in respond
    return await self.followup.send(*args, **kwargs)  # self.send_followup
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\webhook\async_.py", line 1745, in send
    data = await adapter.execute_webhook(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\webhook\async_.py", line 221, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.description: Must be 4096 or fewer in length.
shell radish
#

did you save?

#

full traceback is also appreciated

stray pasture
shell radish
#

yeah look here

  File "D:\Documents\bot discord\timed_role\exceptions\ExceptionHandler.py", line 30, in _handle_unknown
    await self.ctx.respond(embed=embed)
#

it's there where the error occurs

stray pasture
#

ooh I see, but why is it making a error in the first place ?

#

do I send the file the wrong way ?

#

the real error:

Application Command raised an exception: OSError: [Errno 22] Invalid argument: '{\n  "application": null,\n  "application_fee_percent": null,\n  "automatic_tax": {\n    "enabled": false\n  },\n  "billing_cycle_anchor": 1690915497,\n  "billing_thresholds": null,\n  "cancel_at": null,\n  "cancel_at_period_end": false,\n  "canceled_at": 1690947594,\n  "cancellation_details": {\n    "comment": null,\n ...

shell radish
stray pasture
#

oooh I see, I should transform my str into a bufferIO

#

thank you !

#

I though str was consider a buffer in python 😅

shell radish
#

nah

#

it's supposed to be binary-like

stray pasture
#

perfect I just used io.StringIO() and it worked ! Thank you ! 🤩

grim estuary
#
Ignoring exception in command post:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 178, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/evelone.py", line 52, in post
    message = discord.Embed(title="Do you want to buy a product?", image="/home/container/buy.jpg")
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Embed.init() got an unexpected keyword argument 'image'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.init() got an unexpected keyword argument 'image'

I put my bot on the host. The host does not see the images that are uploaded to it. The path to the image is exact, the name is exact

lofty parcel
#

The error isn't even telling you about not finding the path

#

.rtfm Embed.set_image

sly karmaBOT
grim estuary
lofty parcel
#

?tag localfile

grim estuary
#

Path: /home/container/buy.jpg

lofty parcel
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
limber wagonBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
grim estuary
# lofty parcel ```py f = discord.File("some_file_path", filename="image.png") e = discord.Embed...
Ignoring exception in command post:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 178, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/evelone.py", line 56, in post
    file = discord.File("container", filename="buy.jpg")
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/file.py", line 99, in init
    self.fp = open(fp, "rb")
              ^^^^^^^^^^^^^^
IsADirectoryError: [Errno 21] Is a directory: 'container'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IsADirectoryError: [Errno 21] Is a directory: 'container'```
grim estuary
grim estuary
daring valve
# grim estuary Whyyy

You use somewhere tabs and somewhere 4 spaces
Use ide to automatically convert tabs to spaces or spaces to tabs
It's python thing and tbh I don't know why it works like that

#

¯_(ツ)_/¯

#

probably parser thing

grim estuary
#

This is to check every new line

upper hearth
#

any way to see how many boosts a user has given?

#

or can i only check for booster role to see if they've boosted at all

fiery stratus
#

hey so i'm doing UI stuff and am getting this error (see attached 1). This error comes from this statement (see attached 2).

the thing is my PollSelect class inherits from discord.ui.View, which has a children attribute, and self.select inherits fromdiscord.ui.Item, so I don't understand why this is erroring.

fiery stratus
#

oh yeah sorry

shell radish
#

you never initiated the parent class

fiery stratus
#

🤦‍♂️

#

sorry abt that

shell radish
#

no worries

fiery stratus
#

its been a while since i've programmed in an oop language

wary wyvern
#

Is there a way for deselecting the selected item in select menus?

shell radish
# wary wyvern Is there a way for deselecting the selected item in select menus?
wary wyvern
shell radish
#

iirc

wary wyvern
#

It's not selected by default

#

I mean like in the callback of the select menu I want to reset it somehow

shell radish
#

Not by default, even by the user

wary wyvern
#

Ok

shell radish
#

but if that's not true, you can "clone" the select menu and send that instead

drifting turtle
#

i still dont know why there isn't something like that. setting things up during an on_ready event call is dangerous since it is not guaranteed to be called once

shell radish
round heart
#

Isn't there a helper to resolve/extract mentionables in a string (so that they will simply print their string equivalents)? Or did I make that up in my head?

shell radish
round heart
#

There also seems to be raw_*_mentions(for users, channels, and roles).

round heart
shell radish
#

try checking the source code

#

and use that as a reference

round heart
#

Yeah. Just didn't want to reinvent the wheel (e.g. copy code) if I didn't have to, but will figure something out

round heart
#

Came up with this, but unsure if I'm overcomplicating

def clean_content(ctx: discord.ApplicationContext, content: str) -> str:
    channel_mentions = re.finditer(discord_channel_re, content)
    for m in channel_mentions:
        if channel := ctx.bot.get_channel(int(m.group(1))):
            content = content.replace(m.group(0), f"#{channel.name}")
        else:
            content = content.replace(m.group(0), f"#{m.group(1)}")

    user_mentions = re.finditer(discord_id_re, content)
    for m in user_mentions:
        if user := ctx.bot.get_user(int(m.group(1))):
            content = content.replace(m.group(0), user.name)
        else:
            content = content.replace(m.group(0), "Unknown User")

    if ctx.guild:
        role_mentions = re.finditer(discord_role_re, content)
        for m in role_mentions:
            if role := ctx.guild.get_role(int(m.group(1))):
                content = content.replace(m.group(0), role.name)
            else:
                content = content.replace(m.group(0), "Unknown Role")
    
    return content
round heart
#

(...meh, it can't seem to get the channel by id)

#

Ah, I guess related to the issue of it not knowing what guild it's in.

shell radish
#

do you have guild intents?

round heart
#

Oh! The guild thing is fixed - it needed to be a "bot", not just have application commands. Once I added send message ability, it now knows where it is.

#

Initially, it simply had application.commands because that's really all it needed. I still expected it to know where invocation was coming from, though

shell radish
#

yeah, discord only gives you guild_id

subtle moth
brave ore
#

why this demo can't display font color?

fickle salmon
#

Embed color isn't the font color

brave ore
#

how can I add font-color like this?

fickle salmon
#

That's just a link

civic fractal
#

why does this pop up

#

slash commands options field

brave ore
fickle salmon
oak musk
#

Hi guys simple question are discord bots able to execute slash commands on other bots?

plush escarp
#

hey for some reason I don't have persistent view even tho I gave the button a custom id and set the view timeout to none

lost ocean
#

yoo

#

im working on modals

#

and for some reason even though they take in a response and save data from the modal,

#

the modal doesn't close and shoes something went wrong

#

everythings fine tho it just shows something went wrongf.

lofty parcel
rugged lodgeBOT
#

Here's the persistent example.

lofty parcel
lost ocean
#

says it has already been responded to..

#

are you talking about

#

interaction.response.send_message ?

lofty parcel
#

Yes

lost ocean
#

yea it shows an error

lofty parcel
#

Show code

lost ocean
#

because

#

i respond to it before

#
    @commands.guild_only()
    @commands.slash_command(
        name='createprofile',
        description='Create a profile for Team Revenant server',
        usage='/createprofile'
    )
    async def createprofile(self, ctx: ApplicationContext):
        await ctx.defer()

        data = retrieve_profile_data()

        if str(ctx.author.id) in data:
            return await ctx.respond("You already have a profile!\n`/profile` to view it.")
        
        class ProfileButtonView(discord.ui.View):
            @discord.ui.button(label="Create Profile")
            async def button_callback(self, button, interaction):
                await interaction.response.send_modal(ProfileModal(title="Profile Form", timeout=15))
                button.disabled = True
                await interaction.response.edit_message(view=self)

        await ctx.respond("Please answer the modal within 15s", view=ProfileButtonView(timeout=15))```
plush escarp
lofty parcel
#

You should use interaction.edit_original_response

lost ocean
#

ah

lofty parcel
lost ocean
#

it triggers me too

#

but i want to get the basic down first so

lost ocean
#

like its submitted

#

data has been filled in the file

#

but it still shows this

lofty parcel
#

Modal code

little cobalt
lost ocean
# lofty parcel Modal code
class ProfileModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="Current Valorant Rank"))
        self.add_item(discord.ui.InputText(label="Peak Valorant Rank"))

    async def callback(self, interaction: discord.Interaction):
        data = {
            interaction.user.id: {
                "curr_rank": str(self.children[0].value),
                "peak_rank": str(self.children[1].value)
            }
        }

        with open('data/profile.json', 'w') as f:
            json.dump(data, f, indent=4)

        embed = discord.Embed(title=f"Profile Made - {interaction.user.name}", colour=discord.Colour.from_rgb(106, 0, 255))
        embed.add_field(name="Current Valorant Rank", value=self.children[0].value)
        embed.add_field(name="Peak Valorant Rank", value=self.children[1].value)
        embed.add_field(name="Top Role", value=f"{interaction.user.top_role.name}")
        embed.set_thumbnail(url=interaction.user.avatar)
        await interaction.channel.send(embed=embed)```
lost ocean
#

the button wont be disabled

#

and wont it clash with my button response

lofty parcel
little cobalt
#

You are not responding the modal

lofty parcel
#

Interaction.response.send_message

little cobalt
#

Or interaction.response.edit_message

lost ocean
#

idk i tried it before

#

thanks tho

plush escarp
#

I get the following error when I try to click a button that sends a paginator:

  File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\ext\pages\pagination.py", line 1176, in respond
    msg = await interaction.response.send_message(
  File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\interactions.py", line 904, in send_message
    await self._locked_response(
  File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\interactions.py", line 1198, in _locked_response
    await coro
  File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\webhook\async_.py", line 220, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction ```
plush escarp
#

I saw that response has to be up to 3 seconds, and follow up can be up to 15 minutes. how do I follow up with a paginator?

fleet cedar
#

you could do await paginator.respond(...)

thats basic python oop yk

round heart
#

Can Converters be used with slash command options?

fleet cedar
fleet cedar
#

pass the converter parameter (undocumented iirc)

round heart
#

Oooh. So you wouldn’t change the type, just add the kwarg. Thanks

fleet cedar
#

np

#

or wait

#

you probrably pass the converter as the type

#

💀

#

let me check

#

ok yes you pass the converter to the input type

#

sorry

#

@round heart ^

round heart
#

Hah okay, that makes it more consistent. Appreciate the follow up

grim estuary
#

Hello. I understand that cooldown is best done through timestamp?

hybrid fossil
#

Hi!
Question, how do I get button and interaction in the callback?

class Button(discord.ui.Button):
    def __init__(self):

        super().__init__(
            label="-",
            style=discord.ButtonStyle.red,
            custom_id="callButton",
            row=1
        )

    async def callback(self, interaction):
        ...
shell radish
#

self is the button

hybrid fossil
lofty parcel
#

And that's why learning OOP is important kids

hybrid fossil
fleet cedar
shell radish
#

so you're using types without type-hinting. great

fleet cedar
#

Self doesn't need to be typehinted tho

grim estuary
fleet cedar
#

You can also reuse the built in stuff for buttons with some setup

hybrid fossil
#

In all your examples, the callback has the button parameter. I separate my buttons from my views and I've had this problem for a while. I made a mistake but I'm trying to figure out how to fix it.

fleet cedar
#

Only if you use a db as an intermediary, timestamp is useful

shell radish
#

in your case

hybrid fossil
#

ahhh!

#

Self in the other case is the view, I'm stupid.

fleet cedar
#

When subclassing Button, self is the button

When subclassing View, self is the view 🙃

shell radish
#

hi, stupid, I'm squid

hybrid fossil
shell radish
#

you have to edit the message with the updated view after disabling it

fleet cedar
#

Try interaction.response.edit_message

grim estuary
fleet cedar
grim estuary
#

I will try, thank you

grim estuary
#

How can I check that the entered member is a member? Should I resort to throwing a command error or using try-except?

grim estuary
grim estuary
# lofty parcel Just return a response?

I need to take into account several options for incorrect answers:

  • Whether the entered data is a member
  • Is there a member on the server
  • Is the member a bot (this is what i decided)

Is there any way to check the first one without resorting to error "trapping"?

lofty parcel
#

Like I said, just return a response

#

You're in a function

#

The return keyword doesn't execute anything below it

grim estuary
#

I'm sorry, but I didn't understand you. How can I check, for example, "aaaaa" and "deodjdn" are not users without catching errors?

lofty parcel
grim estuary
#

Is catching errors a normal practice?

lofty parcel
#

Yes... you should catch errors

#

You have to tell the user something went wrong. Or catch appropriate errors to handle the behaviour

grim estuary
#

I've always tried to avoid using error, considering all possible variations in the code but when I have to work with library models, I don't understand how to deal with the problem

#

🤷

plush escarp
#

I have a question that is for pymongo and not pycord

how do I find the last inserted document? I tried

client[str(interaction.guild.id)].address_profile.find_one().sort({"_id": pymongo.DESCENDING})``` and

```py
client[str(interaction.guild.id)].address_profile.find_one().sort({"_id": -1})```
 but both dont seem to work and I get the error :

```TypeError: if no direction is specified, key_or_list must be an instance of list```
fickle salmon
grim estuary
upper spade
#

is there anyway to create an invite to a voice channel@

#

in a way that like

#

bypasses permissions

#

so if someone doesnt have view & connect

#

but use the invite

#

they should br able to join

#

i thought this was already the case but apparently not

fickle salmon
#

There's a new feature that lets people join voice without being in the server but I'm pretty sure it has to be public

upper spade
#

yeah the guest thing

#

welp dreams ruined

fickle salmon
#

I don't believe you can bypass permissions with an invite, that wouldn't really make sense

#

You could have them join a public channel and have the bot move them to a private one

upper spade
#

it would tho

upper spade
fickle salmon
#

You can do the whole "create your own VC" thing

upper spade
#

i already got that part its just that when testin w friends i realised they cant actually join

fringe drum
#

is there a way to know if the command completed is ephemeral with on_command_completion?

pine yacht
#

Is there a way to access/specify the data type that a converter returns? Would be useful for static type-checking, and making sure I'm getting what I expect.

grim estuary
#

How to send a response message if the command is in cooldown?

little cobalt
shell radish
shell radish
fringe drum
pine yacht
#

What I'm working with:

class Context(discord.ApplicationContext):
    bot: "Bot"
    # --snip--
    async def text_input(
        self,
        body: str,
        title: Optional[str] = None,
        embed_style: EmbedStyle = EmbedStyle.QUESTION,
        converter: Optional[discord.ext.commands.Converter] = None,
    ):
        #--snip--
        coro = self.bot.wait_for(
            "message",
            check=lambda message: message.author == self.author
            and message.channel == self.channel,
        )
        await self.respond(embed=embed, view=CancelButtonView(coro))
        msg = await coro
        return converter.convert(ctx=self, argument=msg.content) if converter is not None else msg.content # type: ignore [arg-type]
heavy sky
pine yacht
#

Can you override the checks for a group command, specifically to remove checks defined in the parent group? For example:

class ModCog(Cog):
    root = SlashCommandGroup('mod', checks=[required_staff_level(StaffLevel.mod)])
    @root.command()
    async def warn(self, ctx, target: Member):
        pass # Only mods should be able to run this command
    @root.command() # ???
    async def my_warnings(self, ctx):
        pass # Anyone should be able to run this command
fleet cedar
pine yacht
#

OK. Guess I can just make my_warnings its own cmd...

fleet cedar
#

Yea haha

sullen crane
#

When do i deferenciate between use ctx and interaction in a cog

#

because sometimes using ctx is fine sometimes it isnt

lofty parcel
#

ctx for commands

#

Interaction for ui

sullen crane
#

ohh

#

ok

#

thanks

brave ore
#

hi, how to set a error handler to all select_callback?

placid sphinx
#

Hi there, why should I choose Pycord over alternatives like discord.py or nextcord?

shell radish
brave ore
#

Usually, there shouldn't be much difference in terms of usage for these three frameworks.

atomic fern
#

how to add description to bridge slash command option?

fleet cedar
placid sphinx
little cobalt
#

But may was saying after they switched from dpy to pycord, that pycord is way better and faster

placid sphinx
#

I'm asking about maintainability, which isn't something I can test myself 🙂

little cobalt
#

Pycord is currently kinda "finishes" I would say

fleet cedar
placid sphinx
hollow loom
#

Do I need to run kill 1 while working on Replit at any point? (aka restart cloud PC)

grim estuary
#
Ignoring exception in command reputation:
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\user\Desktop\Projects\Evelone\evelone.py", line 365, in reputation
    await reputation.reset_cooldown(ctx=ctx)
TypeError: object NoneType can't be used in 'await' expression

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

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in 'await' expression

Hello. I assigned a specific cooldown to the commands, but made sure that it was skipped in case of incorrect input. Everything works, only an error appears in the console.

The line await badreputation.reset_cooldown(ctx=ctx) works without errors in @client.command() but not in @badreputation.error

deft kestrel
#

Does anyone know why my welcome message is being sent multiple times instead of just once?
here is the code :

@client.event
async def on_member_join(member):
    welcome = client.get_channel(...)
    
    if (member.guild.id == ...):
        
        embed=discord.Embed(title="{}".format(member.guild.name), description="{}".format(member.mention), color=0xffffff)
        embed.set_image(url="...")
        embed.set_footer(text="{}".format(member.guild.name), icon_url="...")
        
        button = Button(label="...", url="...", emoji="📃")
        
        view = View()
        view.add_item(button)
        
        await welcome.send("|| {} ||".format(member.mention) ,embed=embed, view=view)
    else:
        pass
atomic fern
#

that run the bot

little cobalt
#

Also its getting triggert at every server, I had the same issue at the beginning

deft kestrel
grim estuary
#

I want the bot to respond again to the buttons after the restart, which were available before the restart, but the class has arguments, so I don't know what to do

client.add_view(Name()) work if the class doesn't require arguments

grim estuary
#

What is it...

shell radish
grim estuary
upper hearth
#
    async for member in ctx.guild.fetch_members(limit=None):
        print(str(member.activity))```
why is this always `None`
little cobalt
upper hearth
#

yes

#

it works if i do ctx.author.activity aswell

little cobalt
#

Can you show it?

upper hearth
little cobalt
#

also at your bot?

upper hearth
#

wdym

little cobalt
#

where you define the bot

upper hearth
little cobalt
#

discord.Bot(intents=intents)

#

ok

#

weird

#

I get my activity

#

do you have it in a cog?

upper hearth
#

no

upper hearth
little cobalt
#

member.activity

upper hearth
#

oh

#

yeah idk why it wont work when i want to get everyones activities

little cobalt
#
@client.slash_command()
async def test(ctx: discord.ApplicationContext, member: discord.Member):
    await ctx.respond(member.activity)
#

I was trying is like this ^

upper hearth
#

ill try that maybe its something else going wrong

#

cannot send an empty message

#

but i have a status

little cobalt
upper hearth
#

if i did ctx.author.activity it sends my status rn

#

but using the command u sent

#

it says cant send an empty message

#

it should send sdfdss

#

so yes

#

sort of

little cobalt
#

I got this

upper hearth
#

lemme open something and see if it wants that

little cobalt
upper hearth
#

wdym

#

my custom status

#

i set calculator as my game and now it shows me the status?

#

but why doesnt it show me when they dont have a game

little cobalt
upper hearth
#

what do you mean

#

i want that

#

status

little cobalt
#

status would be something like "dnd"

#

or "online"

lofty parcel
#

Custom statuses are activities

upper hearth
#

yeah

lofty parcel
#

.rtfm activity.Custom

sly karmaBOT
#

Target not found, try again and make sure to check your spelling.

upper hearth
#

i want the custom status

little cobalt
#

what is with the raw one?

upper hearth
#

just lots of nones

lofty parcel
#

Are you sure discord.Activity has a to str method?..

upper hearth
#

because

#

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

lofty parcel
#

.rtfm Member.activity

sly karmaBOT
lofty parcel
#

And member.activities?

little cobalt
upper hearth
#

lots of ()

lofty parcel
#

At this point, it's an intents issue

#

Works perfectly fine for me

upper hearth
#

it also lets me use member.id but idk if you need intents for that

upper hearth
#

ah fixed it, apparently ctx.guild.fetch_members(limit=None) doesnt give activity data but ctx.guild.members does

bitter meteor
#
class GameView(discord.ui.View):
    def __init__(self,idd,board):
        super().__init__()
        self.value = None
        self.id = int(idd)
        self.board = board
        # [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
        
        emojify = []
        toggles = []
        
        for a in range(len(self.board)):
            for b in range(len(self.board[a])):
                curr = self.board[a][b]
                if not curr == " ":
                    toggles.append(False)
                    
                if curr == "X":
                    emojify.append(":x:")
                elif curr == "O":
                    emojify.append(":o:")
                else:
                    emojify.append(":white_large_square:")


                
                
        
    @discord.ui.button(emoji=emojify[0], row=0, style=discord.ButtonStyle.green)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        if interaction.user.id == self.id:
            self.value = True
            self.stop()```
code, error in `discord.ui.button` line:
```NameError: name 'emojify' is not defined```
shell radish
#

yeah because it's defined at the __init__ scope

bitter meteor
#

so what do i do?

#

oh i see now

#

i made one tab more

#

now it works, thank for pointing out

bitter meteor
#
class GameView(discord.ui.View):
    def __init__(self,idd,board):
        super().__init__()
        self.value = None
        self.id = int(idd)
        self.board = board
        # [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
        
    
    emojify = []
    toggles = []
    
    for a in range(len(self.board)):
        for b in range(len(self.board[a])):
            curr = self.board[a][b]
            if not curr == " ":
                toggles.append(False)
                
            if curr == "X":
                emojify.append(":x:")
            elif curr == "O":
                emojify.append(":o:")
            else:
                emojify.append(":white_large_square:")


            
    @discord.ui.button(emoji=emojify[0], row=0, style=discord.ButtonStyle.green)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        if interaction.user.id == self.id:
            self.value = True
            self.stop()```
but now how do i acces the data?
shell radish
#

what data

bitter meteor
#

board

upper hearth
#
@bot.command()
async def test2(ctx, id:int):
    guild = await bot.fetch_guild(id)
    print(guild.members)``` 
whys this giving me [] if i have the members intent
bitter meteor
#

what id do you give?

upper hearth
#

the id of my server

daring valve
upper hearth
#

yes

#

im doing the command in the server

daring valve
#

Do you have intents in your code and in discord devs portal?

upper hearth
#

yes

#

all of them

daring valve
#

In devs portal and passed as argument to your bot class?

shell radish
upper hearth
#

oh so theres no way to get it?

#

the thing im trying to make ive seen other bots do it so idk how they do it

grim estuary
#

Is it normal practice to make a regular command and its copy in slash commands?

upper hearth
#

isnt there a whole thing for that

#

like bridge commands

rugged lodgeBOT
#

Here's the bridge commands example.

fleet cedar
grim estuary
upper hearth
#

idk how they work i just know they exist

rugged lodgeBOT
#

Here's the bridge commands example.

fleet cedar
#

Single cmd that is both, a slash cmd and prefix cmd

daring grove
#

I have this as a command, instead of returning it like this how would i just get the name of the role

#

this is my current code

shell radish
#
role_string = ""
for role in roles:
  role_string += role.name
await ctx.respond(role_string)

You can do this in one line, but I did it this way for clarity

upper hearth
#

wouldnt that put them in one long line with no spaces

shell radish
upper hearth
#

oh ok

fleet cedar
daring grove
#

thank you though!

bitter meteor
#
class GameView(discord.ui.View):
    def __init__(self,idd,board):
        super().__init__()
        self.value = None
        self.id = int(idd)
        self.board = board
        # [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
        
    
    emojify = []
    toggles = []
    
    for a in range(len(self.board)):
        for b in range(len(self.board[a])):
            curr = self.board[a][b]
            if not curr == " ":
                toggles.append(False)
                
            if curr == "X":
                emojify.append(":x:")
            elif curr == "O":
                emojify.append(":o:")
            else:
                emojify.append(":white_large_square:")


            
    @discord.ui.button(emoji=emojify[0], row=0, style=discord.ButtonStyle.green)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        if interaction.user.id == self.id:
            self.value = True
            self.stop()```

how do i get board in the middle of code
shell radish
#

probably an xy question. I think there is a better way to go about achieving this

#

?tag xy

limber wagonBOT
#

An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.

You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.

upper hearth
#
@bot.event
async def on_presence_update(before, after):
    print(after.status)```
why is this saying `idle` when im going offline
#

is that discord being weird

little cobalt
#

It can take some time to change

upper hearth
#

?

#

it triggers when it changes no?

#

if i go online -> offline it says i went online -> idle

little cobalt
#

Weird

grim estuary
#

Is it possible to send modal via command with prefix?

fleet cedar
shell radish
grim estuary
#

Thank you

little cobalt
rugged lodgeBOT
#

Here's the slash basic example.

little cobalt
#

@grim estuary check this out ^

grim estuary
#
  • leaderboard
  • by experience
  • by level
  • ...
rugged lodgeBOT
#

Here's the slash options example.

fleet cedar
#

@grim estuary ^

grim estuary
#

Thanks

#
Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-4d58a3cf920547406e31fb5a0f3ba5a2' coro=<Profile.on_timeout() done, defined at C:\Users\user\Desktop\Projects \Evelone\evelone.py:697> exception=AttributeError("'NoneType' object has no attribute 'edit'")>
Traceback (most recent call last):
  File "C:\Users\user\Desktop\Projects\Evelone\evelone.py", line 701, in on_timeout
    await self.message.edit(view=self)
AttributeError: 'NoneType' object has no attribute 'edit'```

I don't understand how to access the message without using `message` inside `View`
fickle salmon
#

You can pass in the message when you make the view

grim estuary
#

It started showing up after I changed the command to slash-command

hazy turret
#

Hello,

I would like to display only certain roles in an autocomplete (or is there also Choice?).
For this I have a list with the role ID's.
Now I want to check which role the user already has and then only all roles above this role should be displayed for him.
If he owns role 2, only all roles from role 3 should be displayed for him and be selectable.

Somehow I can't find a solution.
Here is my approach, maybe someone has an idea how I can implement this well?

Roles = [
    ROLE_1_ID,
    ROLE_2_ID,
    ROLE_3_ID,
    ROLE_4_ID,
    ROLE_5_ID,
    ROLE_6_ID,
]

    async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
        guild = self.bot.get_guild(GUILD_ID)
        # Liste der verfügbaren Rollen in aufsteigender Reihenfolge
        roles = [guild.get_role(role_id) for role_id in Roles]
        print(roles)


    @slash_command(
        name="promote_me",
        description="Promote",
    )
    @option(
        "role",
        description="Select",
        autocomplete=select_role_autocomplete,
        required=True,
    )
    async def promote_me(self, ctx: discord.ApplicationContext, role: discord.Role):
fleet cedar
#

Which pycord version are you using?

#

The library will handle view.message for you

grim estuary
fickle salmon
#

discord.__version__

grim estuary
hazy turret
upper hearth
#
@bot.event
async def on_presence_update(before, after):
    print(after.status) # outputs idle
    member = await after.guild.fetch_member(int(after.id))
    print(member.status) # outputs offline```
im still confused if this is a bug or not but if i go on invisible/offline, `after.status` outputs `idle` which is wrong clearly
do i just have to do it the other way or am i doing something wrong
torpid ivy
#

Does it still take an amount of time for slash commands to become available or should they be available immediately?

upper hearth
#

you mean to show up when you type /

#

?

fickle salmon
#

I think the SLA is still an hour but they can show up faster

hazy turret
#

What am I doing wrong so that the appropriate roles are displayed in the autocomplete?


    async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
        guild = self.bot.get_guild(GUILD_ID)
        # Liste der verfügbaren Rollen in aufsteigender Reihenfolge
        roles = [guild.get_role(role_id) for role_id in Roles]
        print(roles)

        filtered_roles = []
        found_user_role = False

        for role in roles:
            if role in ctx.interaction.user.roles:
                found_user_role = True

            if found_user_role:
                filtered_roles.append(role)

        # Erstelle die Liste der Rollen für die Autocomplete-Antwort
        return [
            role for role in roles if role.name.lower().startswith(ctx.value.lower())
        ]

    @slash_command(
        name="promoteme",
        description="Promote.",
    )
    @option(
        name="role",
        description="Rolle",
        autocomplete=select_role_autocomplete,
        required=True,
    )
    async def promote_me(self, ctx: discord.ApplicationContext, role: discord.Role):```
torpid ivy
#

the file with the code I was editing was in a different spot than the code i was running, lol. I was getting frustrated wondering why nothing was changing/working right!

fleet cedar
hazy turret
fleet cedar
#

You can remove it and do return [role for role in roles if role in user.roles and role.name.lower()...]

fleet cedar
#

So it doesn't fire every time

shell radish
hazy turret
# fleet cedar Discord caches the autocomplete value for some reason

I did it now but I still see all roles from the server.

    async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
        guild = self.bot.get_guild(GUILD_ID)
        user = ctx.interaction.user
        # Liste der verfügbaren Rollen in aufsteigender Reihenfolge
        roles = [guild.get_role(role_id) for role_id in Roles]
        print(roles)

        # Erstelle die Liste der Rollen für die Autocomplete-Antwort
        return [role for role in roles if role in user.roles and role.name.lower().startswith(ctx.value.lower())]```
#

It is correct that I specify here that it is about roles or is the error here?

async def promote_me(self, ctx: discord.ApplicationContext, role: discord.Role):```
fickle salmon
torpid ivy
#

i copied it to two places last night and for some reason opened one in vsc and the other in conda lol

#

now comes the fun part of converting my code from text commands to slash commands. so many places i have to replace "ctx.message" properly

#

wasn't there some secondary decorator you can use along with @bot.command() to limit the channels/servers the command shows up in (or can be used in)

fickle salmon
#

guild_ids

#

As an arg

torpid ivy
#

ooh nice, easy enough

fickle salmon
#

There's also permissions you can limit it to, but I don't think there's a decorator for channels

torpid ivy
#

hmmm

#

i WAS running a block like this

#

i can probably just include that for the channel thing

#

slash command ctx still use "author"? like if i wanna pull the nick/id of the user it'd be ctx.author.id and ctx.author.display_name?

lofty parcel
#

Yes

torpid ivy
#

nice

#

so most of this is probably just going to be me deleting .message from a bunch of strings :D

lofty parcel
#

Search and replace

torpid ivy
#

naw i'm doing it by hand so i dont miss oddball cases

#

i prolly should rewrite this and use cogs or something, since that seems to be the organizational structure provided lol

#

but like ctx.channel.send(embed) will still work, right

#

Sorry I'm just trying to double check a few things as I go to make sure its gonna work as expected (or not)

fickle salmon
#

You should definitely use cogs

#

Even if you throw everything in one cog

#

Having it in a class, with self, and instance variables instead of using global... Highly recommend

upper hearth
#

after.status says idle instead of offline for only certain people why is it being weird.

#

i thought it was everyone but ive seen it say offline for 2 pepole now

lofty parcel
#

Ask discord

wind crypt
#

probably a dumb question but im new to coding n idk why this error is popping up

wind crypt
little cobalt
#

Its just basic

fickle salmon
#

You're responding to an interaction, not replying to a message

torpid ivy
#

I dont fully understand cogs so i gotta figure out what they are even lol

#

right now my bot is basically a list of commands and then also functions that create embeds, and then a few files of settings/functions that get imported into the main file

#

does use a bunch of global vars though. like, it's a game with a timer, and I abuse dictionaries for everything

#

like game_is_active[server_id] = True/False

fickle salmon
#

Love dictionary abuse

torpid ivy
#

i use dicts for everything

#

they are beautiful

fickle salmon
#

💯

#

At least until you want to actually start persisting state

torpid ivy
#

and yeah, def lol

#

this thing uses tinydb for its persistent score database

#

the other stuff idc about persistence

fickle salmon
#

Never heard of tinydb

torpid ivy
#

its just a db format

#

i picked it cuz its what google told me lol

#

works fine, its just a list of dicts more or less

#

soo, ofc i like it

little cobalt
daring grove
#

how might i update an embed with new values on a command?

#

and in the usage of a different command, I want those values such as budget and players on the team to update

#

im trying to figure out how to edit the message effectively without rewriting the whole list of embeds every time I want to update

humble condor
#

Anyone have a code to get the guilds number of active members

Like this:

fleet cedar
#

Autocomplete can only be string type

#

You should return a list of discord.SelectOption with name as role name and value as role id

grim estuary
#

Hello. Is it possible to write a separate line of code if the participant opened the modal but canceled the submission?

hazy turret
hazy turret
south sinew
#

discord.ext.commands.Bot not automatically sync slash commands
Why?

@bot.command(description="Sends the bot's latency.")  
async def ping(ctx: c):
    await ctx.send(str(bot.latency))```
fleet cedar
fleet cedar
little cobalt
fleet cedar
#

Use @bot.slash_command(...)

fleet cedar
daring grove
#

is there any better way to edit an embed rather than fetching the id of the message and editing it like that

#

its really slow

#

i have a command which sends multiple embeds
and i have another command which edits them but it fetches the embed message by id first

#

this usually has like a 5 second delay between the edit and the command

#

any faster way to do this?

grim estuary
south sinew
limber wagonBOT
#

dynoError No tag clients found.

little cobalt
#

?tag client

limber wagonBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
little cobalt
#

@south sinew ^

daring grove
#

is there a faster way of editing a message than getting it by id and editing it?

south sinew
#

I had to sleep that night, I was so confused

#

Thanks, guys

daring grove
#

is there a more efficient way?

south sinew
#

My discord.Bot does not see message.content in the on_message event. For this reason I used Commands.Bot

hazy turret
# fleet cedar Input type should be str

If I do it this way I get an error

    async def select_role_autocomplete(self, ctx: discord.ApplicationContext):

        return [{"name": role.name, "value": role.id} for role in filtered_roles]


    async def promote_me(
        self,
        ctx: discord.ApplicationContext,
        rolle: Option(str, autocomplete=select_role_autocomplete),
    ):```
raise HTTPException(response, data)

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body```

red pagoda
#

Is it possible to select multiple channels option?

south sinew
#

Why discord.Bot does not see message.content in the on_message event?

red pagoda
#

Show code

south sinew
#

@bot.event
async def on_message(message: discord.Message):
    print(message.content)
    if message.author.bot:
        return
    await message.channel.send("Hello!")```
south sinew
#

and content is empty

red pagoda
grim estuary
south sinew
#

Just a minute ago I was doing the same thing and it wasn't working for me. Thanks again - that solved all my problems 😁

daring grove
#

could anyone help me with some message editing?

#

when i do a command, i want to edit embeds sent from a previuos command
currently i fetch the embed message by id but this poses a 5ish second delay between the command and the edit of the embed

grim estuary
#
@client.slash_command(description="description")
@commands.cooldown(1, 86400)

Using this, cooldown is one for all. How to issue an individual cooldown?

bitter meteor
#
@commands.cooldown(1, 2, commands.BucketType.member)``` try this?
#
class GameView(discord.ui.View):
    def __init__(self,data):  # get
        super().__init__()
        self.value = data
        
    
    data = data + ""  # refactor


    @discord.ui.button(label=self.data, row=0, style=discord.ButtonStyle.green)   # acces
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        if interaction.user.id == self.id:
            self.value = True
            self.stop()```
I have this view, and how do i get, refactor and use variable in the `@discord.ui.button()` line.
daring grove
sly karmaBOT
# daring grove is there a faster way of editing a message than getting it by id and editing it?

Partial Objects

These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.

Methods which can be used on them are -

Example Usage:

async def star_message(channel_id: int, message_id: int):

    # Get Partial Messageable object. Docs-
    # https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
    partial_channel = bot.get_partial_messageable(channel_id)

    # Get Partial Message. Docs-
    # https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
    partial_message = partial_channel.get_partial_message(message_id)

    # Add a reaction
    await partial_message.add_reaction(":star:")
fleet cedar
#

You just need the message id and channel id

daring grove
#

or at least trying to get it to work

#
updembedLV1 = await ctx.channel.send(embed=updembedLV)

this is in one command

await updembedLV1.edit(embed = updembedLV2)

this is in another command

#

why do i get this error?

name 'updembedLV1' is not defined
fleet cedar
#

Variable scoping

daring grove
#

i tried making it a global var

fleet cedar
#

Bad idea

daring grove
fleet cedar
#

Multiple users could be using your bot, how will you determine which message is for which user?

fleet cedar
fleet cedar
# daring grove wdym

Two people are using the commands, how will you distinguish which message to edit when both of them use command 2

daring grove
#

in the command you have to input a 'team'

#

and based on that team it'll edit the message

fleet cedar
daring grove
#

regardless, im the only one that will be able to use this command

fleet cedar
#

Ah

#

You can use a bot var ig

#

.tag botvar

sly karmaBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

daring grove
#

without it being sent

valid panther
#

is there any way to make the command visible to those with permissions, the only thing I have found is to limit it and show an error message in case they don't have it, @fleet cedar

fleet cedar
fleet cedar
daring grove
#

oh wait nevermind

#

hm okay let me try

rugged lodgeBOT
#

Here's the slash perms example.

daring grove
valid panther
# fleet cedar You can use default_permissions

yes I know, but it is still visible to the users in my case I am using it like this

    @discord.slash_command(name="config", description="Configure the server")
    @discord.default_permissions(
        administrator=True
    )
    async def config(self, ctx):
valid panther
valid panther
#

and why don't you save only the embed content?

daring grove
#

oh because i want to be able to do bot.updembedSN1.edit anywhere

#

what would i do about the 'await' and 'ctx' problem?

valid panther
daring grove
valid panther
#

inside

daring grove
#

like bot.embed.edit?

#

in other functions

daring grove
#

oh

valid panther
daring grove
#

:)

#

would it be ctx.bot.updembedMU1?

valid panther
# daring grove

What you are trying to store is a message impression, you are aware of that, aren't you?

daring grove
#

and im trying to edit that message in a different command

valid panther
#

just want to edit a message?

humble condor
#

Anyone have a code to get the guilds number of active members

daring grove
#

just want to edit that embed

valid panther
#

then save only the Embed object

fleet cedar
fleet cedar
fleet cedar
#

so make sure that is correct

valid panther
#

now I look at it

daring grove
#

nvm

#

i did it

#

i feel cool now

#

thank you!

fleet cedar
valid panther
grim estuary
#

I want to make an individual cooldown that depends on the role used.

I use this to set the main cooldown.

@commands.cooldown(1, 43200, commands.BucketType.member)```

I use this to reset the cooldown in case of an error.
```py
await command_name.reset_cooldown(ctx=ctx)```
But it is considered as `NoneType` in `Modal` and `View`.

I use this line to update the cooldown according to the role.
```py
command_name.cooldown.per = cooldown```
But it certainly changes the cooldown value for everyone. 


What should I change?
daring grove
#

anyone know why this isnt removing anything

                with open("data.json", "w") as json_file:
                    data["playerrosters"][index].remove(player.display_name)
                    print(index)
                    json.dump(data, json_file)
little cobalt
#

?tag nojson

limber wagonBOT
#

Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.

Advantages of using a database:

- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable

Popular database management systems:

- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
little cobalt
daring grove
grim estuary
lofty sandal
#

@{group_name}.command before your command

little cobalt
lofty sandal
#

yes

fleet cedar
#

Context menu Message commands don't have groups

rugged lodgeBOT
#

Here's the cooldown example.

grim estuary
#

Thank you

harsh gust
#

how do i give a name (with spaces) to a slash command

daring valve
harsh gust
#

kk thanks

#

can i make a param that receives discord.member class data but still input ID when invoking the command

deft kestrel
#

Does anyone know why my welcome message is being sent multiple times instead of just once?
here is the code :

@client.event
async def on_member_join(member):
    welcome = client.get_channel(...)
    
    if (member.guild.id == ...):
        
        embed=discord.Embed(title="{}".format(member.guild.name), description="{}".format(member.mention), color=0xffffff)
        embed.set_image(url="...")
        embed.set_footer(text="{}".format(member.guild.name), icon_url="...")
        
        button = Button(label="...", url="...", emoji="📃")
        
        view = View()
        view.add_item(button)
        
        await welcome.send("|| {} ||".format(member.mention) ,embed=embed, view=view)
    else:
        pass
  • And I changed the bot token several times, but this problem is only in a certain server, there is no problem in other servers, could this problem be from Discord or server settings?
alpine needle
#

@shell radish I officially switched to discord.py and have no plans of switching back PepeSadge

#

Ty for all your help

warm jay
#

I'm using Replit, and when I install Pycord, it installed discord and discord.py
So, I uninstalled them.

Now, I'm getting
AttributeError: module 'discord' has no attribute 'Bot'

shell radish
#

?tag replit

warm jay
#

?tag replit

warm jay
#

oooo

#

thanks

frail ocean
#

I am using Docker with a start.sh and when I use -u it shows me all the logs. Does this have any changes or problems or something. Without -u it doesn’t show the logs

bitter meteor
#

error:
AttributeError: '_EnumValue_ButtonStyle' object has no attribute 'disabled'
code snipped:

self.button1.disabled = toggles[0]```
toggles[0] = True
heavy sky
bitter meteor
#

i am disabling them in the __init __

sinful juniper
#

is there an easier way to see if a slash command has been executed on the bot and then send a log message via webhook, other than setting the log message directly after the ctx.respond() in each individual cog file?

#

possibly an on_slash_command event?

shell radish
#

.rtfm on_interaction

sinful juniper
sinful juniper
deft kestrel
#

Is there a way I can count a specific message keyword in a channel?

grim estuary
#

I installed Python 3.11 with pip, added the link to pip in PATH, but it still doesn't see it on the command panel. How can I fix this?

upper hearth
#

i like accidentally installed discord.py so i uninstalled it and now pycord dont work

  File "bot.py", line 2, in <module>
    from discord import option
ImportError: cannot import name 'option' from 'discord' (unknown location)
#

and installing it again just saying its already installed

little cobalt
#

pip freeze > pip.txt

upper hearth
#

i just uninstalled pycord and reinstalled it and i think it worked?

little cobalt
#

pycord or py-cord?

upper hearth
#

py-cord

south sinew
#

Hi can u help me?
I got error Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

when i use this command

async def rolee(ctx, first: discord.Option(discord.Member), second: discord.Option(discord.Role)):
    await first.add_roles(second)
    await ctx.respond("Yep")```
south sinew
#

But bot is admin

little cobalt
#

Did you invite your bot with the application.commands tag?

south sinew
#

yes, try to reinvite

fickle salmon
south sinew
#

Reinvite didn't help. Any roles do not work, not Admin or Mute

fickle salmon
#

Your bot's role needs to be higher in the list

#

It can't assign roles above its own role

south sinew
#

Does the order of roles matter? omg its realy work

fleet cedar
flat magnet
#

how to differentiate nitro with non nitro users man 🙃

serene lantern
#

How would I grab the server id without ctx?

fickle salmon
serene lantern
fickle salmon
#

you can access bot.guilds

serene lantern
#

it doesnt work though as it just responds with: AttributeError: module 'discord.guild' has no attribute 'id'

fickle salmon
#

Can you send the code

serene lantern
#

def check_near(place):
townSpawn = requests.get(EarthMC_API + "v2/aurora/towns/" + place).json().get("coordinates").get("spawn")
onlineHunters = check_online_hunters()
nearbyHunters = []
with open("config.json", "r") as f:
config_data = json.load(f)
for hunter in onlineHunters:
if math.isclose(townSpawn.get('x'), hunter.get('x'), abs_tol=config_data.get(discord.guild.id).get('radius')) and math.isclose(townSpawn.get('z'), hunter.get('z'), abs_tol=1000):
print("Hunter Spotted! Name: " + hunter.get('name'))
nearbyHunters.append(hunter)
print(nearbyHunters)
return nearbyHunters

fickle salmon
#

?tag codeblock

limber wagonBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
serene lantern
#

sorry

fickle salmon
#

Yeah discord,guild.id isn't going to work, can you pass in your bot to that method?

#

What calls that method

serene lantern
#

i can pass it in

fickle salmon
#

Then you can access bot.guilds

#

Or just pass in ctx.guild?

serene lantern
#

its being called from a task

valid panther
#

I have the database in mongoDB, is it better to use motor, to use it asynchronously than to use pymongo?

torpid ivy
#

so if I pass a ctx object to another python file (like if i have bot.py and game1/functions.py and i do game1.functions.checkanswer(ctx) will game1.functions be able to access the properties/methods associated with ctx without having to import discord? I'm assuming once it's been made, the vars/functions etc are attached to the object itself

#

granted I could just import discord into every file in this thing to be sure but I don't think i NEED to? feels messy

#

like I feel like i would only need to import discord if I wanted to use functions/constructors in the discord module, but not objects already created

torpid ivy
#

though i guess if i'm importing submodule.py into main.py and running submodule.function() it's running submodule.py code in the context of main.py anyways? hmm. sorry, more of a general python question than a pycord question i guess

fringe drum
#

pymongo is blocking meaning no other operations can occur whilst pymongo is doing something

#

reading doc, updating doc etc

daring grove
#

how would i edit an embed with an image thats saved to my computer?

#

currently im trying this
lineupLV1.set_image(url="liverpool.png")
but im getting this error
400 Bad Request (error code: 50035): Invalid Form Body

upper hearth
#

so you either upload it to discord yourself and copy the link or put it on a website

little cobalt
upper hearth
#

i tried it never worked for me

little cobalt
#

?tag localfile

limber wagonBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
upper hearth
#

yea that didnt work when i tried it but maybe it does

little cobalt
#

and if you try it with first the embed and then the file?

daring grove
#

you reckon that would work?

little cobalt
#

Its working fine for me

upper flint
#

Hi! Can anyone please tell me a way to create a dm-only commands for bot?
Regular bot.command() ones only seem to work in guilds

fringe drum
fringe drum
upper flint
#

So it is only possible with message content intent?

fringe drum
#

to my knowledge yes

upper flint
#

Alright, thanks

little cobalt
fringe drum
fringe drum
#

oh my bad, didnt even kow

#

know

little cobalt
#

same for guild_only

upper flint
#

Right now i can see it when typing in bot dm and in any guild the bot is in

pseudo osprey
#

What's the routine to edit the message containing the select menu, i.e. select > edit the message. I have tried both:
discord.Interaction.edit_original_message discord.Interaction.edit_original_response
with no luck (these both edit the interaction response, not the original message)

daring grove
#
            lineupSN1 = discord.Embed()
            with open("napoli.png", "rb") as f:
                pictureSN = discord.File(f, filename="attachment://napoli.png")
            lineupSN1.set_image(url=pictureSN)

this is my code

#

im getting the same error

fleet cedar
daring grove
#

pictureSN = discord.File("napoli.png", filename="attachment://napoli.png")

fleet cedar
#

uh no

daring grove
#

oh wait

#

im silly hold on

#
pictureSN = discord.File(f, filename="napoli.png")
lineupSN1.set_image(url="attachment://napoli.png")
#

like that?

daring grove
#

alright let me try it

fleet cedar
#

you can let discord.File open it for you. that way you can skip the with open

#

you will need to pass the path instead of f

daring grove
#

or

fleet cedar
#

will mostly work

daring grove
#

alright

fleet cedar
daring grove
#

hm

#

it edits the message

#

no error

#

however the embed is empty now

fleet cedar
hazy turret
# fleet cedar Return discord.OptionChoice, not a dict (Sorry I confused it with SelectOption ...

Still not quite working...

        return [
            discord.OptionChoice(name=role.name, value=role.id)
            for role in filtered_roles
        ]```

In data.choices.0.value: Could not interpret "1132358908522434640" as string.
In data.choices.1.value: Could not interpret "1131968976482865448" as string.
In data.choices.2.value: Could not interpret "1131969634553267250" as string.
In data.choices.3.value: Could not interpret "1113454359431590701" as string.
In data.choices.4.value: Could not interpret "1131969155345198561" as string```

fleet cedar
#

that usually works

#

how about str(role.id)

hazy turret
daring grove
#

in this line pictureSN = discord.File(f, filename="napoli.png")
would i need to reference pictureSN anywhere else?

fleet cedar
daring grove
#

i think thats why it probably isnt working

#
lineupSN1 = discord.Embed()
pictureSN = discord.File("napoli.png", filename="napoli.png")
lineupSN1.set_image(url="attachment://napoli.png")
await ctx.bot.setupembedSN1.edit(embed = lineupSN1)
fleet cedar
#

you also need to send it as a file

#

?tag localfile

limber wagonBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
fleet cedar
#

this sums it up pretty much

daring grove
#

oh so

daring grove
fleet cedar
daring grove
#

ok time to try

#

no way

#

it actually worked

#

😱

hazy turret
daring grove
#

anyone know anything about pillow?

upper hearth
#

i emailed discord abt the whole on_presence_update saying idle instead of offline and they told me to ask in the discord devs server and they just said its probably not discord or pycords fault so what am i meant to do

pseudo osprey
hallow copper
#

I did:)

daring grove
hallow copper
#

I'm a lil busy but you can dm me and I can see wut I can do!

daring grove
#

👍

torpid ivy
#

hm. is there a good way to go from a userID back to a nickname? this is after its been separated from ctx so I can't just go ctx.user.name

#

or whatever it is

shell radish
#

.rtfm fetch_user

shell radish
#

.rtfm get_user

shell radish
#

@torpid ivy ^

torpid ivy
#

so you're saying there's not

shell radish
#

I just linked documentation to them...

torpid ivy
#

yeah that was sarcasm lol. thanks!

shell radish
#

🤥

torpid ivy
#

i'm reorganizing my code in a new way, plus trying cogs. so I'm having to learn a bit about how a bunch of new stuff works

#

plus my old bot was written on discord.py instead of py-cord so thats fun too

shell radish
#

yeah

torpid ivy
#

i love how well slash commands just work though

fickle salmon
#

they're so nice

torpid ivy
#

on the old library I was just using $guess and having the bot delete messages as soon as it processed the guess

#

so you'd still see it for a split second. this solves that entirely :D

slender lantern
#

This'll be vague as heck, unfortunately, but one of my bots just stops responding starting today. No update in a week, zero error messages in the log, just stops responding to interactions. Is anyone aware of any issues going on that might be causing this? Is there some API change that necessitated the post in #library-updates ?

slender lantern
#

Not even the new username stuff?

shell radish
#

no

slender lantern
#

Okay, thanks

#

Is there an on_application_command() equivalent that's guaranteed to run before the command itself runs?

shell radish
#

on_interaction

#

read the docs for it tho, there are warnings in there

slender lantern
#

I worried it might be that. Next question, then: how might I construct an ApplicationContext in there? Looking at the docs, it seems it should be ctx = ApplicationContext(bot, interaction), but ctx.command is None when I do that

shell radish
#

interaction.type

ancient cosmos
#

Is there a way to return a value out of a discord.ui.View?

I want to do something along the lines of:

  • A Cog defines a slash command
  • When a user invokes the slash command, a View is created with a select menu to get foo from the user
  • foo gets passed back to the calling slash-command function, where some Cog-level functions do some post-processing on foo combined with other information from the context
  • The output of the post-processing gets sent as a response to the user

But the issue I'm having is that the examples in the Guide don't go beyond using foo right in the callback function of the select menu where it was asked for. I could theoretically return foo, but I don't know where or how that return would get passed up the call stack, or how I would catch it.

#

The issue I'm having, basically, is that I need to either inject the context and some other dependencies into the View (yucky) or else get foo back out of the View somehow (I don't know how).

ancient cosmos
#

Like... I can do that, but then I have to do all the post-processing from within the View, don't I?

That'd mean that instead of being able to call post-processing functions that live at the Cog level (and get called in other places), I'd have to duplicate those functions into the View, it sounds like.

shell radish
#

no?

ancient cosmos
#

I feel like I'm missing something dumb

#

In this example (from https://guide.pycord.dev/interactions/ui-components/modal-dialogs):

class MyModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        self.add_item(discord.ui.InputText(label="Short Input"))
        self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Modal Results")
        embed.add_field(name="Short Input", value=self.children[0].value)
        embed.add_field(name="Long Input", value=self.children[1].value)
        await interaction.response.send_message(embeds=[embed])

@bot.slash_command()
async def modal_slash(ctx: discord.ApplicationContext):
    """Shows an example of a modal dialog being invoked from a slash command."""
    modal = MyModal(title="Modal via Slash Command")
    await ctx.send_modal(modal)

If I wanted to call another function from modal_slash, based on the input captured in the modal, do I just wait until after await ctx.send_modal(modal) has completed, and then look at the attributes of modal, which will have been updated?

shell radish
#

yeah

ancient cosmos
#

Okay, that makes sense; I was kind of locked into expecting some kind of return-based flow. Cheers

shell radish
#

yay

hybrid tinsel
#

i cant seem to make choices work here

@permissions.command(name="list", description="Lists all users in a permission group")
    async def list(self,
                   ctx: discord.ApplicationContext,
                   permission_group: discord.Option(str, choices=['owners', 'managers', 'members'])
                   ):

any ideas why?

little cobalt
#

Also is it still like that after a dc refresh?

hybrid tinsel
#

ah wait nevermind i solved it

#

i just, forgot to include myself in the permission list

#

😭 sorry!

#

i have no idea why it would work like that though?

#

wait no that wasnt it

#

its there an internal cooldown for choices to update?

little cobalt
#

Sometimes you just have to refresh dc

#

Or restart the bot

hybrid tinsel
#

that is pretty weird, thank you!

plucky ingot
#

I want to let my bot to print out the tag of the channel (something like this #general )

but I don't know why the code is nothing print out

lofty parcel
#

And you need the channel.mention attribute

#

Read the docs

plucky ingot
#

to get the channel id becasue I try to just put id(0123456789) and its error

#

it just print those num for me

lofty parcel
#

It's get_channel()

#

get_channel is the method

#

Do you know how oop works?

#

.rtfm get_channel

plucky ingot
#

I think Im the last one

#

let me try thank you

hybrid tinsel
#

how do i turn an integer into an actual username? (given the integer is an actual userid with a real user behind it)

shell radish
#

.rtfm bot.get_user

shell radish
#

.rtfm bot.fetch_user

hybrid tinsel
#

thank you!

brave ore
#

hi all, have any ideas for implementing a shopping cart using Discord?

shell radish
#

what?

hybrid tinsel
#

what am i doing wrong here?

test = self.bot.get_user(get_members('owners')[0])
                print(get_members('owners')[0])
                print(test)
hybrid tinsel
#

ah ill go check

lofty parcel
hybrid tinsel
brave ore
# shell radish what?

select some goods use clock button, and update embed for selected goods list, then click the "Checkout" button will open a new channel for manual settlement. is this a good way?
Are there any other better ideas?

lofty parcel
#

Not impossible

hybrid tinsel
#

whatd i do wrong 💀

shell radish
#

I also suggesting using *members when sending the message instead of just members

hybrid tinsel
shell radish
#

python uses __repr__ for print

#

and __str__ for ... string stuff

sweet gale
#

hey! can we fetch which command raised an error in on_command_error ?

#

👀

shell radish
#

ctx.command

#

.rtfm context.command

sly karmaBOT
proven epoch
#

Is there a way to create a link in discord that calls another slash command ?

daring valve
#

</roblox play:1131169592761385001>

lofty sandal
fleet cedar
dusk flume
#

How to request to speak in a stage channel, i checked docs, it said to use this method:

stage_channel = await channel.connect(timeout=10)
await request_to_speak()
#

Error while joining stage channel: name 'request_to_speak' is not defined

hybrid tinsel
#

is there a way to make a basic help command that lists all commands under cogs with their description?

dusk flume
# hybrid tinsel is there a way to make a basic help command that lists all commands under cogs w...
@commands.slash_command(
        name="help", description="Display a help command with help on the bot"
    )
    async def help(self, ctx):
        embed = discord.Embed(title="Help", color=0x86DB98)
        commandnum = 1
        for command in self.bot.commands:
                embed.add_field(
                    name=f"__**{commandnum}**__ - </{command.name}:0>",
                    value=f"Info: `{command.description}`",
                    inline=True,
                )
                commandnum += 1
        embed.set_footer(text=defaultfooter)
        button = discord.ui.Button(label="Support Server", url=supportserver)
        view = discord.ui.View()
        view.add_item(button)
        await ctx.respond(content=f"made by whatisyourname.", embed=embed, view=view)
rugged lodgeBOT
#
Toolkit

A bot built to help you manage your Discord server as easily as possible.
Use the menu below to view commands.

Server Count

100

User Count

3495

Ping

102.14ms

hybrid tinsel
#

thank you!

dusk flume
heavy sky
#

You need to do await stage_channel.request_to_speak()

dusk flume
#

Also didn’t work

heavy sky
#

What error do you get?

dusk flume
#

“await stage_channel.request_to_speak()” says voice voiceclient object has not attribute request to speak

#

It’s in docs

heavy sky
#

Saw that now, my mistake

dusk flume
heavy sky
#

Do channel.request_to_speak instead

dusk flume
heavy sky
#

stage_channel is the voice client, but channel is the stage channel

#

hmm

dusk flume
#

I’ll try again but I already tried

heavy sky
#

Can you show all the relevant code?

dusk flume
#

Ok

dusk flume
dusk flume
# heavy sky Can you show all the relevant code?
async def join_voice_channel(channel):
    try:
        channel = Bot.get_channel(channel)
        stage_channel = await channel.connect(timeout=10)
        await channel.request_to_speak()
        Bot.loop.create_task(play_music_loop(stage_channel)) 
    except asyncio.TimeoutError:
        print(f"Timeout occurred while trying to join stage channel {channel.id}.")
    except Exception as e:
        print(f"Error while joining stage channel: {e}")
dusk flume
#

I fixed it

lofty parcel
#

It's a method of the member object

#

That's why you read the docs carefully

bronze jewel
#

how to make the button disabled after pressing it

grim estuary
#
@client.command()
async def test(ctx):
    image = Image.open("image.png")
    await ctx.send(file=image)```
I started looking into the Pillow library and ran into a primitive problem: I don't understand how to display an image in a message.
shell radish
#

haven't worked with pillow, but what does Image.open return

grim estuary
#

But it's not in the message

shell radish
#

is image.png a local file?

grim estuary
#

It is in the same folder as the code. This is a local file

lofty parcel
#

Why do you need pillow to send a local image

grim estuary
#

I want to understand how to send files first to work with their change

shell radish
#

to send a file, you need to open a file in binary-read mode and pass it to create a discord.File object

grim estuary
#

I will try. Thanks

tight holly
#

hey! Quick question, does anyone know how to set the author property on a paginator embed? Thanks!

lofty parcel
#

.rtfm embed.set_author

sly karmaBOT
tight holly
#

no, because that's a funcion

#

I need it in my

Page(
  embeds=[
    discord.Embed(
      description=f"> Nom de la carte: **{card.name}**\n> Rareté la carte: **{card.rarity}**\n> Valeur: **{card.price}         €**\n> Carte en circulation: **12**",
      colour=user.accent_color,
      timestamp=datetime.now(),
    )
  ]
)
shell radish