bep40 commited on
Commit
e96b094
Β·
verified Β·
1 Parent(s): f7a0c12

v126b: Fix webhook - handle Zalo message as dict

Browse files
Files changed (1) hide show
  1. app.py +97 -9
app.py CHANGED
@@ -1,5 +1,5 @@
1
- # VASZALOBOT v126 - FIXED STARTUP BLOCKING
2
- """V.AI STUDIO Zalo Bot v126 - non-blocking startup, background product loading"""
3
  import os,json,re,requests,unicodedata,traceback,time,hashlib,random,base64,threading
4
  from flask import Flask,request as flask_request,jsonify
5
  from datetime import datetime
@@ -53,6 +53,85 @@ _products_lock=threading.Lock()
53
  _startup_time=time.time()
54
  def now_vn(): return datetime.now(VN_TZ)
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def load_users():
57
  global KNOWN_CUSTOMERS,WELCOMED_USERS
58
  data=[]
@@ -946,7 +1025,7 @@ def nl_format_results(results,text,budget=0):
946
 
947
  @app.route("/",methods=["GET"])
948
  def home():
949
- return jsonify({"ok":True,"status":"V.AI STUDIO Zalo Bot v126 running","uptime":time.time(),"products_loaded":_products_loaded,"product_count":len(PRODUCTS)})
950
 
951
  @app.route("/healthz",methods=["GET"])
952
  def healthz():
@@ -956,11 +1035,20 @@ def healthz():
956
  def webhook():
957
  try:
958
  data=flask_request.json or {}
959
- text=(data.get('message') or data.get('text') or '').strip()
960
- cid=str(data.get('sender_id') or data.get('cid') or data.get('from') or '')
961
- name=data.get('sender_name') or data.get('name') or ''
 
 
 
 
 
 
 
962
  if not text or not cid:
963
- return jsonify({"ok":False,"error":"missing text or cid"})
 
 
964
  s=sess(cid)
965
  if cid not in WELCOMED_USERS:
966
  WELCOMED_USERS.add(cid)
@@ -1009,9 +1097,9 @@ def admin_logs():
1009
 
1010
  @app.route("/admin/status",methods=["GET"])
1011
  def admin_status():
1012
- return jsonify({"ok":True,"version":"126","products_loaded":_products_loaded,"product_count":len(PRODUCTS),"known_customers":len(KNOWN_CUSTOMERS),"sessions":len(SESSIONS),"uptime":time.time()-_startup_time})
1013
 
1014
- log("πŸš€ V.AI STUDIO Zalo Bot v126 starting...")
1015
  load_users()
1016
  log("πŸ‘₯ Loaded %d known customers"%len(KNOWN_CUSTOMERS))
1017
  start_product_loading()
 
1
+ # VASZALOBOT v126b - FIXED WEBHOOK DICT ERROR
2
+ """V.AI STUDIO Zalo Bot v126b - handle Zalo message object as dict"""
3
  import os,json,re,requests,unicodedata,traceback,time,hashlib,random,base64,threading
4
  from flask import Flask,request as flask_request,jsonify
5
  from datetime import datetime
 
53
  _startup_time=time.time()
54
  def now_vn(): return datetime.now(VN_TZ)
55
 
56
+ def _extract_zalo_text(data):
57
+ """Extract text from Zalo webhook payload. Handles multiple formats."""
58
+ # Try 'text' field first (simple string)
59
+ text = data.get('text', '')
60
+ if isinstance(text, str) and text.strip():
61
+ return text.strip()
62
+
63
+ # Try 'message' field β€” can be string or dict
64
+ msg = data.get('message', '')
65
+ if isinstance(msg, str) and msg.strip():
66
+ return msg.strip()
67
+ if isinstance(msg, dict):
68
+ # Zalo OA webhook: message.text or message.body.text
69
+ inner = msg.get('text', '')
70
+ if isinstance(inner, str) and inner.strip():
71
+ return inner.strip()
72
+ body = msg.get('body', {})
73
+ if isinstance(body, dict):
74
+ inner2 = body.get('text', '')
75
+ if isinstance(inner2, str) and inner2.strip():
76
+ return inner2.strip()
77
+ # Try 'content' key
78
+ content = msg.get('content', '')
79
+ if isinstance(content, str) and content.strip():
80
+ return content.strip()
81
+
82
+ # Try 'body.text'
83
+ body = data.get('body', {})
84
+ if isinstance(body, dict):
85
+ t = body.get('text', '')
86
+ if isinstance(t, str) and t.strip():
87
+ return t.strip()
88
+
89
+ # Try 'event_name' for non-text events
90
+ event = data.get('event_name', '')
91
+ if event:
92
+ return str(event)
93
+
94
+ return ''
95
+
96
+ def _extract_zalo_cid(data):
97
+ """Extract sender ID from Zalo webhook payload."""
98
+ # Direct fields
99
+ for key in ['sender_id', 'cid', 'from', 'user_id']:
100
+ val = data.get(key, '')
101
+ if val:
102
+ return str(val)
103
+
104
+ # Nested in sender
105
+ sender = data.get('sender', {})
106
+ if isinstance(sender, dict):
107
+ sid = sender.get('id', '')
108
+ if sid:
109
+ return str(sid)
110
+
111
+ # Nested in from_user
112
+ from_user = data.get('from_user', {})
113
+ if isinstance(from_user, dict):
114
+ uid = from_user.get('id', '')
115
+ if uid:
116
+ return str(uid)
117
+
118
+ return ''
119
+
120
+ def _extract_zalo_name(data):
121
+ """Extract sender name from Zalo webhook payload."""
122
+ for key in ['sender_name', 'name', 'display_name']:
123
+ val = data.get(key, '')
124
+ if val:
125
+ return str(val)
126
+
127
+ sender = data.get('sender', {})
128
+ if isinstance(sender, dict):
129
+ n = sender.get('name', '')
130
+ if n:
131
+ return str(n)
132
+
133
+ return ''
134
+
135
  def load_users():
136
  global KNOWN_CUSTOMERS,WELCOMED_USERS
137
  data=[]
 
1025
 
1026
  @app.route("/",methods=["GET"])
1027
  def home():
1028
+ return jsonify({"ok":True,"status":"V.AI STUDIO Zalo Bot v126b running","uptime":time.time(),"products_loaded":_products_loaded,"product_count":len(PRODUCTS)})
1029
 
1030
  @app.route("/healthz",methods=["GET"])
1031
  def healthz():
 
1035
  def webhook():
1036
  try:
1037
  data=flask_request.json or {}
1038
+ # Debug: log raw payload for troubleshooting
1039
+ log("πŸ“¨ webhook payload keys: %s" % list(data.keys()))
1040
+
1041
+ # Extract text, cid, name using robust helpers
1042
+ text=_extract_zalo_text(data)
1043
+ cid=_extract_zalo_cid(data)
1044
+ name=_extract_zalo_name(data)
1045
+
1046
+ log("πŸ“¨ cid=%s name=%s text=%s" % (cid[:8] if cid else '', name, text[:80] if text else ''))
1047
+
1048
  if not text or not cid:
1049
+ log("⚠️ webhook: missing text or cid, payload=%s" % str(data)[:200])
1050
+ return jsonify({"ok":False,"error":"missing text or cid","raw_keys":list(data.keys())})
1051
+
1052
  s=sess(cid)
1053
  if cid not in WELCOMED_USERS:
1054
  WELCOMED_USERS.add(cid)
 
1097
 
1098
  @app.route("/admin/status",methods=["GET"])
1099
  def admin_status():
1100
+ return jsonify({"ok":True,"version":"126b","products_loaded":_products_loaded,"product_count":len(PRODUCTS),"known_customers":len(KNOWN_CUSTOMERS),"sessions":len(SESSIONS),"uptime":time.time()-_startup_time})
1101
 
1102
+ log("πŸš€ V.AI STUDIO Zalo Bot v126b starting...")
1103
  load_users()
1104
  log("πŸ‘₯ Loaded %d known customers"%len(KNOWN_CUSTOMERS))
1105
  start_product_loading()