#Sending embed through slash command argument channel
1 messages · Page 1 of 1 (latest)
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
Looking at your earlier posts you wanted the users to have to pick a option from your list right
yes
Did it post in Rules?
That does not really matter
Ok but first. You should not be using auto complete
Because you can write dinglepop in tipo and hit enter
i think
what is dinglepop
that way you have to pick one of the options
In auto completers the users can write whatever they want. the list is just a suggestion
So even tho it ses regra 1 in the list you can just write "pancakes are yummy" and send it
tipo: str = commands.Param(choices=LANGUAGES)
show code
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=" | 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
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"]
Can you run it?
Pretty sure pylance is wrong about that
ah, the choices where also a pylance promt
Yeah think literal does that
use choices instead
add print(tipo) above it
didnt printed anything
the error is here
Yes, buy why
because im giving a list?
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
tysm
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)
@abstract nymph
i need code as example
im brazilian
dont understand much inglesh
Yeah sorry don't speak Portuguese unfortunately
Don't know how they do this
its ok
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? 😛
Perfect
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
Yes. that will work fine
how can i make an optional field in modal
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
ty
What are you trying to do?
a custom embed sender
Show more code
@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)
options=[
Option(
name="message",
description="A mensagem que você quer que eu repita",
type=OptionType.string,
required=True
)
Where did you get this from?
a code example
@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)
@abstract nymph
Give me the entire traceback
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'
is the cog called Custom?
y
try changing the name of the function to something like make_embed
@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
Sigh you changed stuff, get an error and don't show what you cnaged
Throw that away
This is correct
Alright
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
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?
I know
its because its optional
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
didnt understand
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
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 " "
yes!!!!
ok now
if the person select field2, can i make that is obrigatory to fill campo2
No
ok
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
If your issue was solved, we'd appreciate if you could run /solved. 😃
@abstract nymph pls run /solved
Marked the thread as solved. If your question has not been answered, please open a new thread in #1019642966526140566.