Discord机器人Nuke频道命令:点击No后如何禁用所有按钮
解决Discord机器人Nuke命令按钮问题
你的问题是点击No按钮后Yes按钮仍可点击,要让两个按钮都消失,只需修改nukeConfirm类中的按钮回调逻辑即可,以下是修复后的完整代码:
class nukeConfirm(discord.ui.View): def __init__(self, ctx, nuke_channel): self.ctx = ctx self.nuke_channel = nuke_channel super().__init__() @discord.ui.button(label="Yes", style=discord.ButtonStyle.green) async def yes_callback(self, interaction, button): if interaction.user == self.ctx.author: new_channel = await self.nuke_channel.clone(reason="Has been Nuked!") await self.nuke_channel.delete() await new_channel.send(f"Nuked! {self.ctx.author.mention}", delete_after=0.1) await new_channel.send(f"Nuked by `{self.ctx.author.name}`") with open("logs.json", "a") as f: f.writelines(f"\n{self.ctx.author} used the nuke command. Channel nuked: {self.nuke_channel.name}") # 清空所有按钮,防止重复操作并移除按钮 self.clear_items() await interaction.response.edit_message(view=self) @discord.ui.button(label="No", style=discord.ButtonStyle.red) async def no_callback(self, interaction, button): if interaction.user == self.ctx.author: await self.ctx.send("Aborted") # 清空View中的所有组件,让两个按钮都消失 self.clear_items() await interaction.response.edit_message(view=self) class Channels(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() @commands.has_permissions(manage_channels=True) async def nuke(self, ctx, channel: discord.TextChannel = None): if channel is None: await ctx.send(f"{ctx.author.mention}! You did not mention a channel!", delete_after=5) return nuke_channel = discord.utils.get(ctx.guild.channels, name=channel.name) if nuke_channel is not None: view = nukeConfirm(ctx, nuke_channel) await nuke_channel.send(f"{ctx.author.mention}, are you sure you want to nuke this channel?", view=view) else: await ctx.send(f"No channel named **{channel.name}** was found!") @nuke.error async def nuke_error(self, ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("You don't have permission to use this command.")
关键修改说明
- 在两个按钮的回调函数中都添加了
self.clear_items():这个方法会直接清空当前View中的所有交互组件(也就是两个按钮),编辑消息后按钮就会完全消失。 - 原代码仅禁用了点击的No按钮,没有处理Yes按钮,导致Yes按钮仍处于可点击状态,清空所有组件就能彻底解决这个问题。
- 在Yes回调中添加同样的处理,还能避免用户在执行完Nuke操作后重复点击按钮触发重复执行。
内容的提问来源于stack exchange,提问作者user19932233
相关产品推荐
相关产品推荐

