Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,14 +1,22 @@
|
|
|
|
1 |
import telebot
|
2 |
import google.generativeai as genai
|
3 |
import logging
|
4 |
import requests
|
5 |
import gradio as gr
|
|
|
|
|
|
|
6 |
|
|
|
|
|
7 |
|
8 |
# Configuration
|
9 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
10 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
11 |
-
|
|
|
|
|
12 |
|
13 |
# Initialize the Telegram bot
|
14 |
bot = telebot.TeleBot(BOT_TOKEN)
|
@@ -76,5 +84,92 @@ iface = gr.Interface(
|
|
76 |
live=True
|
77 |
)
|
78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
if __name__ == "__main__":
|
80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
import telebot
|
3 |
import google.generativeai as genai
|
4 |
import logging
|
5 |
import requests
|
6 |
import gradio as gr
|
7 |
+
import httpx
|
8 |
+
import asyncio
|
9 |
+
from flask import Flask, request, jsonify
|
10 |
|
11 |
+
# Suppress experimental warnings
|
12 |
+
os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
|
13 |
|
14 |
# Configuration
|
15 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
16 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
17 |
+
WEBHOOK_SECRET = 'A3%26c8%21jP%23xZ1v*Qw5kL%5E0tR%40u9%25yS6' # URL-encoded secret
|
18 |
+
POWER_USER_ID = 75516649
|
19 |
+
PROXY_URL = 'http://eR3LhYeoZXNWhIp:[email protected]:58874'
|
20 |
|
21 |
# Initialize the Telegram bot
|
22 |
bot = telebot.TeleBot(BOT_TOKEN)
|
|
|
84 |
live=True
|
85 |
)
|
86 |
|
87 |
+
# Initialize Flask app
|
88 |
+
app = Flask(__name__)
|
89 |
+
|
90 |
+
@app.route(f'/webhooks/{WEBHOOK_SECRET}', methods=['POST'])
|
91 |
+
def handle_update():
|
92 |
+
"""Handles incoming updates from Telegram."""
|
93 |
+
payload = request.json
|
94 |
+
logger.debug(f"Received payload: {payload}") # Log the incoming payload
|
95 |
+
|
96 |
+
if payload.get('message'):
|
97 |
+
message_text = payload['message'].get('text')
|
98 |
+
chat_id = payload['message']['chat']['id']
|
99 |
+
|
100 |
+
if message_text:
|
101 |
+
try:
|
102 |
+
# Forward message to Gradio and get the response
|
103 |
+
response = requests.post('http://localhost:7860/', json={'text': message_text})
|
104 |
+
if response.status_code == 200:
|
105 |
+
response_text = response.json().get('data', 'Sorry, I cannot process this request.')
|
106 |
+
else:
|
107 |
+
response_text = 'Error occurred while processing your request.'
|
108 |
+
|
109 |
+
# Log and send the response
|
110 |
+
logger.debug(f"Generated response: {response_text}")
|
111 |
+
asyncio.run(bot_send_message(chat_id, response_text))
|
112 |
+
logger.info(f"Response sent to chat_id {chat_id}")
|
113 |
+
|
114 |
+
except Exception as e:
|
115 |
+
logger.error(f"Error during processing: {e}")
|
116 |
+
error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
|
117 |
+
asyncio.run(bot_send_message(chat_id, error_message))
|
118 |
+
logger.error(f"Error message sent to chat_id {chat_id}")
|
119 |
+
|
120 |
+
return jsonify({'status': 'ok'}), 200
|
121 |
+
|
122 |
+
async def set_telegram_webhook():
|
123 |
+
"""Sets the webhook for the Telegram bot with proxy configuration."""
|
124 |
+
webhook_url = f"https://measmonysuon-flyingbird.hf.space/webhooks/{WEBHOOK_SECRET}"
|
125 |
+
retry_attempts = 5
|
126 |
+
retry_delay = 1 # seconds
|
127 |
+
|
128 |
+
for attempt in range(retry_attempts):
|
129 |
+
try:
|
130 |
+
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
131 |
+
response = await client.post(
|
132 |
+
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
|
133 |
+
data={"url": webhook_url},
|
134 |
+
)
|
135 |
+
result = response.json()
|
136 |
+
if result.get('ok'):
|
137 |
+
logger.info("Webhook set successfully.")
|
138 |
+
# Notify power user
|
139 |
+
await bot_send_message(POWER_USER_ID, "🚀 The webhook has been successfully connected! 🎉")
|
140 |
+
return
|
141 |
+
elif result.get('error_code') == 429:
|
142 |
+
retry_after = result['parameters'].get('retry_after', retry_delay)
|
143 |
+
logger.warning(f"Rate limit exceeded. Retrying after {retry_after} seconds.")
|
144 |
+
await asyncio.sleep(retry_after)
|
145 |
+
else:
|
146 |
+
logger.error(f"Failed to set webhook: {result}")
|
147 |
+
return
|
148 |
+
except httpx.RequestError as e:
|
149 |
+
logger.error(f"Request exception: {e}")
|
150 |
+
return
|
151 |
+
|
152 |
+
async def bot_send_message(chat_id, text):
|
153 |
+
"""Send a message to the specified chat ID using the proxy configuration."""
|
154 |
+
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
155 |
+
response = await client.post(
|
156 |
+
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
|
157 |
+
data={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
|
158 |
+
)
|
159 |
+
if response.status_code == 200:
|
160 |
+
logger.info(f"Message sent successfully to chat_id {chat_id}")
|
161 |
+
else:
|
162 |
+
logger.error(f"Failed to send message: {response.text}")
|
163 |
+
|
164 |
+
def run_flask_app():
|
165 |
+
"""Launches the Flask app and sets the Telegram webhook."""
|
166 |
+
asyncio.run(set_telegram_webhook())
|
167 |
+
app.run(host="0.0.0.0", port=5000, debug=True)
|
168 |
+
|
169 |
if __name__ == "__main__":
|
170 |
+
# Launch the Gradio app in a separate thread/process
|
171 |
+
import threading
|
172 |
+
threading.Thread(target=iface.launch, kwargs={'server_name': '0.0.0.0', 'server_port': 7860}).start()
|
173 |
+
|
174 |
+
# Start Flask app
|
175 |
+
run_flask_app()
|