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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -63
app.py CHANGED
@@ -1,12 +1,10 @@
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 ====
12
  TELEGRAM_TOKEN = "7745816717:AAGKTpRtuPknjRAIct_2kdoANpJx3ZFztrg"
@@ -23,15 +21,11 @@ genai.configure(api_key=GEMINI_API_KEY)
23
  model = genai.GenerativeModel("gemini-1.5-flash")
24
 
25
  # ==== FLASK APP ====
26
- flask_app = Flask(__name__)
27
-
28
- @flask_app.route("/")
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):
@@ -51,56 +45,50 @@ async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
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()
 
1
  import logging
2
+ import json
3
+ from flask import Flask, request
4
+ from telegram import Update, Bot
5
+ from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters
 
 
 
6
  import google.generativeai as genai
7
+ import asyncio
8
 
9
  # ==== CONFIG ====
10
  TELEGRAM_TOKEN = "7745816717:AAGKTpRtuPknjRAIct_2kdoANpJx3ZFztrg"
 
21
  model = genai.GenerativeModel("gemini-1.5-flash")
22
 
23
  # ==== FLASK APP ====
24
+ app = Flask(__name__)
 
 
 
 
25
 
26
+ # ==== TELEGRAM SETUP ====
27
+ bot = Bot(token=TELEGRAM_TOKEN)
28
+ application = Application.builder().token(TELEGRAM_TOKEN).build()
29
 
30
  # ==== TELEGRAM BOT HANDLERS ====
31
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
 
45
  except Exception as e:
46
  logger.error(f"Telegram reply error: {e}")
47
 
48
+ # Add handlers
49
+ application.add_handler(CommandHandler("start", start))
50
+ application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
51
+
52
+ # ==== FLASK ROUTES ====
53
+ @app.route("/")
54
+ def home():
55
+ return " Telegram AI Chatbot is running with webhooks!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ @app.route("/health")
58
+ def health():
59
+ return {"status": "healthy"}
60
+
61
+ @app.route(f"/{TELEGRAM_TOKEN}", methods=["POST"])
62
+ def webhook():
63
+ """Handle incoming updates from Telegram"""
64
+ try:
65
+ update = Update.de_json(request.get_json(force=True), bot)
66
+ # Process update asynchronously
67
+ asyncio.create_task(application.process_update(update))
68
+ return "OK"
69
+ except Exception as e:
70
+ logger.error(f"Webhook error: {e}")
71
+ return "Error", 500
72
+
73
+ @app.route("/set_webhook", methods=["GET"])
74
+ def set_webhook():
75
+ """Set up the webhook (call this once after deployment)"""
76
+ webhook_url = f"https://your-space-name-your-username.hf.space/{TELEGRAM_TOKEN}"
77
+ try:
78
+ # This will need to be called manually or you can set it via Telegram API
79
+ success = asyncio.run(bot.set_webhook(url=webhook_url))
80
+ if success:
81
+ return f"Webhook set to {webhook_url}"
82
+ else:
83
+ return "Failed to set webhook"
84
+ except Exception as e:
85
+ logger.error(f"Error setting webhook: {e}")
86
+ return f"Error: {e}"
87
 
88
  # ==== MAIN ====
89
  if __name__ == "__main__":
90
+ # Initialize the application
91
+ asyncio.run(application.initialize())
 
 
 
 
 
92
 
93
+ # Run Flask app
94
+ app.run(host="0.0.0.0", port=7860, debug=False)