python - Discord.py 按钮交互在用户单击时失败
问题描述
我正在尝试使用按钮为 Discord Bot 创建验证功能。我已经尝试创建它,但不确定它是否有效(测试目的)。
我需要它来提供一个角色来验证一个用户,比如一个名为 Verified 的角色,还想要一个关于我如何使它不是命令的建议,只是让它嵌入到一个新成员可以简单地点击它的单个频道中并获取要验证的角色。
我在开发控制台中没有收到任何错误,只是说当我单击 UI(Discord 应用程序)中的按钮时,我收到一条消息说“交互失败”。
@client.command()
async def verify(ctx):
member = ctx.message.author
role = get(member.guild.roles, name="Sexy EGirl")
await ctx.send(
embed = discord.Embed(description="Click below to verify", color=getcolor(client.user.avatar_url)),
components = [
Button(style=ButtonStyle.blue, label = 'Verify')
]
)
interaction = await client.wait_for("button_click", check=lambda i: i.component.label.startswith("Verify"))
await interaction.respond(member.add_roles(role))
解决方案
如果您不发送响应消息,则会收到“交互失败”。
@client.event
async def on_button_click(interaction):
message = interaction.message
button_id = interaction.component.id
if button_id == "verify_button":
member = message.guild.get_member(interaction.user.id)
role = message.guild.get_role(859852728260231198) # replace role_id with your roleID
await member.add_roles(role)
response = await interaction.respond(embed=discord.Embed(title="Verified"))
@client.command()
@commands.has_permissions(administrator=True) # you need to import command from discord.ext if you want to use this -> from discord.ext import commands
async def verify(ctx):
await ctx.send(
embed=discord.Embed(title="Embed - Title", description="Click below to verify"),
components=[
Button(style=ButtonStyle.blue, label='Verify', custom_id="verify_button")
])
使用此代码,您可以在频道中发送带有验证按钮的嵌入。(如果您有管理员权限)然后用户可以按下按钮并触发 on_button_click 事件。
要处理交互失败,您将发送响应消息。
推荐阅读
- powershell - 有没有办法使用 Pester 测试/断言 Write-Host 的输出?
- wso2 - 基于组的管理员看不到服务提供商配置
- azure-devops - 是否可以从测试计划运行 Powershell 脚本?
- sql - COUNT 和 GROUP BY 仅基于最近的行
- c++ - 从arrayfire中的两个一维数组的划分创建二维数组
- java - JPA在一列中仅选择一个参数并将其放入字符串中
- fiware-orion - Fiware-Device-Simulator Orion 可以处理 bool 类型的值吗?
- spfx - 如何使用 sp.web 获取文件元数据以及文件名本身?SPFX
- django - Django authlib MismatchingStateError on authorize_access_token
- python - python中相似矩阵的Networkx图