首页 > 解决方案 > 有没有办法阻止不和谐位运行此代码?

问题描述

Heyyyyy 我正在制作一个不和谐的机器人,它里面有一个 !kill 命令。你会像这样使用它:

!kill MySecretCode !yes 或 !no 有没有办法在我执行 !no 后阻止代码监听 !yes 函数?这是代码(Python):


@client.command()
@commands.has_any_role("Server Owner")
async def kill(ctx, code):
  if code == "MySecretCode":
    channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
    emb = discord.Embed(color=discord.Color.orange(), title="**Terminate Bot?**",description=f"Are you sure you want to terminate this bot?\nTo continue with termination, type '!yes'.\nTo cancel the termination, type '!no'.")
    await channel.send(embed=emb)
    @client.command()
    async def yes(ctx):
      channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
      emb = discord.Embed(color=discord.Color.red(), title="**Terminating**",description=f"Process terminating...")
      await channel.send(embed=emb)
      await client.close()
      print("Bot terminated")
    @client.command()
    async def no(ctx):
      channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
      emb = discord.Embed(color=discord.Color.green(), title="**Termination Canceled**",description=f"You canceled the termination process")
      await channel.send(embed=emb)


标签: pythondiscord

解决方案


您应该考虑使用wait_fordiscord.py 中针对这种情况制作的函数。wait_for是一个事件函数,它将返回匹配“检查规则”的下一条发送消息。它只会返回或收听 1 条消息。返回消息对象后,事件将结束。

@client.command()
@commands.has_any_role("Server Owner")
async def kill(ctx, code):
  def check_rule(message: discord.Message): # Checks if the author is the sender that triggered the !kill command.
    return message.author.id == ctx.message.author.id

  if code == "MySecretCode":
    channel = discord.utils.get(ctx.author.guild.text_channels, name="new-channel")
    emb = discord.Embed(color=discord.Color.orange(), title="**Terminate Bot?**",description=f"Are you sure you want to terminate this bot?\nTo continue with termination, type '!yes'.\nTo cancel the termination, type '!no'.")
    await channel.send(embed=emb)


    try:
        # timeout after 10 seconds
        answer = (await client.wait_for('message', check=check_rule, timeout=10)).content
    except (asyncio.exceptions.TimeoutError, 
        discord.ext.commands.errors.CommandInvokeError):
        await ctx.send("Took too long to answer.")
        return

    if answer == '!yes':
       # turn off the bot
    elif answer == '!no':
       # don't turn off
    else:
       # invalid answer

推荐阅读