#Sending embed through slash command argument channel

1 messages · Page 1 of 1 (latest)

abstract nymph
#

Sending an embed using text channel argument

#
from disnake.ext import commands
from regras import regra1, regra2
import disnake

LANGUAGES = ["regra 1", "regra 2"]

async def autocomp_rules(inter: disnake.ApplicationCommandInteraction, user_input: str):
    return [lang for lang in LANGUAGES if user_input.lower() in lang]


class Custom(commands.Cog):

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.slash_command()
    async def regras(self, inter: disnake.ApplicationCommandInteraction, canal: disnake.TextChannel, tipo: str = commands.Param(autocomplete=autocomp_rules)):
        """Manda algumas regras prontas para o canal de regras do servidor
        
        Parameters
        ----------
        canal: O canal que você deseja enviar a regra
        tipo: A regra escolhida (veja as regras no site)
        """
        if tipo == ["regra 1"]:
            await canal.send(embed=regra1)


def setup(bot: commands.Bot):
    bot.add_cog(Custom(bot))
#

@shrewd cradle

#

Sending embed through slash command argument channel

#

Its probably that tipo is not regra 1

shrewd cradle
abstract nymph
#

Looking at your earlier posts you wanted the users to have to pick a option from your list right

shrewd cradle
#

yes

abstract nymph
#

Did it post in Rules?

shrewd cradle
#

nope

#

it says that the application didnt responded

abstract nymph
#

That does not really matter

shrewd cradle
#

like

#

i want to send a rule to a rule channel

abstract nymph
#

Ok but first. You should not be using auto complete

shrewd cradle
#

why not?

#

more easier that using buttons

abstract nymph
#

Because you can write dinglepop in tipo and hit enter

shrewd cradle
#

i think

abstract nymph
#

you want to use choices=

#

and give it the list

shrewd cradle
#

what is dinglepop

abstract nymph
#

that way you have to pick one of the options

shrewd cradle
#

yes yes

abstract nymph
#

In auto completers the users can write whatever they want. the list is just a suggestion

shrewd cradle
#

oh

#

really

abstract nymph
#

So even tho it ses regra 1 in the list you can just write "pancakes are yummy" and send it

shrewd cradle
#

yes i see it now

#

how can i make the user select one of the option

#

?

abstract nymph
#

tipo: str = commands.Param(choices=LANGUAGES)

shrewd cradle
abstract nymph
#

show code

shrewd cradle
#

sorry

#
from disnake.ext import commands
import disnake

#inicio das regras

LANGUAGES = ["regra 1", "regra 2"]

async def autocomp_rules(inter: disnake.ApplicationCommandInteraction, user_input: str):
    return [lang for lang in LANGUAGES if user_input.lower() in lang]


regra1 = disnake.Embed(
    title="Regras do servidor",
    description="![regras](https://cdn.discordapp.com/emojis/1057752735740596335.webp?size=128 "regras") | Leia todas as regras para não ser punido!",
    color=disnake.Colour.dark_blue(),
)
regra1.set_footer(
     text="Todos os direitos reservados | Solaris",
)
regra1.set_image(url="https://media.discordapp.net/attachments/1055089950040801321/1060294486921584722/template_1.png?width=832&height=468")
regra1.add_field(name="Desrespeito e xingamentos", value="O desrespeito com quaisquer membro ou admisministrado não será permitido, ou seja, trate todos com muito respeito!", inline=False)
regra1.add_field(name="Spam ou flood", value="Não é permitido enviar várias mensagens idênticas ou enviar várias mensagens aletórias repitidamente.", inline=False)
regra1.add_field(name="Divulgação", value="Qualquer divulgução de servidor, bot etc. não é permitida! ", inline=False)
regra1.add_field(name="Nsfw/Gore", value="Não é permitido qualquer postagem que contenha conteúdo +18", inline=False)
regra1.add_field(name="É inaceitável usar linguagem abusiva", value="Tenha cuidado para não usar palavras ofensivas que possam ferir outro membro, independentemente do idioma que você usa.", inline=False)
regra1.add_field(name="Apelidos inapropriados", value="Não é permitido nenhum apelido inapropriado no servidor", inline=False)




class Custom(commands.Cog):

    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.slash_command()
    async def regras(self, inter: disnake.ApplicationCommandInteraction, canal: disnake.TextChannel, tipo: str = commands.Param(choices=LANGUAGES)):
        """Manda algumas regras prontas para o canal de regras do servidor
        
        Parameters
        ----------
        canal: O canal que você deseja enviar a regra
        tipo: A regra escolhida (veja as regras no site)
        """
        if tipo == ["regra 1"]:
            await canal.send(embed=regra1)


def setup(bot: commands.Bot):
    bot.add_cog(Custom(bot))
#

@abstract nymph

abstract nymph
#

Thats really strange

#

try doing choices=["regra 1", "regra 2"]

shrewd cradle
abstract nymph
#

i do this all the time.

#

What version of disnake are you using?

#

alternatively you can try
from typing import Literal
then
tipo:str = Literal["regra 1", "regra 2"]

shrewd cradle
abstract nymph
#

Can you run it?

#

Pretty sure pylance is wrong about that

#

ah, the choices where also a pylance promt

shrewd cradle
#

@abstract nymph

#

it is now an optional option

abstract nymph
#

Yeah think literal does that

shrewd cradle
abstract nymph
#

use choices instead

shrewd cradle
#

i think the problem is here

abstract nymph
#

add print(tipo) above it

shrewd cradle
#

didnt printed anything

shrewd cradle
abstract nymph
#

Sigh yes it is

#

i diddnt see it

#

Want to make a guess? 😛

shrewd cradle
#

remove the []

#

?

abstract nymph
#

Yes, buy why

shrewd cradle
#

because im giving a list?

abstract nymph
#

Internet died on my computer..

#

But yes you where comparing a list to a string

#

You can do that but you need to use if string in list syntax then

shrewd cradle
#

tysm

abstract nymph
#

Now, to get rid of the error you get inside discord.
This is because when you execute a slash command. Discord sends your bot an interaction. Which you have to respond to within 3 seconds. If you don't it errors out like you see.

Normally we respond by doing
inter.send("command works")
Or
inter.response.send_message("command works")

However since you want the output to happen in a different channel you should use
inter.response.defer() at the beginning for the bot to answer silently
Or
inter.response.send(ephemeral=True, content="Message delivered")
Can add delete_after=10.0
To have that confirmation message dissappear

As a side note.
Defer is normally used as a way to indicate to discord that I got the interaction, but I need time to answer.
You will then get a followup webhook back you can use to edit the response
using either
inter.followup.send or edit("slow command finished")
or
inter.edit_original_response("slow command finished)

shrewd cradle
#

@abstract nymph

#

i need code as example

#

im brazilian

#

dont understand much inglesh

abstract nymph
#

Yeah sorry don't speak Portuguese unfortunately

abstract nymph
shrewd cradle
abstract nymph
#

Agora, para se livrar do erro, você entra no discord.
Isso ocorre porque quando você executa um comando de barra. Discord envia ao seu bot uma interação. Que você tem que responder dentro de 3 segundos. Se você não fizer isso, os erros serão como você vê.

Normalmente respondemos fazendo
inter.send("comando funciona")
Ou
inter.response.send_message("comando funciona")

No entanto, como você deseja que a saída aconteça em um canal diferente, você deve usar
inter.response.defer() no início para o bot responder silenciosamente
Ou
inter.response.send(ephemeral=True, content="Mensagem entregue")
Pode adicionar delete_after=10.0
Para que essa mensagem de confirmação desapareça

Como uma nota rodapé.
Defer é normalmente usado como uma forma de indicar ao Discord que consegui a interação, mas preciso de tempo para responder.
Você receberá um webhook de acompanhamento que pode ser usado para editar a resposta
usando qualquer um
inter.followup.send ou edit("comando lento finalizado")
ou
inter.edit_original_response("comando lento finalizado)

Better? 😛

shrewd cradle
#

yes

#

i did this

abstract nymph
#

Perfect

shrewd cradle
#

now im trying a modal embed

#

like

#

i want to send a custom embed to a channel with a modal

#

is that possible?

#

like this

abstract nymph
#

Yes. that will work fine

shrewd cradle
#

how can i make an optional field in modal

abstract nymph
#
        components = [
            disnake.ui.TextInput(
                label="Enter CP Rank if number below is wrong",
                placeholder=f"Last CP was: {cp}",
                custom_id="cp",
                style=TextInputStyle.short,
                max_length=5,
                required=False,
                value = cp,

example from my code

shrewd cradle
#

ty

shrewd cradle
#

@abstract nymph

#

sorry

#

resokved mt=y erroe

#

@abstract nymph

#

help

abstract nymph
#

What are you trying to do?

shrewd cradle
#

a custom embed sender

abstract nymph
#

Show more code

shrewd cradle
#

@commands.slash_command(
name="embed",
description="Cria uma embed personalizada",
options=[
Option(
name="message",
description="A mensagem que você quer que eu repita",
type=OptionType.string,
required=True
)
],
)
async def embed(self, interaction: disnake.ApplicationCommandInteraction, message: str):
"""
The bot will say anything you want, but within embeds.
"""
embed = disnake.Embed(
description=message,
color=0x9C84EF
)
await interaction.send(embed=embed)

abstract nymph
#
        options=[
            Option(
                name="message",
                description="A mensagem que você quer que eu repita",
                type=OptionType.string,
                required=True
            )

Where did you get this from?

shrewd cradle
#

a code example

abstract nymph
#
@commands.slash_command(description="Cria uma embed personalizada")
    async def embed(self, interaction: disnake.ApplicationCommandInteraction, message: str):
        """
        The bot will say anything you want, but within embeds.
        """
        embed = disnake.Embed(
            description=message,
            color=0x9C84EF
        )
        await interaction.send(embed=embed)
#

Or if you want descriptions on everything

@commands.slash_command()
    async def embed(self, interaction: disnake.ApplicationCommandInteraction, message: str):
        """
        The bot will say anything you want, but within embeds.

        Parameters
        ----------
        message: A mensagem que você quer que eu repita
        """
        embed = disnake.Embed(
            description=message,
            color=0x9C84EF
        )
        await interaction.send(embed=embed)
shrewd cradle
#

@abstract nymph

abstract nymph
#

Give me the entire traceback

shrewd cradle
#

Ignoring exception in slash command 'embed':
Traceback (most recent call last):
File "C:\Users\iimax\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\slash_core.py", line 730, in invoke
await call_param_func(self.callback, inter, self.cog, **kwargs)
sed an exception: TypeError: Custom.embed() missing 3 required positional arguments: 'title', 'field1', and 'campo1'

abstract nymph
#

is the cog called Custom?

shrewd cradle
#

y

abstract nymph
#

try changing the name of the function to something like make_embed

shrewd cradle
#
    @commands.slash_command(
        name="embed",
        description="Cria uma embed personalizada",
        options=[
            Option(
                name="message",
                description="A mensagem que você quer que eu repita",
                type=OptionType.string,
                required=True
            )
        ]
    )
    async def make_embed(self, interaction: disnake.ApplicationCommandInteraction, title: str, message: str, field1: str, campo1: str, field2: Optional[str] = None, campo2: Optional[str] = None, field3: Optional[str] = None, campo3: Optional[str] = None, field4: Optional[str] = None, campo4: Optional[str] = None):
        """
        The bot will say anything you want, but within embeds.
        """
        embed = disnake.Embed(
            title=title,
            description=message,
            color=0x9C84EF
        )
        embed.add_field(name=field1, value=campo1, inline=False)
        await interaction.send(embed=embed)```
#

lol

abstract nymph
#

Sigh you changed stuff, get an error and don't show what you cnaged

shrewd cradle
#

i will try again to see what it gives lol

abstract nymph
#

Throw that away

shrewd cradle
#

i want to make title, field and description

#

oh

shrewd cradle
#

@abstract nymph

#

Good morning

#

so I have another question

abstract nymph
#

Alright

shrewd cradle
#

so

#

my problem is that when the person makes an embed and dont fill the field2, 3 and 4, it sends the word none

#

can you help?

abstract nymph
#

I know

shrewd cradle
#

its because its optional

abstract nymph
#
async def make_embed(self, interaction: disnake.ApplicationCommandInteraction, title: str, description: str, field1: str, campo1: str, field2: Optional[str] = None, campo2: Optional[str] = None, field3: Optional[str] = None, campo3: Optional[str] = None, field4: Optional[str] = None, campo4: Optional[str] = None):

its because you set them to None if they are not provided

#

So you need to test them before you add the fields

shrewd cradle
#

didnt understand

abstract nymph
#

like

if field2 and campo2:
  embed.add_field(name=field2, value=campo2, inline=False)
#

None evaluates as false, and Strings that are not "" evaluate as True
so if both field2 and campo2 is given, it will add the field

shrewd cradle
#

aaa

#

ok

#

let me try

abstract nymph
#

Or you could do:

if field2:
  embed.add_field(name=field2, value=campo2 or " ", inline=False)
#

That way you can have a "empty" field

#

and value=campo2 or " " will pick campo2 if its given, or default to " "

shrewd cradle
#

yes!!!!

#

ok now

#

if the person select field2, can i make that is obrigatory to fill campo2

abstract nymph
#

No

shrewd cradle
#

ok

abstract nymph
#

You can however have the bot respond like "You added a field with no campo" please enter campo2 now

#

Then use the bot.wait_for() to wait for a response. then you can use that

shrewd cradle
#

ok

#

solved

gloomy path
#

If your issue was solved, we'd appreciate if you could run /solved. 😃

shrewd cradle
#

o can’t

#

i

shrewd cradle
#

@abstract nymph pls run /solved

zinc pendantBOT
#
Solved!

Marked the thread as solved. If your question has not been answered, please open a new thread in #1019642966526140566.