rate_limiter.py 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. import time
  5. from typing import Optional, Union, Dict
  6. from pqai_agent.logging_service import logger
  7. from pqai_agent.mq_message import MessageType
  8. class MessageSenderRateLimiter:
  9. MAX_CHAR_PER_SECOND = 5
  10. def __init__(self):
  11. self.last_send_time = {}
  12. def wait_for_sending(self, sender_id: str, next_message: Union[str, Dict]):
  13. current_time = time.time()
  14. last_send_time = self.last_send_time.get(sender_id, 0)
  15. elapsed_time = current_time - last_send_time
  16. if isinstance(next_message, str) or next_message["type"] in (MessageType.TEXT, MessageType.VOICE):
  17. required_time = len(next_message) / self.MAX_CHAR_PER_SECOND
  18. else:
  19. # FIXME: 非文字消息的判断方式
  20. required_time = 2
  21. if elapsed_time < required_time:
  22. logger.debug(f"Rate limit exceeded. Waiting for {required_time - elapsed_time:.2f} seconds.")
  23. time.sleep(required_time - elapsed_time)
  24. current_time = time.time()
  25. self.last_send_time[sender_id] = current_time
  26. return