2017-01-27 5 views
0

나는 트위터 봇을 Pthon으로 만들고 있습니다. 명령에 대한 재사용 대기열을 작성하여 매 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 

답변

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) 
1

내 조언은 각각 특정 유형의 메시지를 처리 ​​할 수있는 모듈 형 MessageHandler 클래스를 사용하는 코드를 구조 조정하는 것 (즉 single responsibility가) 로봇의 전반적인 동작은 다음의 종류와 순서에 따라 결정되면서, chain of responsibility 내에서 메시지 핸들러 : 여러 가지 다른 장점 중

이 구현 벨로에서 (쉽게 명령을 호출 사이에 재사용 대기 시간을 구현할 수 있습니다 w, 다른 유형의 메시지에 대해 다른 지속 시간의 재사용 대기 시간을 사용자 정의 할 수 있음).

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