import os import logging import httpx import asyncio from flask import Flask, request, jsonify # Configuration BOT_TOKEN = '7484321656:AAExhpS7sOGMu2BCuPQrDjuXpY3sEQmBgfY' WEBHOOK_SECRET = 'A3%26c8%21jP%23xZ1v*Qw5kL%5E0tR%40u9%25yS6' # URL-encoded secret POWER_USER_ID = 75516649 # Proxy Configuration PROXY_URL = 'http://eR3LhYeoZXNWhIp:clIvQ2hSkO5CtLl@107.180.131.170:58874' # Initialize logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('bot_debug.log'), logging.StreamHandler() ] ) logger = logging.getLogger(__name__) app = Flask(__name__) async def bot_send_message(chat_id, text): """Send a message to the specified chat ID using the proxy configuration.""" async with httpx.AsyncClient(proxies=PROXY_URL) as client: response = await client.post( f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage", data={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"} ) if response.status_code == 200: logger.info(f"Message sent successfully to chat_id {chat_id}") else: logger.error(f"Failed to send message: {response.text}") @app.route(f'/webhooks/{WEBHOOK_SECRET}', methods=['POST']) def handle_update(): """Handles incoming updates from Telegram.""" payload = request.json logger.debug(f"Received payload: {payload}") if payload.get('message'): message_text = payload['message'].get('text') chat_id = payload['message']['chat']['id'] if message_text: try: # Forward message to Gradio and get the response async def forward_message(): async with httpx.AsyncClient(proxies=PROXY_URL) as client: response = await client.post( 'http://localhost:7860/', # Gradio app URL json={'text': message_text} ) if response.status_code == 200: response_text = response.json().get('data', 'Error processing request.') else: response_text = 'Error occurred while processing your request.' await bot_send_message(chat_id, response_text) asyncio.run(forward_message()) logger.info(f"Response sent to chat_id {chat_id}") except Exception as e: logger.error(f"Error during processing: {e}") error_message = "Sorry, I can't answer this query right now but I will improve from time to time." asyncio.run(bot_send_message(chat_id, error_message)) logger.error(f"Error message sent to chat_id {chat_id}") return jsonify({'status': 'ok'}), 200 async def set_telegram_webhook(flask_url): """Sets the webhook for the Telegram bot using the provided Flask URL.""" webhook_url = f"{flask_url}/webhooks/{WEBHOOK_SECRET}" retry_attempts = 5 retry_delay = 1 # seconds for attempt in range(retry_attempts): try: async with httpx.AsyncClient(proxies=PROXY_URL) as client: response = await client.post( f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook", data={"url": webhook_url}, ) result = response.json() if result.get('ok'): logger.info("Webhook set successfully.") return elif result.get('error_code') == 429: retry_after = result['parameters'].get('retry_after', retry_delay) logger.warning(f"Rate limit exceeded. Retrying after {retry_after} seconds.") await asyncio.sleep(retry_after) else: logger.error(f"Failed to set webhook: {result}") return except httpx.RequestError as e: logger.error(f"Request exception: {e}") return def run_flask_app(): """Launches the Flask app and sets the Telegram webhook.""" flask_url = "https://your-flask-url.com" # Replace with your actual Flask URL asyncio.run(set_telegram_webhook(flask_url)) # Set the webhook before starting the Flask app app.run(host="0.0.0.0", port=5000, debug=True) if __name__ == "__main__": run_flask_app()