在Discord.py中实现带解封按钮的封禁命令遇阻求助
问题分析与修复方案
你的代码存在几个关键问题,导致解封按钮无法正常工作:
- 按钮未绑定回调函数,点击后不会触发任何操作
- 回调函数参数定义错误,discord.py按钮回调仅接收
interaction作为参数 - 无法在回调中获取被封禁的成员对象,需要提前保存成员信息
修复后的完整代码
@client.hybrid_command() @commands.has_permissions(ban_members=True) async def ban(ctx, member: discord.Member, *, reason="nicht gegeben"): await member.ban(reason=reason) embed = discord.Embed(description=f' {member.mention} wurde gebannt von {ctx.author.mention}\n**Grund:** {reason}') # 定义带有成员信息的View类 class UnbanView(discord.ui.View): def __init__(self, member_id: int): super().__init__(timeout=None) # 设置永久超时,或按需设置具体时长 self.member_id = member_id # 按钮回调函数,参数仅为interaction @discord.ui.button(label="UNBAN", style=discord.ButtonStyle.red) async def unban_button(self, interaction: discord.Interaction, button: discord.ui.Button): # 检查点击者是否有解封权限 if not interaction.user.guild_permissions.ban_members: await interaction.response.send_message("Du hast keine Berechtigung, jemanden zu entbannen!", ephemeral=True) return try: member = await interaction.guild.fetch_member(self.member_id) await interaction.guild.unban(member, reason="Über Entbann-Button entbannt") await interaction.response.send_message(f"{member.mention} wurde erfolgreich entbannt!", ephemeral=True) # 更新原embed内容(可选) embed.description = f' {member.mention} wurde gebannt von {ctx.author.mention}\n**Grund:** {reason}\n✅ Wurde von {interaction.user.mention} entbannt' await interaction.message.edit(embed=embed) except discord.NotFound: await interaction.response.send_message("Dieser Benutzer ist nicht gebannt oder existiert nicht!", ephemeral=True) # 创建View实例并传入被封禁成员的ID view = UnbanView(member.id) await ctx.send(embed=embed, view=view)
关键修复点说明
- 自定义View类:通过自定义View类保存被封禁成员的ID,确保回调函数能获取到目标对象
- 绑定回调函数:使用
@discord.ui.button装饰器直接绑定按钮的回调逻辑,无需手动赋值 - 权限检查:添加点击者的权限验证,避免无权限用户误操作
- 错误处理:处理用户不存在或未被封禁的异常情况,提升命令稳定性
- 超时设置:设置
timeout=None让按钮永久有效(也可设置具体秒数,如timeout=3600表示1小时后失效)
内容的提问来源于stack exchange,提问作者Lucky
相关产品推荐
相关产品推荐

