Welly-code's picture
Update main.py
71fd5b5 verified
Raw
History Blame Contribute Delete
2.15 kB
import os
import signal
import logging
import asyncio
import uvicorn
from fastapi import FastAPI
from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes
from telegram import Update
from brain.ops_brain import OpsManagerAI
from brain.db_handler import StoreDB
# Setup logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
def get_env(var: str):
val = os.getenv(var)
if not val or not val.strip(): raise RuntimeError(f"Missing {var}")
return val.strip()
# Configuration
TELEGRAM_TOKEN = get_env("TELEGRAM_TOKEN")
GROQ_API_KEY = get_env("GROQ_API_KEY")
SUPABASE_URL = get_env("SUPABASE_URL")
SUPABASE_KEY = get_env("SUPABASE_KEY")
ai_manager, db = None, None
app = FastAPI()
# --- Telegram Handlers ---
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message or not update.message.text: return
try:
data = ai_manager.process_telegram_message(update.message.text.strip())
if data and data.get('store_id'):
db.save_report(data)
await update.message.reply_text("✅ Report logged.")
except Exception as e:
logger.error(f"Handler error: {e}")
# --- Entry ---
async def main():
global ai_manager, db
# 1. Initialize Engines
ai_manager = OpsManagerAI(api_key=GROQ_API_KEY)
db = StoreDB(url=SUPABASE_URL, key=SUPABASE_KEY)
# 2. Build Bot (Polling Mode)
# By using build(), it automatically defaults to polling if no webhook is set
bot_app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
bot_app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))
# 3. Start Bot
logger.info("🚀 Starting bot in polling mode...")
await bot_app.initialize()
await bot_app.start()
await bot_app.updater.start_polling()
# 4. Start Web Server (for health checks)
config = uvicorn.Config(app, host="0.0.0.0", port=7860)
server = uvicorn.Server(config)
await server.serve()
if __name__ == "__main__":
asyncio.run(main())