Spaces:
Running
Running
Chandima Prabhath
commited on
Commit
Β·
c15a013
1
Parent(s):
87a21e8
Refactor environment variable handling and remove unused send_status_image function
Browse files
app.py
CHANGED
|
@@ -18,7 +18,7 @@ logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(m
|
|
| 18 |
|
| 19 |
# Env vars
|
| 20 |
GREEN_API_URL = os.getenv("GREEN_API_URL")
|
| 21 |
-
GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL")
|
| 22 |
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
|
| 23 |
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
|
| 24 |
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
|
|
@@ -26,10 +26,6 @@ BOT_STATUS_CHAT = "120363312903494448@g.us" # Chat ID for system messages
|
|
| 26 |
image_dir = "/tmp/images"
|
| 27 |
audio_dir = "/tmp/audio"
|
| 28 |
|
| 29 |
-
# Ensure necessary directories exist
|
| 30 |
-
os.makedirs(image_dir, exist_ok=True)
|
| 31 |
-
os.makedirs(audio_dir, exist_ok=True)
|
| 32 |
-
|
| 33 |
if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE, WEBHOOK_AUTH_TOKEN]):
|
| 34 |
raise ValueError("Environment variables are not set properly")
|
| 35 |
|
|
@@ -138,49 +134,6 @@ def send_audio(message_id, to_number, audio_path, retries=3):
|
|
| 138 |
except Exception as e:
|
| 139 |
return {"error": str(e)}
|
| 140 |
|
| 141 |
-
# --- New helper: send WhatsApp status image ---
|
| 142 |
-
def send_status_image(image_path, caption="Status Update", retries=3):
|
| 143 |
-
"""
|
| 144 |
-
Uploads an image file using Green API's uploadFile endpoint to obtain a URL,
|
| 145 |
-
then sends the WhatsApp status update with that URL using sendMediaStatus.
|
| 146 |
-
"""
|
| 147 |
-
# Step 1: Upload the image to get a file URL
|
| 148 |
-
upload_url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/uploadFile/{GREEN_API_TOKEN}"
|
| 149 |
-
logging.debug("Uploading image to Green API: %s", upload_url)
|
| 150 |
-
try:
|
| 151 |
-
with open(image_path, "rb") as f:
|
| 152 |
-
files = {"file": f}
|
| 153 |
-
upload_response = requests.post(upload_url, files=files)
|
| 154 |
-
upload_response.raise_for_status()
|
| 155 |
-
upload_data = upload_response.json()
|
| 156 |
-
# Adjust key as per API response. Here we try "url" or "fileUrl".
|
| 157 |
-
file_url = upload_data.get("url") or upload_data.get("fileUrl")
|
| 158 |
-
if not file_url:
|
| 159 |
-
logging.error("Upload failed: no file URL returned.")
|
| 160 |
-
return {"error": "No file URL returned from upload"}
|
| 161 |
-
logging.info("Image uploaded successfully. URL: %s", file_url)
|
| 162 |
-
except Exception as e:
|
| 163 |
-
logging.error("Error uploading image: %s", e)
|
| 164 |
-
return {"error": str(e)}
|
| 165 |
-
|
| 166 |
-
# Step 2: Use the file URL to send the status update
|
| 167 |
-
status_url = f"{GREEN_API_MEDIA_URL}/waInstance{GREEN_API_ID_INSTANCE}/sendMediaStatus/{GREEN_API_TOKEN}"
|
| 168 |
-
payload = {
|
| 169 |
-
"urlFile": file_url,
|
| 170 |
-
"caption": caption,
|
| 171 |
-
"fileName": os.path.basename(image_path)
|
| 172 |
-
}
|
| 173 |
-
for i in range(retries):
|
| 174 |
-
try:
|
| 175 |
-
r = requests.post(status_url, json=payload)
|
| 176 |
-
r.raise_for_status()
|
| 177 |
-
logging.info("Status image sent successfully.")
|
| 178 |
-
return r.json()
|
| 179 |
-
except requests.RequestException as e:
|
| 180 |
-
if i == retries - 1:
|
| 181 |
-
logging.error("send_status_image failed: %s", str(e))
|
| 182 |
-
return {"error": str(e)}
|
| 183 |
-
|
| 184 |
# --- core response functions ---
|
| 185 |
def response_text(message_id, chat_id, prompt):
|
| 186 |
try:
|
|
@@ -220,38 +173,10 @@ def handle_image_generation(message_id, chat_id, prompt):
|
|
| 220 |
)
|
| 221 |
else:
|
| 222 |
send_message(message_id, chat_id, "Image generation failed.")
|
| 223 |
-
break # exit on success
|
| 224 |
except Exception as e:
|
| 225 |
logging.error("Error in handle_image_generation: %s", e)
|
| 226 |
send_message(message_id, chat_id, "Error generating image.")
|
| 227 |
|
| 228 |
-
# --- New background thread: WhatsApp Status Updater ---
|
| 229 |
-
def whatsapp_status_updater():
|
| 230 |
-
"""
|
| 231 |
-
Every 2 minutes, this function uses the LLM to generate a random creative image prompt,
|
| 232 |
-
generates an image from it, uploads the image to get a URL, and sends it as a WhatsApp status update.
|
| 233 |
-
"""
|
| 234 |
-
while True:
|
| 235 |
-
try:
|
| 236 |
-
# Generate a random image prompt via LLM
|
| 237 |
-
random_prompt = generate_llm("Generate a creative and random image prompt for a WhatsApp status update.")
|
| 238 |
-
logging.info("Random status prompt: %s", random_prompt)
|
| 239 |
-
# Generate image from the prompt; using "status" as dummy identifiers.
|
| 240 |
-
img, path, ret_prompt, url = generate_image(random_prompt, "status", "status", image_dir)
|
| 241 |
-
if img and os.path.exists(path):
|
| 242 |
-
caption = f"Status: {random_prompt}"
|
| 243 |
-
send_status_image(path, caption)
|
| 244 |
-
os.remove(path)
|
| 245 |
-
else:
|
| 246 |
-
logging.error("Image generation for status failed.")
|
| 247 |
-
except Exception as e:
|
| 248 |
-
logging.error("Error in whatsapp_status_updater: %s", e)
|
| 249 |
-
# Sleep for 2 minutes
|
| 250 |
-
time.sleep(120)
|
| 251 |
-
|
| 252 |
-
# Start the WhatsApp status updater thread
|
| 253 |
-
threading.Thread(target=whatsapp_status_updater, daemon=True).start()
|
| 254 |
-
|
| 255 |
# --- Startup Message ---
|
| 256 |
def send_startup_message():
|
| 257 |
if BOT_STATUS_CHAT:
|
|
@@ -263,22 +188,22 @@ def send_startup_message():
|
|
| 263 |
logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
|
| 264 |
|
| 265 |
help_text = (
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
)
|
| 282 |
|
| 283 |
# --- Webhook ---
|
| 284 |
@app.post("/whatsapp")
|
|
@@ -395,11 +320,14 @@ async def whatsapp_webhook(request: Request):
|
|
| 395 |
send_message(mid, chat, "Failed to generate trivia. Please try again.")
|
| 396 |
return {"success": True}
|
| 397 |
|
|
|
|
| 398 |
if low.startswith("/answer"):
|
|
|
|
| 399 |
user_response = body[len("/answer"):].strip()
|
| 400 |
if chat in trivia_store:
|
| 401 |
correct_answer = trivia_store[chat]["answer"]
|
| 402 |
question = trivia_store[chat]["question"]
|
|
|
|
| 403 |
if user_response:
|
| 404 |
eval_prompt = (
|
| 405 |
f"Question: {question}\n"
|
|
@@ -490,6 +418,7 @@ async def whatsapp_webhook(request: Request):
|
|
| 490 |
})
|
| 491 |
return {"success": True}
|
| 492 |
|
|
|
|
| 493 |
task_queue.put({
|
| 494 |
"type": "audio",
|
| 495 |
"message_id": mid,
|
|
@@ -503,6 +432,13 @@ def index():
|
|
| 503 |
return "Server is running!"
|
| 504 |
|
| 505 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
send_startup_message()
|
| 507 |
import uvicorn
|
| 508 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 18 |
|
| 19 |
# Env vars
|
| 20 |
GREEN_API_URL = os.getenv("GREEN_API_URL")
|
| 21 |
+
GREEN_API_MEDIA_URL = os.getenv("GREEN_API_MEDIA_URL", "https://api.green-api.com")
|
| 22 |
GREEN_API_TOKEN = os.getenv("GREEN_API_TOKEN")
|
| 23 |
GREEN_API_ID_INSTANCE = os.getenv("GREEN_API_ID_INSTANCE")
|
| 24 |
WEBHOOK_AUTH_TOKEN = os.getenv("WEBHOOK_AUTH_TOKEN")
|
|
|
|
| 26 |
image_dir = "/tmp/images"
|
| 27 |
audio_dir = "/tmp/audio"
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
if not all([GREEN_API_URL, GREEN_API_TOKEN, GREEN_API_ID_INSTANCE, WEBHOOK_AUTH_TOKEN]):
|
| 30 |
raise ValueError("Environment variables are not set properly")
|
| 31 |
|
|
|
|
| 134 |
except Exception as e:
|
| 135 |
return {"error": str(e)}
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
# --- core response functions ---
|
| 138 |
def response_text(message_id, chat_id, prompt):
|
| 139 |
try:
|
|
|
|
| 173 |
)
|
| 174 |
else:
|
| 175 |
send_message(message_id, chat_id, "Image generation failed.")
|
|
|
|
| 176 |
except Exception as e:
|
| 177 |
logging.error("Error in handle_image_generation: %s", e)
|
| 178 |
send_message(message_id, chat_id, "Error generating image.")
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
# --- Startup Message ---
|
| 181 |
def send_startup_message():
|
| 182 |
if BOT_STATUS_CHAT:
|
|
|
|
| 188 |
logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
|
| 189 |
|
| 190 |
help_text = (
|
| 191 |
+
"π€ *Hi there, I'm Eve!* Here are the commands you can use:\n\n"
|
| 192 |
+
"β’ */help* β _Show this help message._\n"
|
| 193 |
+
"β’ */summarize <text>* β _Get a quick summary of your text._\n"
|
| 194 |
+
"β’ */translate <language>|<text>* β _Translate text to your chosen language._\n"
|
| 195 |
+
"β’ */joke* β _Enjoy a random, funny joke._\n"
|
| 196 |
+
"β’ */weather <location>* β _Get the current weather for a location._\n"
|
| 197 |
+
"β’ */inspire* β _Receive a short inspirational quote._\n"
|
| 198 |
+
"β’ */trivia* β _Start a new trivia question._\n"
|
| 199 |
+
"β’ */answer [your answer]* β _Reveal the trivia answer or check your answer if provided._\n"
|
| 200 |
+
"β’ */meme <text>* β _Generate a fun meme image._\n"
|
| 201 |
+
"β’ */poll <Question>|<Option1>|<Option2>|β¦* β _Create a poll._\n"
|
| 202 |
+
"β’ */results* β _See current poll results._\n"
|
| 203 |
+
"β’ */endpoll* β _End the poll and show final results._\n"
|
| 204 |
+
"β’ */gen <prompt>* β _Generate an image from your prompt._\n\n"
|
| 205 |
+
"Send any other text and I'll reply with a voice message. I'm here to help, so don't hesitate to ask!"
|
| 206 |
+
)
|
| 207 |
|
| 208 |
# --- Webhook ---
|
| 209 |
@app.post("/whatsapp")
|
|
|
|
| 320 |
send_message(mid, chat, "Failed to generate trivia. Please try again.")
|
| 321 |
return {"success": True}
|
| 322 |
|
| 323 |
+
# ANSWER: Accept any message starting with /answer. If additional text is provided, check it.
|
| 324 |
if low.startswith("/answer"):
|
| 325 |
+
# Remove command and any extra spaces
|
| 326 |
user_response = body[len("/answer"):].strip()
|
| 327 |
if chat in trivia_store:
|
| 328 |
correct_answer = trivia_store[chat]["answer"]
|
| 329 |
question = trivia_store[chat]["question"]
|
| 330 |
+
# If user provided an answer, evaluate it via LLM; otherwise, just reveal the answer.
|
| 331 |
if user_response:
|
| 332 |
eval_prompt = (
|
| 333 |
f"Question: {question}\n"
|
|
|
|
| 418 |
})
|
| 419 |
return {"success": True}
|
| 420 |
|
| 421 |
+
# Fallback: voice reply for any other text
|
| 422 |
task_queue.put({
|
| 423 |
"type": "audio",
|
| 424 |
"message_id": mid,
|
|
|
|
| 432 |
return "Server is running!"
|
| 433 |
|
| 434 |
if __name__ == "__main__":
|
| 435 |
+
# Send startup message on launch
|
| 436 |
+
def send_startup_message():
|
| 437 |
+
if BOT_STATUS_CHAT:
|
| 438 |
+
startup_msg = "π Hi! I'm Eve, your friendly AI assistant. I'm now live and ready to help with images, voice replies, and more!"
|
| 439 |
+
send_message_to_chat(BOT_STATUS_CHAT, startup_msg)
|
| 440 |
+
else:
|
| 441 |
+
logging.warning("BOT_STATUS_CHAT is not set; startup message not sent.")
|
| 442 |
send_startup_message()
|
| 443 |
import uvicorn
|
| 444 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|