Pārlūkot izejas kodu

feat: added chat message duplication to Redis for Telegram notifications

unknown 4 stundas atpakaļ
vecāks
revīzija
1257959858
1 mainītis faili ar 28 papildinājumiem un 14 dzēšanām
  1. 28 14
      backend/services/event_hooks.py

+ 28 - 14
backend/services/event_hooks.py

@@ -1,30 +1,32 @@
 import json
 import db
 import config
+import redis
+
+_redis_client = None
+
+def _get_redis():
+    global _redis_client
+    if _redis_client is None:
+        try:
+            _redis_client = redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT, db=0, decode_responses=True)
+        except Exception as e:
+            print(f"FAILED TO CONNECT TO REDIS IN HOOKS: {e}")
+    return _redis_client
 
 def on_order_created(order_id: int):
     """
     Hook triggered asynchronously when a new order is placed.
-    Users can add any notification logic here (e.g. email or telegram).
     """
     print(f"EVENT: Order {order_id} created.")
-    # Fetch order data if needed
-    order = db.execute_query("SELECT * FROM orders WHERE id = %s", (order_id,))
-    if order:
-        order_data = order[0]
-        # TODO: Add your notification logic here
-        pass
 
 def on_order_status_changed(order_id: int, status: str, order_data: dict, send_notification: bool):
     """
     Hook triggered asynchronously when the admin changes the order status.
-    Uses the send_notification flag explicitly.
     """
     print(f"EVENT: Order {order_id} status changed to {status}. Notify user: {send_notification}")
     
     if send_notification:
-        # TODO: Add your notification logic here (Email, Telegram, SMS, etc.)
-        # The order_data dictionary contains all the details of the order.
         user_email = order_data.get('email')
         first_name = order_data.get('first_name')
         user_id = order_data.get('user_id')
@@ -35,15 +37,27 @@ def on_order_status_changed(order_id: int, status: str, order_data: dict, send_n
             if user_info and user_info[0].get('preferred_language'):
                 lang = user_info[0]['preferred_language']
         
-        print(f"--> Preparing notification to {user_email} (User: {first_name}, Lang: {lang})...")
         import notifications
         notifications.notify_status_change(user_email, order_id, status, first_name, lang)
 
 def on_message_received(order_id: int, user_id: int, message: str):
     """
     Hook triggered when a client sends a message to an order chat.
-    Useful for alerting admins via external systems.
+    Duplicates message to Redis for Telegram notification.
     """
     print(f"EVENT: New message for Order {order_id} from User {user_id}: {message[:20]}...")
-    # TODO: Integration logic (Telegram, Slack, Email to shop owner, etc.)
-    pass
+    
+    r = _get_redis()
+    if r and config.TELEGRAM_CHAT_ID:
+        try:
+            # Fetch user name for better notification
+            user_res = db.execute_query("SELECT first_name, last_name FROM users WHERE id = %s", (user_id,))
+            name = f"{user_res[0].get('first_name', 'User')} {user_res[0].get('last_name', '')}".strip() if user_res else "Client"
+            
+            payload = {
+                "id": config.TELEGRAM_CHAT_ID,
+                "message": f"💬 <b>Новое сообщение</b>\nЗаказ: #{order_id}\nОт: <b>{name}</b>\n\n{message}"
+            }
+            r.rpush("messages_queue", json.dumps(payload, ensure_ascii=False))
+        except Exception as e:
+            print(f"FAILED TO PUSH CHAT MESSAGE TO REDIS: {e}")