shashwatIDR commited on
Commit
611a040
·
verified ·
1 Parent(s): d56de30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -12
app.py CHANGED
@@ -1,8 +1,11 @@
1
  import logging
 
 
2
  from flask import Flask
3
  from threading import Thread
4
  from telegram import Update
5
  from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters
 
6
  import google.generativeai as genai
7
 
8
  # ==== CONFIG ====
@@ -17,7 +20,6 @@ logger = logging.getLogger(__name__)
17
 
18
  # ==== GEMINI AI SETUP ====
19
  genai.configure(api_key=GEMINI_API_KEY)
20
- # Updated model name - gemini-pro is deprecated
21
  model = genai.GenerativeModel("gemini-1.5-flash")
22
 
23
  # ==== FLASK APP ====
@@ -27,6 +29,10 @@ flask_app = Flask(__name__)
27
  def home():
28
  return "✅ Telegram AI Chatbot is running on port 7860!"
29
 
 
 
 
 
30
  # ==== TELEGRAM BOT HANDLERS ====
31
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
32
  await update.message.reply_text("👋 Hi! I am Sumit, your AI buddy. How can I help you today?")
@@ -37,18 +43,64 @@ async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
37
  response = model.generate_content(user_message)
38
  reply = response.text if response.text else "⚠️ I couldn't generate a reply."
39
  except Exception as e:
40
- logger.error(e)
41
  reply = "❌ Something went wrong while generating response."
42
- await update.message.reply_text(reply)
 
 
 
 
43
 
44
- # ==== MAIN ====
45
- if __name__ == "__main__":
46
- # Run Flask in a separate thread
47
- Thread(target=lambda: flask_app.run(host="0.0.0.0", port=7860), daemon=True).start()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- # Run Telegram bot (no asyncio.run!)
50
- app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
51
- app.add_handler(CommandHandler("start", start))
52
- app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
53
 
54
- app.run_polling()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import logging
2
+ import time
3
+ import asyncio
4
  from flask import Flask
5
  from threading import Thread
6
  from telegram import Update
7
  from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, ContextTypes, filters
8
+ from telegram.error import NetworkError, TimedOut
9
  import google.generativeai as genai
10
 
11
  # ==== CONFIG ====
 
20
 
21
  # ==== GEMINI AI SETUP ====
22
  genai.configure(api_key=GEMINI_API_KEY)
 
23
  model = genai.GenerativeModel("gemini-1.5-flash")
24
 
25
  # ==== FLASK APP ====
 
29
  def home():
30
  return "✅ Telegram AI Chatbot is running on port 7860!"
31
 
32
+ @flask_app.route("/health")
33
+ def health():
34
+ return {"status": "healthy", "timestamp": time.time()}
35
+
36
  # ==== TELEGRAM BOT HANDLERS ====
37
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
38
  await update.message.reply_text("👋 Hi! I am Sumit, your AI buddy. How can I help you today?")
 
43
  response = model.generate_content(user_message)
44
  reply = response.text if response.text else "⚠️ I couldn't generate a reply."
45
  except Exception as e:
46
+ logger.error(f"Gemini error: {e}")
47
  reply = "❌ Something went wrong while generating response."
48
+
49
+ try:
50
+ await update.message.reply_text(reply)
51
+ except Exception as e:
52
+ logger.error(f"Telegram reply error: {e}")
53
 
54
+ def start_bot_with_retry():
55
+ """Start bot with retry logic for network issues"""
56
+ max_retries = 5
57
+ retry_delay = 10
58
+
59
+ for attempt in range(max_retries):
60
+ try:
61
+ logger.info(f"Attempting to start bot (attempt {attempt + 1}/{max_retries})")
62
+
63
+ # Build application with custom settings for better reliability
64
+ app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
65
+ app.add_handler(CommandHandler("start", start))
66
+ app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
67
+
68
+ # Start polling with error handling
69
+ app.run_polling(
70
+ timeout=30,
71
+ bootstrap_retries=3,
72
+ read_timeout=30,
73
+ write_timeout=30,
74
+ connect_timeout=30,
75
+ pool_timeout=30
76
+ )
77
+
78
+ except (NetworkError, TimedOut, OSError) as e:
79
+ logger.error(f"Network error on attempt {attempt + 1}: {e}")
80
+ if attempt < max_retries - 1:
81
+ logger.info(f"Retrying in {retry_delay} seconds...")
82
+ time.sleep(retry_delay)
83
+ retry_delay *= 2 # Exponential backoff
84
+ else:
85
+ logger.error("Max retries reached. Bot failed to start.")
86
+ raise
87
+ except Exception as e:
88
+ logger.error(f"Unexpected error: {e}")
89
+ raise
90
 
91
+ def run_flask():
92
+ """Run Flask app"""
93
+ flask_app.run(host="0.0.0.0", port=7860, debug=False)
 
94
 
95
+ # ==== MAIN ====
96
+ if __name__ == "__main__":
97
+ # Start Flask in a separate thread
98
+ flask_thread = Thread(target=run_flask, daemon=True)
99
+ flask_thread.start()
100
+
101
+ # Wait a bit for Flask to start
102
+ time.sleep(2)
103
+ logger.info("Flask app started, now starting Telegram bot...")
104
+
105
+ # Start bot with retry logic
106
+ start_bot_with_retry()