Python Twitch Bot的命令冷却 [英] Command Cooldown for a Python Twitch Bot

查看:76
本文介绍了Python Twitch Bot的命令冷却的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Pthon制作Twitch Bot.我想对命令进行冷却,因此您只能每(x)秒调用一次命令. 例如:

I'm making a Twitch Bot using Pthon. I want to create a cooldown on the commands so you can only call the command once every (x) seconds. Eg:

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

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

I have tried this code but it doesn't work (Also I want to get rid of time.sleep as during that time I can't use other commands):

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

    break

推荐答案

我的建议是重组代码,以使用模块化的MessageHandler类,每个类都可以处理特定类型的消息(即具有责任链:

My advice would be to restructure your code to use modular MessageHandler classes that can each handle a particular type of message (i.e. have a single responsibility), with the bot's overall behaviour being determined by the type and order of these message handlers within a chain of responsibility:

在其他好处中,使在命令调用之间实现冷却很容易(在下面的实现中,您可以为不同类型的消息自定义不同的持续时间冷却).

Among several other benefits, this makes it easy to implement cooldowns between command invocations (in the implementation below, you can customise different duration cooldowns for different types of message).

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...

这篇关于Python Twitch Bot的命令冷却的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆