新答案
Discord.py 2.0 允许使用按钮和下拉菜单,并新增了对斜杠命令的支持。不再需要第三方存储库。但是,如果您由于某种原因不想使用默认值,您可以查看discord_slash
.
升级到 Discord.py 2.0:
Windows:
pip install -U git+https://github.com/Rapptz/discord.py
MacOS 和 Linux:
pip3 install -U git+https://github.com/Rapptz/discord.py
旧答案:
(这个答案已经过时了。)
截至目前,您可以获得一个名为discord_components
使用按钮。
要安装此库,请使用pip install --upgrade discord-components
(有时命令是pip3 install --upgrade discord-components
).
要导入 Discord 组件按钮,请使用
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
然后只需将这段代码添加到机器人的on_ready()
:
DiscordComponents(bot, change_discord_methods=True)
(确保更换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")])
(需留言)
要在单击按钮时执行某些操作,您可以执行以下操作:
@bot.event
async def on_button_click(interaction):
if interaction.component.label.startswith("Default Button"):
await interaction.respond(type=InteractionType.ChannelMessageWithSource, content='Button Clicked')
此方法甚至在重新启动后仍然有效!
如果您需要的话,这是我为您整理的一个示例:
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")
希望这可以帮助!
提示:如果您希望按钮位于一行,请使用 [[]] 而不是仅使用 [],例如:[[btn1, btn2],[btn3, btn4]] 将导致:
[btn 1][btn 2]
[btn 3][btn 4]
额外提示:您还可以将变量设置为按钮,然后发送该变量