【问题标题】:Command Cooldown for a Python Twitch BotPython Twitch Bot 的命令冷却时间
【发布时间】:2017-06-13 14:58:13
【问题描述】:

我正在使用 Pthon 制作 Twitch Bot。我想为命令创建一个冷却时间,因此您只能每 (x) 秒调用一次命令。 例如:

Rustie: test
Bot: Testing command
*Imediately after*
Rustie: test
*5 seconds later*
Rustie: test
Bot: Testing command

我已经尝试过这段代码,但它不起作用(另外我想摆脱 time.sleep 因为在那段时间我不能使用其他命令):

used = []
if "test" in message:
    if "test" in used:
        time.sleep(5)
        del(used[:])
    else:
        sendMessage(s, "Testing command")
        used.append("test")

    break

【问题讨论】:

    标签: python bots twitch


    【解决方案1】:

    您需要跟踪自上次调用每个命令以来经过的时间。您可以使用time 模块来实现。

    import time
    
    min_call_freq = 5
    used = {}
    
    def call_command(command):
        print('Calling command `%s`.' % command)
        # do whatever
    
    def cooldown(command):
        print('You have used command `%s` in the last %u seconds.' % (command, min_call_freq))
    
    def process_command(command):
        if (
            command not in used or
            time.time() - used[command] > min_call_freq
        ):
            used[command] = time.time()
            call_command(command)
        else:
            cooldown(command)
    

    【讨论】:

      【解决方案2】:

      我的建议是重组你的代码以使用模块化的MessageHandler 类,每个类都可以处理特定类型的消息(即有一个single responsibility),机器人的整体行为由这些类型和顺序决定chain of responsibility 中的消息处理程序:

      除了其他几个好处之外,这可以轻松实现命令调用之间的冷却时间(在下面的实现中,您可以为不同类型的消息自定义不同的持续时间冷却时间)。

      from abc import ABC, abstractmethod
      
      from datetime import datetime, timedelta
      from time import sleep
      
      
      class MessageHandler(ABC):
          def __init__(self, command_cooldown):
              self._command_cooldown = command_cooldown
              self._last_command_usage = datetime.min
      
          def try_handle_message(self, message):
              if self._can_handle_message(message) and not self.__on_cooldown:
                  self._last_command_usage = datetime.now()
                  return self._handle_message(message)
              else:
                  return None
      
          @property
          def __on_cooldown(self):
              return datetime.now() - self._last_command_usage <= self._command_cooldown
      
          @abstractmethod
          def _can_handle_message(self, s):
              pass
      
          @abstractmethod
          def _handle_message(self, s):
              pass
      
      
      class TestMessageHandler(MessageHandler):
          def __init__(self):
              super().__init__(timedelta(seconds=5))
      
          def _can_handle_message(self, s):
              return 'test' in s
      
          def _handle_message(self, s):
              return 'Testing command'
      
      
      class Bot(object):
          def __init__(self):
              self._message_handlers = [TestMessageHandler()]
      
          def receive_message(self, message):
              print('Received:', message)
              for message_handler in self._message_handlers:
                  response = message_handler.try_handle_message(message)
                  if response:
                      self.send_response(response)
      
          def send_response(self, response):
              print('Responding:', response)
      
      
      if __name__ == '__main__':
          bot = Bot()
          bot.receive_message('test')
      
          for i in range(6):
              bot.receive_message('test')
              print('Sleep 1 second...')
              sleep(1)
      

      输出

      Received: test
      Responding: Testing command
      Received: test
      Sleep 1 second...
      Received: test
      Sleep 1 second...
      Received: test
      Sleep 1 second...
      Received: test
      Sleep 1 second...
      Received: test
      Sleep 1 second...
      Received: test
      Responding: Testing command
      Sleep 1 second...
      

      【讨论】:

        猜你喜欢
        • 2018-02-15
        • 2017-11-21
        • 2019-02-17
        • 2021-09-07
        • 2021-06-17
        • 1970-01-01
        • 2021-03-11
        • 2019-03-11
        • 2021-08-07
        相关资源
        最近更新 更多