【问题标题】:How to stop infinite loop with the same trigger that starts it?如何使用启动它的相同触发器停止无限循环?
【发布时间】:2017-10-31 06:24:35
【问题描述】:

所以我有这样的事情:

import discord, asyncio

client = discord.Client()

@client.event
async def on_message(message):
    if message.content.lower().startswith("!test"):
        await client.delete_message(message)
        test1 = await client.send_message(message.channel, "%s test1" % (message.author.mention))
        await asyncio.sleep(1)
        while True:
            #newtest = await client.wait_for_message()
            #if newtest.content.lower().startswith("!test"):
                #return 0
            #else:
                test2 = await client.edit_message(test1, "%s test2" % (message.author.mention))
                await asyncio.sleep(1)
                await client.edit_message(test2, "%s test1" % (message.author.mention))
                await asyncio.sleep(1)

client.run('ClientTokenHere')

它的作用是,如果有人在聊天频道中输入 !test,脚本将删除该 !test 消息,然后将一条消息发送到聊天中,该消息显示此人的姓名,后跟文本 test1。然后脚本将在一秒钟后编辑该消息以说test2,然后它将编辑那个相同的消息说test1,然后再次编辑为test2,等等,等等。

但是,我想这样做,以便如果另一个用户再次键入相同的命令!test,脚本将立即为之前激活它的用户停止,并开始为最近的用户执行此操作谁发出命令。我注释掉的行是我试图实现这一目标的尝试。我该怎么做?

【问题讨论】:

    标签: python python-3.x loops discord discord.py


    【解决方案1】:

    您可以使用全局变量来设置您关注的用户。如果用户更改,您可以中断 while 循环并停止。

    【讨论】:

      【解决方案2】:

      不要使用asyncio.sleep(1),您应该使用

      def check(message):
         return message.channel == ctx.channel and message.content.lower().startswith("!test")
      
      try:
         await client.wait_for('message', timeout=1, check=check)
      except:
         continue
      

      唯一的缺点是如果发生超时,那么在循环再次运行之前,机器人不会听命令。

      【讨论】:

        猜你喜欢
        • 2021-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-28
        • 1970-01-01
        相关资源
        最近更新 更多