File size: 3,632 Bytes
21b6b8b
611a040
 
21b6b8b
d56de30
c540b1a
 
611a040
c540b1a
21b6b8b
 
 
c540b1a
21b6b8b
c540b1a
 
 
21b6b8b
c540b1a
21b6b8b
c540b1a
 
d56de30
21b6b8b
c540b1a
 
21b6b8b
c540b1a
 
 
 
611a040
 
 
 
c540b1a
 
d56de30
21b6b8b
c540b1a
 
21b6b8b
c540b1a
d56de30
21b6b8b
611a040
c540b1a
611a040
 
 
 
 
21b6b8b
611a040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d56de30
611a040
 
 
c540b1a
611a040
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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__)

@flask_app.route("/")
def home():
    return "✅ Telegram AI Chatbot is running on port 7860!"

@flask_app.route("/health")
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()