Spaces:
Sleeping
Sleeping
| import logging | |
| import json | |
| import requests | |
| from flask import Flask, request, jsonify | |
| import google.generativeai as genai | |
| # ==== CONFIG ==== | |
| TELEGRAM_TOKEN = "7745816717:AAGKTpRtuPknjRAIct_2kdoANpJx3ZFztrg" | |
| GEMINI_API_KEY = "AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I" | |
| TELEGRAM_API_URL = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}" | |
| # ==== LOGGING ==== | |
| logging.basicConfig( | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| level=logging.INFO | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ==== GEMINI AI SETUP ==== | |
| try: | |
| genai.configure(api_key=GEMINI_API_KEY) | |
| model = genai.GenerativeModel("gemini-1.5-flash") | |
| logger.info("Gemini AI configured successfully") | |
| except Exception as e: | |
| logger.error(f"Failed to configure Gemini AI: {e}") | |
| model = None | |
| # ==== FLASK APP ==== | |
| app = Flask(__name__) | |
| def send_message(chat_id, text): | |
| """Send message via direct HTTP request to Telegram API""" | |
| try: | |
| url = f"{TELEGRAM_API_URL}/sendMessage" | |
| payload = { | |
| 'chat_id': chat_id, | |
| 'text': text, | |
| 'parse_mode': 'HTML' | |
| } | |
| response = requests.post(url, json=payload, timeout=10) | |
| return response.status_code == 200 | |
| except Exception as e: | |
| logger.error(f"Failed to send message: {e}") | |
| return False | |
| def generate_ai_response(message): | |
| """Generate AI response using Gemini""" | |
| if not model: | |
| return "❌ AI service is not available." | |
| try: | |
| response = model.generate_content(message) | |
| return response.text if response.text else "⚠️ I couldn't generate a reply." | |
| except Exception as e: | |
| logger.error(f"Gemini error: {e}") | |
| return "❌ Something went wrong while generating response." | |
| # ==== ROUTES ==== | |
| def home(): | |
| return """ | |
| <h1>🤖 Telegram AI Chatbot</h1> | |
| <p>✅ Bot is running and ready to receive webhooks!</p> | |
| <p><strong>Webhook URL:</strong> <code>https://your-space-url.hf.space/webhook/{}</code></p> | |
| <p><a href="/health">Health Check</a> | <a href="/set_webhook">Set Webhook</a></p> | |
| """.format(TELEGRAM_TOKEN) | |
| def health(): | |
| return jsonify({ | |
| "status": "healthy", | |
| "gemini_configured": model is not None, | |
| "telegram_token_set": bool(TELEGRAM_TOKEN) | |
| }) | |
| def webhook(): | |
| """Handle incoming updates from Telegram""" | |
| try: | |
| update = request.get_json() | |
| logger.info(f"Received update: {update}") | |
| if not update: | |
| return "No data received", 400 | |
| # Handle message | |
| if "message" in update: | |
| message = update["message"] | |
| chat_id = message["chat"]["id"] | |
| # Handle /start command | |
| if message.get("text") == "/start": | |
| response_text = "👋 Hi! I am Sumit, your AI buddy. How can I help you today?" | |
| send_message(chat_id, response_text) | |
| return "OK" | |
| # Handle regular messages | |
| if "text" in message: | |
| user_message = message["text"] | |
| logger.info(f"Processing message from {chat_id}: {user_message}") | |
| # Generate AI response | |
| ai_response = generate_ai_response(user_message) | |
| # Send response | |
| if send_message(chat_id, ai_response): | |
| logger.info(f"Response sent successfully to {chat_id}") | |
| else: | |
| logger.error(f"Failed to send response to {chat_id}") | |
| return "OK" | |
| except Exception as e: | |
| logger.error(f"Webhook error: {e}") | |
| return "Error", 500 | |
| def set_webhook(): | |
| """Set up the webhook - call this after deployment""" | |
| try: | |
| # Get the current space URL (you'll need to replace this with your actual space URL) | |
| webhook_url = request.host_url.rstrip('/') + f"/webhook/{TELEGRAM_TOKEN}" | |
| url = f"{TELEGRAM_API_URL}/setWebhook" | |
| payload = { | |
| 'url': webhook_url, | |
| 'allowed_updates': ['message'] | |
| } | |
| response = requests.post(url, json=payload, timeout=10) | |
| if response.status_code == 200: | |
| result = response.json() | |
| if result.get('ok'): | |
| return f""" | |
| <h2>✅ Webhook Set Successfully!</h2> | |
| <p><strong>Webhook URL:</strong> {webhook_url}</p> | |
| <p><strong>Response:</strong> {result}</p> | |
| <p>Your bot is now ready to receive messages!</p> | |
| <a href="/">← Back to Home</a> | |
| """ | |
| else: | |
| return f"❌ Failed to set webhook: {result}" | |
| else: | |
| return f"❌ HTTP Error: {response.status_code}" | |
| except Exception as e: | |
| logger.error(f"Error setting webhook: {e}") | |
| return f"❌ Error: {str(e)}" | |
| def webhook_info(): | |
| """Get current webhook information""" | |
| try: | |
| url = f"{TELEGRAM_API_URL}/getWebhookInfo" | |
| response = requests.get(url, timeout=10) | |
| if response.status_code == 200: | |
| info = response.json() | |
| return f""" | |
| <h2>📊 Webhook Information</h2> | |
| <pre>{json.dumps(info, indent=2)}</pre> | |
| <a href="/">← Back to Home</a> | |
| """ | |
| else: | |
| return f"❌ Error getting webhook info: {response.status_code}" | |
| except Exception as e: | |
| return f"❌ Error: {str(e)}" | |
| # ==== TEST ROUTE ==== | |
| def test_ai(): | |
| """Test AI functionality""" | |
| test_message = request.args.get('message', 'Hello, how are you?') | |
| response = generate_ai_response(test_message) | |
| return jsonify({ | |
| "input": test_message, | |
| "output": response, | |
| "gemini_available": model is not None | |
| }) | |
| if __name__ == "__main__": | |
| logger.info("🚀 Starting Telegram Bot Flask App") | |
| app.run(host="0.0.0.0", port=7860, debug=False) |