rate_limiter.py 833 B

123456789101112131415161718192021222324
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim:fenc=utf-8
  4. import time
  5. from pqai_agent.logging_service import logger
  6. class MessageSenderRateLimiter:
  7. MAX_CHAR_PER_SECOND = 5
  8. def __init__(self):
  9. self.last_send_time = {}
  10. def wait_for_sending(self, sender_id: str, next_message: str):
  11. current_time = time.time()
  12. last_send_time = self.last_send_time.get(sender_id, 0)
  13. elapsed_time = current_time - last_send_time
  14. required_time = len(next_message) / self.MAX_CHAR_PER_SECOND
  15. if elapsed_time < required_time:
  16. logger.debug(f"Rate limit exceeded. Waiting for {required_time - elapsed_time:.2f} seconds.")
  17. time.sleep(required_time - elapsed_time)
  18. current_time = time.time()
  19. self.last_send_time[sender_id] = current_time
  20. return