Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,9 @@ import google.generativeai as genai
|
|
| 4 |
import logging
|
| 5 |
import requests
|
| 6 |
import gradio as gr
|
| 7 |
-
import
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Suppress experimental warnings
|
| 10 |
os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
|
|
@@ -12,7 +14,9 @@ os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
|
|
| 12 |
# Configuration
|
| 13 |
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
| 14 |
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
| 15 |
-
WEBHOOK_SECRET = 'A3
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# Initialize the Telegram bot
|
| 18 |
bot = telebot.TeleBot(BOT_TOKEN)
|
|
@@ -58,62 +62,120 @@ chat_session = model.start_chat(
|
|
| 58 |
]
|
| 59 |
)
|
| 60 |
|
| 61 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
"""Handles incoming updates from Telegram."""
|
|
|
|
|
|
|
|
|
|
| 63 |
if payload.get('message'):
|
| 64 |
message_text = payload['message'].get('text')
|
| 65 |
chat_id = payload['message']['chat']['id']
|
| 66 |
|
| 67 |
if message_text:
|
| 68 |
try:
|
| 69 |
-
#
|
| 70 |
-
|
| 71 |
-
response
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
| 75 |
logger.debug(f"Generated response: {response_text}")
|
| 76 |
-
|
| 77 |
-
# Send the response to the chat
|
| 78 |
-
bot.send_message(chat_id, response_text, parse_mode='Markdown')
|
| 79 |
logger.info(f"Response sent to chat_id {chat_id}")
|
| 80 |
|
| 81 |
except Exception as e:
|
| 82 |
-
logger.error(f"Error during
|
| 83 |
error_message = "Sorry, I can't answer this query right now but I will improve from time to time."
|
| 84 |
-
|
| 85 |
logger.error(f"Error message sent to chat_id {chat_id}")
|
| 86 |
|
| 87 |
-
return '
|
| 88 |
|
| 89 |
-
def set_telegram_webhook(gradio_url):
|
| 90 |
-
"""Sets the webhook for the Telegram bot."""
|
| 91 |
-
webhook_url = f"{gradio_url}/webhooks/
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
logger.info("Webhook set successfully.")
|
| 100 |
else:
|
| 101 |
-
logger.error(f"Failed to
|
| 102 |
-
except requests.exceptions.RequestException as e:
|
| 103 |
-
logger.error(f"Request exception: {e}")
|
| 104 |
|
| 105 |
def run_gradio_app():
|
| 106 |
"""Launches the Gradio app and sets the Telegram webhook."""
|
| 107 |
-
|
| 108 |
-
gr.Textbox(label="Input") # Dummy input component
|
| 109 |
-
gr.Textbox(label="Output") # Dummy output component
|
| 110 |
-
|
| 111 |
-
iface = app.launch(server_name="0.0.0.0", server_port=5000, debug=True)
|
| 112 |
|
| 113 |
# Directly set the webhook URL for local testing
|
| 114 |
-
gradio_url = "http://localhost:
|
| 115 |
|
| 116 |
-
set_telegram_webhook(gradio_url) # Set the webhook for Telegram
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
| 119 |
run_gradio_app()
|
|
|
|
| 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 |
# 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:clIvQ2hSkO5CtLl@107.180.131.170:58874'
|
| 20 |
|
| 21 |
# Initialize the Telegram bot
|
| 22 |
bot = telebot.TeleBot(BOT_TOKEN)
|
|
|
|
| 62 |
]
|
| 63 |
)
|
| 64 |
|
| 65 |
+
def generate_response(user_input):
|
| 66 |
+
"""Generate a response using Google Generative AI."""
|
| 67 |
+
try:
|
| 68 |
+
prompt = f"Respond to the user: {user_input}"
|
| 69 |
+
response = chat_session.send_message(prompt) # Generate response using text and prompt
|
| 70 |
+
response_text = response.text
|
| 71 |
+
return response_text
|
| 72 |
+
except Exception as e:
|
| 73 |
+
logger.error(f"Error during GenAI processing: {e}")
|
| 74 |
+
return "Sorry, I can't answer this query right now but I will improve from time to time."
|
| 75 |
+
|
| 76 |
+
# Define Gradio interface
|
| 77 |
+
def gradio_handle_update(user_input):
|
| 78 |
+
return generate_response(user_input)
|
| 79 |
+
|
| 80 |
+
iface = gr.Interface(
|
| 81 |
+
fn=gradio_handle_update,
|
| 82 |
+
inputs=gr.Textbox(label="User Input"),
|
| 83 |
+
outputs=gr.Textbox(label="Bot Response"),
|
| 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 |
+
# Run Gradio app and Flask app concurrently
|
| 179 |
+
loop = asyncio.get_event_loop()
|
| 180 |
+
loop.create_task(run_flask_app())
|
| 181 |
run_gradio_app()
|