Update app.py
Browse files
app.py
CHANGED
|
@@ -1,92 +1,26 @@
|
|
| 1 |
-
import os, sys, logging,
|
| 2 |
-
|
| 3 |
-
from logging.handlers import RotatingFileHandler
|
| 4 |
import google.generativeai as genai
|
| 5 |
-
from
|
| 6 |
-
from flask import Flask, request, jsonify
|
| 7 |
|
| 8 |
# ---------- Configuration ----------
|
| 9 |
BALE_BOT_TOKEN = os.environ["BALE_BOT_TOKEN"]
|
| 10 |
GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
file_handler = RotatingFileHandler('bot.log', maxBytes=5*1024*1024, backupCount=2)
|
| 20 |
-
file_handler.setFormatter(log_formatter)
|
| 21 |
-
file_handler.setLevel(logging.DEBUG)
|
| 22 |
-
|
| 23 |
-
# Console handler
|
| 24 |
-
console_handler = logging.StreamHandler(sys.stdout)
|
| 25 |
-
console_handler.setFormatter(log_formatter)
|
| 26 |
-
console_handler.setLevel(logging.DEBUG)
|
| 27 |
-
|
| 28 |
-
# Root logger
|
| 29 |
-
logging.basicConfig(level=logging.DEBUG, handlers=[file_handler, console_handler])
|
| 30 |
logger = logging.getLogger(__name__)
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
# ---------- Initialize AI Model ----------
|
| 35 |
genai.configure(api_key=GOOGLE_API_KEY)
|
| 36 |
-
|
| 37 |
-
try:
|
| 38 |
-
model = genai.GenerativeModel('models/gemma-4-31b-it')
|
| 39 |
-
logger.info("Gemma model loaded successfully.")
|
| 40 |
-
except Exception as e:
|
| 41 |
-
logger.error(f"Failed to load Gemma model: {e}")
|
| 42 |
-
|
| 43 |
-
# ---------- Initialize Bale Bot ----------
|
| 44 |
-
bot = Client(BALE_BOT_TOKEN)
|
| 45 |
-
logger.info("Bale client created.")
|
| 46 |
-
|
| 47 |
-
async def send_log_to_chat(text):
|
| 48 |
-
"""Send a log message to the configured LOG_CHAT_ID (if any)."""
|
| 49 |
-
if LOG_CHAT_ID:
|
| 50 |
-
try:
|
| 51 |
-
await bot.send_message(LOG_CHAT_ID, f"🤖 Bot Log:\n{text}")
|
| 52 |
-
except Exception as e:
|
| 53 |
-
logger.error(f"Failed to send log to chat: {e}")
|
| 54 |
|
| 55 |
-
|
| 56 |
-
async def handle_message(message):
|
| 57 |
-
logger.debug(f"Received message from {message.author.id}: {message.text}")
|
| 58 |
-
try:
|
| 59 |
-
user_text = message.text
|
| 60 |
-
if not user_text:
|
| 61 |
-
logger.debug("Empty text, ignoring.")
|
| 62 |
-
return
|
| 63 |
-
|
| 64 |
-
logger.info(f"Calling AI for: {user_text}")
|
| 65 |
-
response = model.generate_content(user_text)
|
| 66 |
-
ai_response = response.text
|
| 67 |
-
logger.info(f"AI response: {ai_response[:100]}...") # log first 100 chars
|
| 68 |
-
|
| 69 |
-
await message.reply(ai_response)
|
| 70 |
-
logger.debug("Reply sent successfully.")
|
| 71 |
-
|
| 72 |
-
except Exception as e:
|
| 73 |
-
error_msg = f"Error processing message: {e}\n{traceback.format_exc()}"
|
| 74 |
-
logger.error(error_msg)
|
| 75 |
-
# Reply to the user with a generic error
|
| 76 |
-
await message.reply("Sorry, I encountered an error. The admin has been notified.")
|
| 77 |
-
# Send detailed error to admin chat (if configured)
|
| 78 |
-
await send_log_to_chat(f"Error: {e}")
|
| 79 |
-
|
| 80 |
-
def start_polling():
|
| 81 |
-
"""Run the bot in a separate thread."""
|
| 82 |
-
loop = asyncio.new_event_loop()
|
| 83 |
-
asyncio.set_event_loop(loop)
|
| 84 |
-
logger.info("Polling thread started.")
|
| 85 |
-
# Send a startup notification
|
| 86 |
-
loop.run_until_complete(send_log_to_chat("Bot started and polling..."))
|
| 87 |
-
bot.run() # blocks here
|
| 88 |
-
|
| 89 |
-
# ---------- Flask Web Server ----------
|
| 90 |
app = Flask(__name__)
|
| 91 |
|
| 92 |
@app.route('/')
|
|
@@ -95,7 +29,6 @@ def health():
|
|
| 95 |
|
| 96 |
@app.route('/logs')
|
| 97 |
def show_logs():
|
| 98 |
-
"""Return the last 100 lines of the log file."""
|
| 99 |
try:
|
| 100 |
with open('bot.log', 'r') as f:
|
| 101 |
lines = f.readlines()[-100:]
|
|
@@ -103,19 +36,67 @@ def show_logs():
|
|
| 103 |
except FileNotFoundError:
|
| 104 |
return "No log file yet."
|
| 105 |
|
| 106 |
-
|
| 107 |
-
def
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
|
|
|
| 117 |
if __name__ == "__main__":
|
| 118 |
-
|
| 119 |
-
threading.Thread(target=start_polling, daemon=True).start()
|
| 120 |
-
# Start Flask
|
| 121 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
import os, sys, logging, time, json, traceback, threading
|
| 2 |
+
import requests
|
|
|
|
| 3 |
import google.generativeai as genai
|
| 4 |
+
from flask import Flask
|
|
|
|
| 5 |
|
| 6 |
# ---------- Configuration ----------
|
| 7 |
BALE_BOT_TOKEN = os.environ["BALE_BOT_TOKEN"]
|
| 8 |
GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
|
| 9 |
+
BALE_API_URL = f"https://tapi.bale.ai/bot{BALE_BOT_TOKEN}"
|
| 10 |
+
|
| 11 |
+
# ---------- Logging ----------
|
| 12 |
+
logging.basicConfig(
|
| 13 |
+
level=logging.DEBUG,
|
| 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.configure(api_key=GOOGLE_API_KEY)
|
| 21 |
+
model = genai.GenerativeModel('models/gemma-4-31b-it') # use 'gemma-4-31b-it' if that fails
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
# ---------- Flask health check ----------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
app = Flask(__name__)
|
| 25 |
|
| 26 |
@app.route('/')
|
|
|
|
| 29 |
|
| 30 |
@app.route('/logs')
|
| 31 |
def show_logs():
|
|
|
|
| 32 |
try:
|
| 33 |
with open('bot.log', 'r') as f:
|
| 34 |
lines = f.readlines()[-100:]
|
|
|
|
| 36 |
except FileNotFoundError:
|
| 37 |
return "No log file yet."
|
| 38 |
|
| 39 |
+
# ---------- Manual polling loop ----------
|
| 40 |
+
def poll_updates():
|
| 41 |
+
offset = None
|
| 42 |
+
logger.info("Starting manual polling loop...")
|
| 43 |
+
while True:
|
| 44 |
+
try:
|
| 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}")
|
| 51 |
+
time.sleep(5)
|
| 52 |
+
continue
|
| 53 |
+
|
| 54 |
+
data = resp.json()
|
| 55 |
+
if not data.get("ok"):
|
| 56 |
+
logger.error(f"getUpdates returned not ok: {data}")
|
| 57 |
+
time.sleep(5)
|
| 58 |
+
continue
|
| 59 |
+
|
| 60 |
+
updates = data.get("result", [])
|
| 61 |
+
logger.debug(f"Received {len(updates)} update(s)")
|
| 62 |
+
|
| 63 |
+
for upd in updates:
|
| 64 |
+
logger.info(f"Full update: {json.dumps(upd, indent=2)}") # <-- see everything
|
| 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 |
+
# Got a real message, reply with AI
|
| 77 |
+
logger.info(f"Processing message from {chat_id}: {text}")
|
| 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()}")
|
| 97 |
+
time.sleep(5)
|
| 98 |
|
| 99 |
+
# ---------- Start everything ----------
|
| 100 |
if __name__ == "__main__":
|
| 101 |
+
threading.Thread(target=poll_updates, daemon=True).start()
|
|
|
|
|
|
|
| 102 |
app.run(host="0.0.0.0", port=7860)
|