You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord按钮跳转并分配角色报错:AttributeError问题排查与解决

问题分析与解决

错误原因

  • 调用Google(discord.Interaction)时传入的是discord.Interaction类本身,而非实际的交互实例,导致interaction.guild是属性对象而非服务器实例,因此没有get_role方法。
  • 带url的链接按钮无法触发回调逻辑,点击后直接跳转,无法执行添加角色的操作。
  • 你把添加角色的逻辑放在了View的__init__方法里,这会在发送消息时就执行,而非用户点击按钮时,完全不符合需求。

修复方案

改用普通按钮,在按钮的回调函数中完成「添加角色+引导跳转」的逻辑:

class Google(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)  # 设置timeout=None让按钮永久有效,可按需调整

    @discord.ui.button(label='Click Here', style=discord.ButtonStyle.green)
    async def click_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        # 替换为你的Role2 ID
        role = interaction.guild.get_role(123456789012345678)
        # 为用户添加角色
        await interaction.user.add_roles(role)
        # 替换为目标频道的跳转链接(格式:https://discord.com/channels/服务器ID/频道ID/消息ID)
        channel_url = 'https://discord.com/channels/xxxx/xxxx/xxxx'
        # 仅向点击按钮的用户发送回复
        await interaction.response.send_message(f"已为你添加角色,点击链接跳转:{channel_url}", ephemeral=True)

@bot.command()
async def google(ctx: commands.Context):
    """返回带按钮的消息,点击后添加角色并跳转"""
    await ctx.send('点击下方按钮获取权限并跳转', view=Google())

注意事项

  • 确保Bot拥有「管理角色」权限,且Bot的角色位置高于Role2,否则无法为用户添加角色。
  • 代码中的角色ID、跳转链接需替换为实际值。
  • ephemeral=True可让回复仅对点击按钮的用户可见,避免刷屏,无需该特性可删除此参数。

内容的提问来源于stack exchange,提问作者Test

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:51:16