Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,35 @@
|
|
| 1 |
-
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import requests
|
| 3 |
-
|
| 4 |
from flask import Flask
|
| 5 |
|
| 6 |
# ---------- Configuration ----------
|
| 7 |
-
BALE_BOT_TOKEN = os.environ
|
| 8 |
-
GOOGLE_API_KEY = os.environ
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 10 |
|
| 11 |
# ---------- Logging ----------
|
| 12 |
logging.basicConfig(
|
| 13 |
-
level=logging.
|
| 14 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 15 |
handlers=[logging.StreamHandler(sys.stdout), logging.FileHandler('bot.log')]
|
| 16 |
)
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
-
# ---------- AI Model ----------
|
| 20 |
-
genai.
|
| 21 |
-
|
| 22 |
|
| 23 |
# ---------- Flask health check ----------
|
| 24 |
app = Flask(__name__)
|
|
@@ -36,6 +47,38 @@ def show_logs():
|
|
| 36 |
except FileNotFoundError:
|
| 37 |
return "No log file yet."
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
# ---------- Manual polling loop ----------
|
| 40 |
def poll_updates():
|
| 41 |
offset = None
|
|
@@ -45,6 +88,7 @@ def poll_updates():
|
|
| 45 |
params = {"timeout": 30}
|
| 46 |
if offset is not None:
|
| 47 |
params["offset"] = offset
|
|
|
|
| 48 |
resp = requests.post(f"{BALE_API_URL}/getUpdates", json=params, timeout=35)
|
| 49 |
if resp.status_code != 200:
|
| 50 |
logger.error(f"getUpdates failed: {resp.status_code} {resp.text}")
|
|
@@ -58,39 +102,22 @@ def poll_updates():
|
|
| 58 |
continue
|
| 59 |
|
| 60 |
updates = data.get("result", [])
|
| 61 |
-
|
|
|
|
| 62 |
|
| 63 |
for upd in updates:
|
| 64 |
-
|
| 65 |
-
offset = upd["update_id"] + 1 # always acknowledge
|
| 66 |
msg = upd.get("message")
|
| 67 |
if not msg:
|
| 68 |
-
logger.info("Update has no 'message' field, skipping.")
|
| 69 |
continue
|
|
|
|
| 70 |
text = msg.get("text")
|
| 71 |
chat_id = msg.get("chat", {}).get("id")
|
| 72 |
if not text or not chat_id:
|
| 73 |
-
logger.info("No text or chat_id, skipping.")
|
| 74 |
continue
|
| 75 |
|
| 76 |
-
#
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
response = model.generate_content(text)
|
| 80 |
-
reply_text = response.text
|
| 81 |
-
except Exception as e:
|
| 82 |
-
logger.error(f"AI call failed: {e}")
|
| 83 |
-
reply_text = "Sorry, I couldn't process that request."
|
| 84 |
-
# Send reply
|
| 85 |
-
send_resp = requests.post(
|
| 86 |
-
f"{BALE_API_URL}/sendMessage",
|
| 87 |
-
json={"chat_id": chat_id, "text": reply_text},
|
| 88 |
-
timeout=10
|
| 89 |
-
)
|
| 90 |
-
if send_resp.status_code == 200:
|
| 91 |
-
logger.info(f"Reply sent successfully to {chat_id}")
|
| 92 |
-
else:
|
| 93 |
-
logger.error(f"sendMessage failed: {send_resp.status_code} {send_resp.text}")
|
| 94 |
|
| 95 |
except Exception as e:
|
| 96 |
logger.error(f"Polling loop error: {traceback.format_exc()}")
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import logging
|
| 4 |
+
import time
|
| 5 |
+
import json
|
| 6 |
+
import traceback
|
| 7 |
+
import threading
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
import requests
|
| 10 |
+
from google import genai
|
| 11 |
from flask import Flask
|
| 12 |
|
| 13 |
# ---------- Configuration ----------
|
| 14 |
+
BALE_BOT_TOKEN = os.environ.get("BALE_BOT_TOKEN")
|
| 15 |
+
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
|
| 16 |
+
|
| 17 |
+
if not BALE_BOT_TOKEN or not GOOGLE_API_KEY:
|
| 18 |
+
sys.exit("Error: Please set BALE_BOT_TOKEN and GOOGLE_API_KEY environment variables.")
|
| 19 |
+
|
| 20 |
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 21 |
|
| 22 |
# ---------- Logging ----------
|
| 23 |
logging.basicConfig(
|
| 24 |
+
level=logging.INFO, # Changed to INFO to avoid excessive debug poll spam
|
| 25 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 26 |
handlers=[logging.StreamHandler(sys.stdout), logging.FileHandler('bot.log')]
|
| 27 |
)
|
| 28 |
logger = logging.getLogger(__name__)
|
| 29 |
|
| 30 |
+
# ---------- AI Model (Modern SDK) ----------
|
| 31 |
+
ai_client = genai.Client(api_key=GOOGLE_API_KEY)
|
| 32 |
+
MODEL_NAME = 'gemma-4-31b-it'
|
| 33 |
|
| 34 |
# ---------- Flask health check ----------
|
| 35 |
app = Flask(__name__)
|
|
|
|
| 47 |
except FileNotFoundError:
|
| 48 |
return "No log file yet."
|
| 49 |
|
| 50 |
+
# ---------- Thread Pool for Concurrent Processing ----------
|
| 51 |
+
# Allows up to 5 AI requests to process in parallel
|
| 52 |
+
executor = ThreadPoolExecutor(max_workers=5)
|
| 53 |
+
|
| 54 |
+
def process_single_message(chat_id, text):
|
| 55 |
+
"""Processes a single message and sends the reply in a separate thread."""
|
| 56 |
+
logger.info(f"Processing message from {chat_id}: {text}")
|
| 57 |
+
try:
|
| 58 |
+
# Utilizing the modern google-genai client
|
| 59 |
+
response = ai_client.models.generate_content(
|
| 60 |
+
model=MODEL_NAME,
|
| 61 |
+
contents=text
|
| 62 |
+
)
|
| 63 |
+
reply_text = response.text
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"AI call failed for chat {chat_id}: {e}")
|
| 66 |
+
reply_text = "Sorry, I couldn't process that request right now."
|
| 67 |
+
|
| 68 |
+
# Send reply
|
| 69 |
+
try:
|
| 70 |
+
send_resp = requests.post(
|
| 71 |
+
f"{BALE_API_URL}/sendMessage",
|
| 72 |
+
json={"chat_id": chat_id, "text": reply_text},
|
| 73 |
+
timeout=10
|
| 74 |
+
)
|
| 75 |
+
if send_resp.status_code == 200:
|
| 76 |
+
logger.info(f"Reply sent successfully to {chat_id}")
|
| 77 |
+
else:
|
| 78 |
+
logger.error(f"sendMessage failed: {send_resp.status_code} {send_resp.text}")
|
| 79 |
+
except Exception as e:
|
| 80 |
+
logger.error(f"Network error while sending reply to {chat_id}: {e}")
|
| 81 |
+
|
| 82 |
# ---------- Manual polling loop ----------
|
| 83 |
def poll_updates():
|
| 84 |
offset = None
|
|
|
|
| 88 |
params = {"timeout": 30}
|
| 89 |
if offset is not None:
|
| 90 |
params["offset"] = offset
|
| 91 |
+
|
| 92 |
resp = requests.post(f"{BALE_API_URL}/getUpdates", json=params, timeout=35)
|
| 93 |
if resp.status_code != 200:
|
| 94 |
logger.error(f"getUpdates failed: {resp.status_code} {resp.text}")
|
|
|
|
| 102 |
continue
|
| 103 |
|
| 104 |
updates = data.get("result", [])
|
| 105 |
+
if updates:
|
| 106 |
+
logger.info(f"Received {len(updates)} update(s)")
|
| 107 |
|
| 108 |
for upd in updates:
|
| 109 |
+
offset = upd["update_id"] + 1 # Always acknowledge update first
|
|
|
|
| 110 |
msg = upd.get("message")
|
| 111 |
if not msg:
|
|
|
|
| 112 |
continue
|
| 113 |
+
|
| 114 |
text = msg.get("text")
|
| 115 |
chat_id = msg.get("chat", {}).get("id")
|
| 116 |
if not text or not chat_id:
|
|
|
|
| 117 |
continue
|
| 118 |
|
| 119 |
+
# Offload AI generation to the executor so the polling loop remains non-blocking
|
| 120 |
+
executor.submit(process_single_message, chat_id, text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
logger.error(f"Polling loop error: {traceback.format_exc()}")
|