Spaces:
Sleeping
Sleeping
import logging | |
import time | |
import asyncio | |
from flask import Flask | |
from threading import Thread | |
from telegram import Update | |
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters | |
from telegram.error import NetworkError, TimedOut | |
import google.generativeai as genai | |
# ==== CONFIG ==== | |
TELEGRAM_TOKEN = "7745816717:AAGKTpRtuPknjRAIct_2kdoANpJx3ZFztrg" | |
GEMINI_API_KEY = "AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I" | |
# ==== LOGGING ==== | |
logging.basicConfig( | |
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO | |
) | |
logger = logging.getLogger(__name__) | |
# ==== GEMINI AI SETUP ==== | |
genai.configure(api_key=GEMINI_API_KEY) | |
model = genai.GenerativeModel("gemini-1.5-flash") | |
# ==== FLASK APP ==== | |
flask_app = Flask(__name__) | |
def home(): | |
return "✅ Telegram AI Chatbot is running on port 7860!" | |
def health(): | |
return {"status": "healthy", "timestamp": time.time()} | |
# ==== TELEGRAM BOT HANDLERS ==== | |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
await update.message.reply_text("👋 Hi! I am Sumit, your AI buddy. How can I help you today?") | |
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
user_message = update.message.text | |
try: | |
response = model.generate_content(user_message) | |
reply = response.text if response.text else "⚠️ I couldn't generate a reply." | |
except Exception as e: | |
logger.error(f"Gemini error: {e}") | |
reply = "❌ Something went wrong while generating response." | |
try: | |
await update.message.reply_text(reply) | |
except Exception as e: | |
logger.error(f"Telegram reply error: {e}") | |
def start_bot_with_retry(): | |
"""Start bot with retry logic for network issues""" | |
max_retries = 5 | |
retry_delay = 10 | |
for attempt in range(max_retries): | |
try: | |
logger.info(f"Attempting to start bot (attempt {attempt + 1}/{max_retries})") | |
# Build application with custom settings for better reliability | |
app = ApplicationBuilder().token(TELEGRAM_TOKEN).build() | |
app.add_handler(CommandHandler("start", start)) | |
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat)) | |
# Start polling with error handling | |
app.run_polling( | |
timeout=30, | |
bootstrap_retries=3, | |
read_timeout=30, | |
write_timeout=30, | |
connect_timeout=30, | |
pool_timeout=30 | |
) | |
except (NetworkError, TimedOut, OSError) as e: | |
logger.error(f"Network error on attempt {attempt + 1}: {e}") | |
if attempt < max_retries - 1: | |
logger.info(f"Retrying in {retry_delay} seconds...") | |
time.sleep(retry_delay) | |
retry_delay *= 2 # Exponential backoff | |
else: | |
logger.error("Max retries reached. Bot failed to start.") | |
raise | |
except Exception as e: | |
logger.error(f"Unexpected error: {e}") | |
raise | |
def run_flask(): | |
"""Run Flask app""" | |
flask_app.run(host="0.0.0.0", port=7860, debug=False) | |
# ==== MAIN ==== | |
if __name__ == "__main__": | |
# Start Flask in a separate thread | |
flask_thread = Thread(target=run_flask, daemon=True) | |
flask_thread.start() | |
# Wait a bit for Flask to start | |
time.sleep(2) | |
logger.info("Flask app started, now starting Telegram bot...") | |
# Start bot with retry logic | |
start_bot_with_retry() |