Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,94 +1,185 @@
|
|
1 |
import logging
|
2 |
import json
|
3 |
-
|
4 |
-
from
|
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"
|
11 |
GEMINI_API_KEY = "AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I"
|
|
|
12 |
|
13 |
# ==== LOGGING ====
|
14 |
logging.basicConfig(
|
15 |
-
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
|
|
16 |
)
|
17 |
logger = logging.getLogger(__name__)
|
18 |
|
19 |
# ==== GEMINI AI SETUP ====
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
# ==== FLASK APP ====
|
24 |
app = Flask(__name__)
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
application = Application.builder().token(TELEGRAM_TOKEN).build()
|
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?")
|
33 |
-
|
34 |
-
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
35 |
-
user_message = update.message.text
|
36 |
try:
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
except Exception as e:
|
40 |
-
logger.error(f"
|
41 |
-
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
try:
|
44 |
-
|
|
|
45 |
except Exception as e:
|
46 |
-
logger.error(f"
|
47 |
-
|
48 |
-
# Add handlers
|
49 |
-
application.add_handler(CommandHandler("start", start))
|
50 |
-
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
|
51 |
|
52 |
-
# ====
|
53 |
@app.route("/")
|
54 |
def home():
|
55 |
-
return "
|
|
|
|
|
|
|
|
|
|
|
56 |
|
57 |
@app.route("/health")
|
58 |
def health():
|
59 |
-
return {
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
@app.route(f"/{TELEGRAM_TOKEN}", methods=["POST"])
|
62 |
def webhook():
|
63 |
"""Handle incoming updates from Telegram"""
|
64 |
try:
|
65 |
-
update =
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
76 |
-
webhook_url = f"https://your-space-name-your-username.hf.space/{TELEGRAM_TOKEN}"
|
77 |
try:
|
78 |
-
#
|
79 |
-
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
82 |
else:
|
83 |
-
return "
|
|
|
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 |
-
|
91 |
-
asyncio.run(application.initialize())
|
92 |
-
|
93 |
-
# Run Flask app
|
94 |
app.run(host="0.0.0.0", port=7860, debug=False)
|
|
|
1 |
import logging
|
2 |
import json
|
3 |
+
import requests
|
4 |
+
from flask import Flask, request, jsonify
|
|
|
5 |
import google.generativeai as genai
|
|
|
6 |
|
7 |
# ==== CONFIG ====
|
8 |
TELEGRAM_TOKEN = "7745816717:AAGKTpRtuPknjRAIct_2kdoANpJx3ZFztrg"
|
9 |
GEMINI_API_KEY = "AIzaSyCq23lcvpPfig6ifq1rmt-z11vKpMvDD4I"
|
10 |
+
TELEGRAM_API_URL = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}"
|
11 |
|
12 |
# ==== LOGGING ====
|
13 |
logging.basicConfig(
|
14 |
+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
15 |
+
level=logging.INFO
|
16 |
)
|
17 |
logger = logging.getLogger(__name__)
|
18 |
|
19 |
# ==== GEMINI AI SETUP ====
|
20 |
+
try:
|
21 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
22 |
+
model = genai.GenerativeModel("gemini-1.5-flash")
|
23 |
+
logger.info("Gemini AI configured successfully")
|
24 |
+
except Exception as e:
|
25 |
+
logger.error(f"Failed to configure Gemini AI: {e}")
|
26 |
+
model = None
|
27 |
|
28 |
# ==== FLASK APP ====
|
29 |
app = Flask(__name__)
|
30 |
|
31 |
+
def send_message(chat_id, text):
|
32 |
+
"""Send message via direct HTTP request to Telegram API"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
try:
|
34 |
+
url = f"{TELEGRAM_API_URL}/sendMessage"
|
35 |
+
payload = {
|
36 |
+
'chat_id': chat_id,
|
37 |
+
'text': text,
|
38 |
+
'parse_mode': 'HTML'
|
39 |
+
}
|
40 |
+
response = requests.post(url, json=payload, timeout=10)
|
41 |
+
return response.status_code == 200
|
42 |
except Exception as e:
|
43 |
+
logger.error(f"Failed to send message: {e}")
|
44 |
+
return False
|
45 |
+
|
46 |
+
def generate_ai_response(message):
|
47 |
+
"""Generate AI response using Gemini"""
|
48 |
+
if not model:
|
49 |
+
return "❌ AI service is not available."
|
50 |
|
51 |
try:
|
52 |
+
response = model.generate_content(message)
|
53 |
+
return response.text if response.text else "⚠️ I couldn't generate a reply."
|
54 |
except Exception as e:
|
55 |
+
logger.error(f"Gemini error: {e}")
|
56 |
+
return "❌ Something went wrong while generating response."
|
|
|
|
|
|
|
57 |
|
58 |
+
# ==== ROUTES ====
|
59 |
@app.route("/")
|
60 |
def home():
|
61 |
+
return """
|
62 |
+
<h1>🤖 Telegram AI Chatbot</h1>
|
63 |
+
<p>✅ Bot is running and ready to receive webhooks!</p>
|
64 |
+
<p><strong>Webhook URL:</strong> <code>https://your-space-url.hf.space/webhook/{}</code></p>
|
65 |
+
<p><a href="/health">Health Check</a> | <a href="/set_webhook">Set Webhook</a></p>
|
66 |
+
""".format(TELEGRAM_TOKEN)
|
67 |
|
68 |
@app.route("/health")
|
69 |
def health():
|
70 |
+
return jsonify({
|
71 |
+
"status": "healthy",
|
72 |
+
"gemini_configured": model is not None,
|
73 |
+
"telegram_token_set": bool(TELEGRAM_TOKEN)
|
74 |
+
})
|
75 |
|
76 |
+
@app.route(f"/webhook/{TELEGRAM_TOKEN}", methods=["POST"])
|
77 |
def webhook():
|
78 |
"""Handle incoming updates from Telegram"""
|
79 |
try:
|
80 |
+
update = request.get_json()
|
81 |
+
logger.info(f"Received update: {update}")
|
82 |
+
|
83 |
+
if not update:
|
84 |
+
return "No data received", 400
|
85 |
+
|
86 |
+
# Handle message
|
87 |
+
if "message" in update:
|
88 |
+
message = update["message"]
|
89 |
+
chat_id = message["chat"]["id"]
|
90 |
+
|
91 |
+
# Handle /start command
|
92 |
+
if message.get("text") == "/start":
|
93 |
+
response_text = "👋 Hi! I am Sumit, your AI buddy. How can I help you today?"
|
94 |
+
send_message(chat_id, response_text)
|
95 |
+
return "OK"
|
96 |
+
|
97 |
+
# Handle regular messages
|
98 |
+
if "text" in message:
|
99 |
+
user_message = message["text"]
|
100 |
+
logger.info(f"Processing message from {chat_id}: {user_message}")
|
101 |
+
|
102 |
+
# Generate AI response
|
103 |
+
ai_response = generate_ai_response(user_message)
|
104 |
+
|
105 |
+
# Send response
|
106 |
+
if send_message(chat_id, ai_response):
|
107 |
+
logger.info(f"Response sent successfully to {chat_id}")
|
108 |
+
else:
|
109 |
+
logger.error(f"Failed to send response to {chat_id}")
|
110 |
+
|
111 |
return "OK"
|
112 |
+
|
113 |
except Exception as e:
|
114 |
logger.error(f"Webhook error: {e}")
|
115 |
return "Error", 500
|
116 |
|
117 |
@app.route("/set_webhook", methods=["GET"])
|
118 |
def set_webhook():
|
119 |
+
"""Set up the webhook - call this after deployment"""
|
|
|
120 |
try:
|
121 |
+
# Get the current space URL (you'll need to replace this with your actual space URL)
|
122 |
+
webhook_url = request.host_url.rstrip('/') + f"/webhook/{TELEGRAM_TOKEN}"
|
123 |
+
|
124 |
+
url = f"{TELEGRAM_API_URL}/setWebhook"
|
125 |
+
payload = {
|
126 |
+
'url': webhook_url,
|
127 |
+
'allowed_updates': ['message']
|
128 |
+
}
|
129 |
+
|
130 |
+
response = requests.post(url, json=payload, timeout=10)
|
131 |
+
|
132 |
+
if response.status_code == 200:
|
133 |
+
result = response.json()
|
134 |
+
if result.get('ok'):
|
135 |
+
return f"""
|
136 |
+
<h2>✅ Webhook Set Successfully!</h2>
|
137 |
+
<p><strong>Webhook URL:</strong> {webhook_url}</p>
|
138 |
+
<p><strong>Response:</strong> {result}</p>
|
139 |
+
<p>Your bot is now ready to receive messages!</p>
|
140 |
+
<a href="/">← Back to Home</a>
|
141 |
+
"""
|
142 |
+
else:
|
143 |
+
return f"❌ Failed to set webhook: {result}"
|
144 |
else:
|
145 |
+
return f"❌ HTTP Error: {response.status_code}"
|
146 |
+
|
147 |
except Exception as e:
|
148 |
logger.error(f"Error setting webhook: {e}")
|
149 |
+
return f"❌ Error: {str(e)}"
|
150 |
+
|
151 |
+
@app.route("/webhook_info", methods=["GET"])
|
152 |
+
def webhook_info():
|
153 |
+
"""Get current webhook information"""
|
154 |
+
try:
|
155 |
+
url = f"{TELEGRAM_API_URL}/getWebhookInfo"
|
156 |
+
response = requests.get(url, timeout=10)
|
157 |
+
|
158 |
+
if response.status_code == 200:
|
159 |
+
info = response.json()
|
160 |
+
return f"""
|
161 |
+
<h2>📊 Webhook Information</h2>
|
162 |
+
<pre>{json.dumps(info, indent=2)}</pre>
|
163 |
+
<a href="/">← Back to Home</a>
|
164 |
+
"""
|
165 |
+
else:
|
166 |
+
return f"❌ Error getting webhook info: {response.status_code}"
|
167 |
+
|
168 |
+
except Exception as e:
|
169 |
+
return f"❌ Error: {str(e)}"
|
170 |
+
|
171 |
+
# ==== TEST ROUTE ====
|
172 |
+
@app.route("/test_ai", methods=["GET"])
|
173 |
+
def test_ai():
|
174 |
+
"""Test AI functionality"""
|
175 |
+
test_message = request.args.get('message', 'Hello, how are you?')
|
176 |
+
response = generate_ai_response(test_message)
|
177 |
+
return jsonify({
|
178 |
+
"input": test_message,
|
179 |
+
"output": response,
|
180 |
+
"gemini_available": model is not None
|
181 |
+
})
|
182 |
|
|
|
183 |
if __name__ == "__main__":
|
184 |
+
logger.info("🚀 Starting Telegram Bot Flask App")
|
|
|
|
|
|
|
185 |
app.run(host="0.0.0.0", port=7860, debug=False)
|