Spaces:
Running
Running
Chandima Prabhath
commited on
Commit
·
f913369
1
Parent(s):
193784d
ignore quoted messeges
Browse files
app.py
CHANGED
@@ -19,6 +19,7 @@ GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.co
|
|
19 |
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
|
20 |
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
|
21 |
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
|
|
|
22 |
image_dir = "/tmp/images"
|
23 |
audio_dir = "/tmp/audio"
|
24 |
|
@@ -120,6 +121,7 @@ def response_audio(message_id, chat_id, prompt):
|
|
120 |
logging.debug("Entering response_audio with prompt: %s", prompt)
|
121 |
try:
|
122 |
result = generate_voice_reply(prompt, model="openai-audio", voice="coral", audio_dir=audio_dir)
|
|
|
123 |
if result and result[0]:
|
124 |
audio_path, _ = result
|
125 |
send_audio(message_id, chat_id, audio_path)
|
@@ -153,24 +155,24 @@ def index():
|
|
153 |
|
154 |
@app.post("/whatsapp")
|
155 |
async def whatsapp_webhook(request: Request):
|
156 |
-
# Auth
|
157 |
auth = request.headers.get('Authorization', '').strip()
|
158 |
if auth != f"Bearer {WEBHOOK_AUTH_TOKEN}":
|
159 |
raise HTTPException(403, "Unauthorized")
|
160 |
|
161 |
-
# Parse JSON
|
162 |
try:
|
163 |
data = await request.json()
|
164 |
except:
|
165 |
return JSONResponse({"error": "Invalid JSON"}, status_code=400)
|
166 |
|
167 |
-
# Only handle incoming messages
|
168 |
if data.get('typeWebhook') != 'incomingMessageReceived':
|
169 |
return {"success": True}
|
170 |
-
|
171 |
logging.debug(f"Received data: {data}")
|
172 |
|
173 |
-
# Extract core fields
|
174 |
try:
|
175 |
chat_id = data['senderData']['chatId']
|
176 |
message_id = data['idMessage']
|
@@ -178,38 +180,33 @@ async def whatsapp_webhook(request: Request):
|
|
178 |
except KeyError as e:
|
179 |
return JSONResponse({"error": f"Missing key: {e}"}, status_code=200)
|
180 |
|
181 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
182 |
if 'textMessageData' in message_data:
|
183 |
body = message_data['textMessageData'].get('textMessage', '').strip()
|
|
|
184 |
elif 'extendedTextMessageData' in message_data:
|
185 |
body = message_data['extendedTextMessageData'].get('text', '').strip()
|
|
|
186 |
else:
|
187 |
return {"success": True}
|
188 |
|
189 |
-
#
|
190 |
-
# 1) pull contextInfo from either textMessageData or extendedTextMessageData
|
191 |
-
ctx = {}
|
192 |
-
if 'extendedTextMessageData' in message_data:
|
193 |
-
ctx = message_data['extendedTextMessageData'].get('contextInfo', {})
|
194 |
-
elif 'textMessageData' in message_data:
|
195 |
-
ctx = message_data['textMessageData'].get('contextInfo', {})
|
196 |
-
|
197 |
-
if ctx.get('quotedMessageId'):
|
198 |
-
logging.debug(f"Ignoring quoted reply: {ctx['quotedMessageId']}")
|
199 |
-
return {"success": True}
|
200 |
-
|
201 |
-
# 2) structured mentions (WhatsApp native tagging)
|
202 |
if ctx.get('mentionedJid') or ctx.get('mentionedJidList'):
|
203 |
logging.debug(f"Ignoring structured mention: {ctx.get('mentionedJid') or ctx.get('mentionedJidList')}")
|
204 |
return {"success": True}
|
205 |
|
206 |
-
#
|
207 |
if chat_id.endswith('@g.us') and re.search(r'@\d+', body):
|
208 |
logging.debug(f"Ignoring plain-text mention in body: {body}")
|
209 |
return {"success": True}
|
210 |
-
# ----------------------------------------
|
211 |
|
212 |
-
# Enqueue work
|
213 |
if body.lower().startswith('/imagine'):
|
214 |
prompt = body[len('/imagine'):].strip()
|
215 |
if not prompt:
|
@@ -234,4 +231,4 @@ async def whatsapp_webhook(request: Request):
|
|
234 |
|
235 |
if __name__ == '__main__':
|
236 |
import uvicorn
|
237 |
-
uvicorn.run(app, host="0.0.0.0", port=
|
|
|
19 |
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
|
20 |
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
|
21 |
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
|
22 |
+
PORT = int(os.getenv("PORT", 7860))
|
23 |
image_dir = "/tmp/images"
|
24 |
audio_dir = "/tmp/audio"
|
25 |
|
|
|
121 |
logging.debug("Entering response_audio with prompt: %s", prompt)
|
122 |
try:
|
123 |
result = generate_voice_reply(prompt, model="openai-audio", voice="coral", audio_dir=audio_dir)
|
124 |
+
logging.debug("generate_voice_reply result: %s", result)
|
125 |
if result and result[0]:
|
126 |
audio_path, _ = result
|
127 |
send_audio(message_id, chat_id, audio_path)
|
|
|
155 |
|
156 |
@app.post("/whatsapp")
|
157 |
async def whatsapp_webhook(request: Request):
|
158 |
+
# 1) Auth
|
159 |
auth = request.headers.get('Authorization', '').strip()
|
160 |
if auth != f"Bearer {WEBHOOK_AUTH_TOKEN}":
|
161 |
raise HTTPException(403, "Unauthorized")
|
162 |
|
163 |
+
# 2) Parse JSON
|
164 |
try:
|
165 |
data = await request.json()
|
166 |
except:
|
167 |
return JSONResponse({"error": "Invalid JSON"}, status_code=400)
|
168 |
|
169 |
+
# 3) Only handle incoming messages
|
170 |
if data.get('typeWebhook') != 'incomingMessageReceived':
|
171 |
return {"success": True}
|
172 |
+
|
173 |
logging.debug(f"Received data: {data}")
|
174 |
|
175 |
+
# 4) Extract core fields
|
176 |
try:
|
177 |
chat_id = data['senderData']['chatId']
|
178 |
message_id = data['idMessage']
|
|
|
180 |
except KeyError as e:
|
181 |
return JSONResponse({"error": f"Missing key: {e}"}, status_code=200)
|
182 |
|
183 |
+
# --- NEW: IGNORE any WhatsApp “quotedMessage” payload entirely ---
|
184 |
+
if message_data.get('typeMessage') == 'quotedMessage' or 'quotedMessage' in message_data:
|
185 |
+
logging.debug("Ignoring WhatsApp quotedMessage payload")
|
186 |
+
return {"success": True}
|
187 |
+
# --------------------------------------------------------------------
|
188 |
+
|
189 |
+
# 5) Extract text body
|
190 |
if 'textMessageData' in message_data:
|
191 |
body = message_data['textMessageData'].get('textMessage', '').strip()
|
192 |
+
ctx = message_data['textMessageData'].get('contextInfo', {})
|
193 |
elif 'extendedTextMessageData' in message_data:
|
194 |
body = message_data['extendedTextMessageData'].get('text', '').strip()
|
195 |
+
ctx = message_data['extendedTextMessageData'].get('contextInfo', {})
|
196 |
else:
|
197 |
return {"success": True}
|
198 |
|
199 |
+
# 6) IGNORE structured mentions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
if ctx.get('mentionedJid') or ctx.get('mentionedJidList'):
|
201 |
logging.debug(f"Ignoring structured mention: {ctx.get('mentionedJid') or ctx.get('mentionedJidList')}")
|
202 |
return {"success": True}
|
203 |
|
204 |
+
# 7) IGNORE plain-text "@1234..." mentions in groups
|
205 |
if chat_id.endswith('@g.us') and re.search(r'@\d+', body):
|
206 |
logging.debug(f"Ignoring plain-text mention in body: {body}")
|
207 |
return {"success": True}
|
|
|
208 |
|
209 |
+
# 8) Enqueue work
|
210 |
if body.lower().startswith('/imagine'):
|
211 |
prompt = body[len('/imagine'):].strip()
|
212 |
if not prompt:
|
|
|
231 |
|
232 |
if __name__ == '__main__':
|
233 |
import uvicorn
|
234 |
+
uvicorn.run(app, host="0.0.0.0", port=PORT)
|