将按钮组件添加到消息 (discord.py)

Sha*_*ito 1 python api discord.py

在 discord 的 API 参考中看到这个(消息组件)后,我想知道是否有任何方法可以使用 python 来实现它?

我尝试制作一个 json 数组并将其传递到我的消息中,但无法使其工作。

我也尝试查看 python 的参考,但找不到任何东西。

这是我的代码

components= [
  {
    "type": 2,
    "label": "Clear les kick",
    "style": 4,
    "custom_id": "clear_kick_button"
  }
]
@slash.slash(name="kicked", description="Voir qui a été kick et combien de fois.", guild_ids=guild_id)
async def kicked(ctx):
  await ctx.send("test", components= components)
Run Code Online (Sandbox Code Playgroud)

如果你有任何信息,如果你分享它,谢谢你。

Eri*_*ric 7

截至目前,您可以调用一个库discord_components来使用按钮。

要安装此库,请使用pip install --upgrade discord-components (有时命令是pip3 install --upgrade discord-components)。

要导入 Discord 组件按钮,请使用

from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
Run Code Online (Sandbox Code Playgroud)

然后只需将此代码添加到机器人的on_ready()

DiscordComponents(bot, change_discord_methods=True)
Run Code Online (Sandbox Code Playgroud)

(确保替换bot为您的机器人名称,与您使用的名称相同@something.command()

要向消息添加按钮,请执行以下操作:

await ctx.send(type=InteractionType.ChannelMessageWithSource, content="Message Here", components=[Button(style=ButtonStyle.URL, label="Example Invite Button", url="https://google.com"), Button(style=ButtonStyle.blue, label="Default Button", custom_id="button")])
Run Code Online (Sandbox Code Playgroud)

(需要留言)

要在单击按钮时执行某些操作,您可以执行以下操作:

@bot.event
async def on_button_click(interaction):
    if interaction.component.label.startswith("Default Button"):
        await interaction.respond(type=InteractionType.ChannelMessageWithSource, content='Button Clicked')
Run Code Online (Sandbox Code Playgroud)

这种方法甚至可以在重新启动后幸免于难!

如果您需要,这是我为您整理的示例:

import discord
from discord.ext import commands
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType

bot = commands.Bot(command_prefix=prefix, description="Desc", help_command=None)

@bot.event
async def on_ready():
    DiscordComponents(bot, change_discord_methods=True)
    await bot.change_presence(activity=discord.Game(name=f"{prefix}help"))
    print("Bot has successfully logged in as: {}".format(bot.user))
    print("Bot ID: {}\n".format(bot.user.id))

@bot.command()
async def button(ctx):
    await ctx.send(type=InteractionType.ChannelMessageWithSource, content="Message Here", components=[Button(style=ButtonStyle.URL, label="Example Invite Button", url="https://google.com"), Button(style=ButtonStyle.blue, label="Default Button", custom_id="button")])

bot.run("token")
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

提示:如果您希望按钮在一行中,请使用 [[]] 而不是 [] 例如:[[btn1, btn2],[btn3, btn4]] 将导致:

[btn 1][btn 2]
[btn 3][btn 4]
Run Code Online (Sandbox Code Playgroud)

额外提示:您还可以将变量设置为按钮,然后发送变量