我正在使用Pthon制作Twitch Bot。我想在命令上创建一个冷却时间,这样你每隔(x)秒就可以调用一次命令。 例如:
bool WriteString(void)
{
if(*appData.stringPointer == '\0')
{
return true;
}
/* Write a character at a time, only if transmitter is empty */
while (PLIB_USART_TransmitterIsEmpty(USART_ID_2))
{
/* Send character */
PLIB_USART_TransmitterByteSend(USART_ID_2, *appData.stringPointer);
/* Increment to address of next character */
appData.stringPointer++;
if(*appData.stringPointer == '\0')
{
return true;
}
}
return false;
}
我已经尝试过这段代码,但它不起作用(我也希望摆脱time.sleep,因为在那段时间我不能使用其他命令):
Rustie: test
Bot: Testing command
*Imediately after*
Rustie: test
*5 seconds later*
Rustie: test
Bot: Testing command
答案 0 :(得分:1)
我的建议是重构您的代码以使用模块化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...
答案 1 :(得分:0)
您需要跟踪自上次调用每个命令以来经过的时间。您可以使用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)