File size: 6,226 Bytes
21b6b8b
e7c1dd3
028e138
 
c540b1a
21b6b8b
 
 
c540b1a
028e138
21b6b8b
c540b1a
 
028e138
 
21b6b8b
c540b1a
21b6b8b
c540b1a
028e138
 
 
 
 
 
 
21b6b8b
c540b1a
e7c1dd3
c540b1a
028e138
 
21b6b8b
028e138
 
 
 
 
 
 
 
21b6b8b
028e138
 
 
 
 
 
 
611a040
 
028e138
 
611a040
028e138
 
e7c1dd3
028e138
e7c1dd3
 
028e138
 
 
 
 
 
d56de30
e7c1dd3
 
028e138
 
 
 
 
e7c1dd3
028e138
e7c1dd3
 
 
028e138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7c1dd3
028e138
e7c1dd3
 
 
 
 
 
028e138
e7c1dd3
028e138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e7c1dd3
028e138
 
e7c1dd3
 
028e138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c540b1a
611a040
028e138
e7c1dd3
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
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 ====
@app.route("/")
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)

@app.route("/health")
def health():
    return jsonify({
        "status": "healthy",
        "gemini_configured": model is not None,
        "telegram_token_set": bool(TELEGRAM_TOKEN)
    })

@app.route(f"/webhook/{TELEGRAM_TOKEN}", methods=["POST"])
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

@app.route("/set_webhook", methods=["GET"])
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)}"

@app.route("/webhook_info", methods=["GET"])
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 ====
@app.route("/test_ai", methods=["GET"])
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)