Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,8 @@
|
|
| 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'
|
|
@@ -14,9 +10,7 @@ os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
|
|
| 14 |
# Configuration
|
| 15 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
| 16 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
| 17 |
-
|
| 18 |
-
POWER_USER_ID = 75516649
|
| 19 |
-
PROXY_URL = 'http://eR3LhYeoZXNWhIp:clIvQ2hSkO5CtLl@107.180.131.170:58874'
|
| 20 |
|
| 21 |
# Initialize the Telegram bot
|
| 22 |
bot = telebot.TeleBot(BOT_TOKEN)
|
|
@@ -84,98 +78,5 @@ iface = gr.Interface(
|
|
| 84 |
live=True
|
| 85 |
)
|
| 86 |
|
| 87 |
-
# Flask app setup
|
| 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/gradio', json={'message': message_text})
|
| 104 |
-
if response.status_code == 200:
|
| 105 |
-
response_text = response.json().get('response', '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(gradio_url):
|
| 123 |
-
"""Sets the webhook for the Telegram bot with proxy configuration."""
|
| 124 |
-
webhook_url = f"{gradio_url}/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_gradio_app():
|
| 165 |
-
"""Launches the Gradio app and sets the Telegram webhook."""
|
| 166 |
-
iface.launch(server_name="0.0.0.0", server_port=7860, debug=True)
|
| 167 |
-
|
| 168 |
-
# Directly set the webhook URL for local testing
|
| 169 |
-
gradio_url = "http://localhost:7860" # Use local URL for testing
|
| 170 |
-
|
| 171 |
-
asyncio.run(set_telegram_webhook(gradio_url)) # Set the webhook for Telegram
|
| 172 |
-
|
| 173 |
-
def run_flask_app():
|
| 174 |
-
"""Launches the Flask app and sets the Telegram webhook."""
|
| 175 |
-
app.run(host="0.0.0.0", port=5000, debug=True)
|
| 176 |
-
|
| 177 |
if __name__ == "__main__":
|
| 178 |
-
#
|
| 179 |
-
loop = asyncio.get_event_loop()
|
| 180 |
-
loop.create_task(run_flask_app())
|
| 181 |
-
run_gradio_app()
|
|
|
|
|
|
|
| 1 |
import telebot
|
| 2 |
import google.generativeai as genai
|
| 3 |
import logging
|
| 4 |
import requests
|
| 5 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Suppress experimental warnings
|
| 8 |
os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
|
|
|
|
| 10 |
# Configuration
|
| 11 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
| 12 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
| 13 |
+
WEBHOOK_URL = f"https://measmonysuon-flyingbird.hf.space/webhooks/handle_update"
|
|
|
|
|
|
|
| 14 |
|
| 15 |
# Initialize the Telegram bot
|
| 16 |
bot = telebot.TeleBot(BOT_TOKEN)
|
|
|
|
| 78 |
live=True
|
| 79 |
)
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
if __name__ == "__main__":
|
| 82 |
+
iface.launch() # Launch the Gradio app
|
|
|
|
|
|
|
|
|