Discord反突袭机器人Lockdown按钮无响应,报AttributeError错误
错误根源
你遇到的交互失败和属性错误,核心原因是代码里错误地通过button.guild获取服务器对象——discord.ui.Button实例本身并不包含guild属性,这会导致遍历频道时抛出异常,后续的响应消息代码根本没机会执行,最终触发交互失败提示。
修复方案
将所有button.guild替换为interaction.guild,interaction对象才是交互上下文的核心载体,包含当前操作所在的服务器、频道等关键信息。
修正后的完整代码
class Lockdown(discord.ui.View): @discord.ui.button(label="Lockdown", style=discord.ButtonStyle.red) async def lockdown(self, button: discord.ui.Button, interaction: discord.Interaction): guild = interaction.guild # 遍历并锁定所有文本频道 for channel in guild.channels: if isinstance(channel, discord.TextChannel): await channel.set_permissions(guild.default_role, send_messages=False) await interaction.response.send_message("所有文本频道已锁定", ephemeral=True) @bot.command() async def lockdown(ctx): view = Lockdown() await ctx.send("点击Lockdown按钮锁定所有文本频道", view=view)
额外优化建议
可以直接筛选出所有文本频道,减少不必要的类型判断次数:
text_channels = [ch for ch in guild.channels if isinstance(ch, discord.TextChannel)] for channel in text_channels: await channel.set_permissions(guild.default_role, send_messages=False)
内容的提问来源于stack exchange,提问作者Kaze
相关产品推荐
相关产品推荐

