event_hooks.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. import db
  3. import config
  4. import redis
  5. _redis_client = None
  6. def _get_redis():
  7. global _redis_client
  8. if _redis_client is None:
  9. try:
  10. _redis_client = redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT, db=0, decode_responses=True)
  11. except Exception as e:
  12. print(f"FAILED TO CONNECT TO REDIS IN HOOKS: {e}")
  13. return _redis_client
  14. def on_order_created(order_id: int):
  15. """
  16. Hook triggered asynchronously when a new order is placed.
  17. """
  18. print(f"EVENT: Order {order_id} created.")
  19. def on_order_status_changed(order_id: int, status: str, order_data: dict, send_notification: bool):
  20. """
  21. Hook triggered asynchronously when the admin changes the order status.
  22. """
  23. print(f"EVENT: Order {order_id} status changed to {status}. Notify user: {send_notification}")
  24. if send_notification:
  25. user_email = order_data.get('email')
  26. first_name = order_data.get('first_name')
  27. user_id = order_data.get('user_id')
  28. lang = "en"
  29. if user_id:
  30. user_info = db.execute_query("SELECT preferred_language FROM users WHERE id = %s", (user_id,))
  31. if user_info and user_info[0].get('preferred_language'):
  32. lang = user_info[0]['preferred_language']
  33. import notifications
  34. notifications.notify_status_change(user_email, order_id, status, first_name, lang)
  35. def on_message_received(order_id: int, user_id: int, message: str):
  36. """
  37. Hook triggered when a client sends a message to an order chat.
  38. Duplicates message to Redis for Telegram notification.
  39. """
  40. print(f"EVENT: New message for Order {order_id} from User {user_id}: {message[:20]}...")
  41. r = _get_redis()
  42. if r and config.TELEGRAM_CHAT_ID:
  43. try:
  44. # Fetch user name for better notification
  45. user_res = db.execute_query("SELECT first_name, last_name FROM users WHERE id = %s", (user_id,))
  46. name = f"{user_res[0].get('first_name', 'User')} {user_res[0].get('last_name', '')}".strip() if user_res else "Client"
  47. payload = {
  48. "id": config.TELEGRAM_CHAT_ID,
  49. "message": f"💬 <b>Новое сообщение</b>\nЗаказ: #{order_id}\nОт: <b>{name}</b>\n\n{message}"
  50. }
  51. r.rpush("messages_queue", json.dumps(payload, ensure_ascii=False))
  52. except Exception as e:
  53. print(f"FAILED TO PUSH CHAT MESSAGE TO REDIS: {e}")