AforativeBot / app.py
measmonysuon's picture
Update app.py
668c19d verified
raw
history blame
3.97 kB
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__)
@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}") # Log the incoming payload
if payload.get('message'):
message_text = payload['message'].get('text')
chat_id = payload['message']['chat']['id']
if message_text:
try:
# Send a static response
static_response = "This is a static response for testing purposes."
asyncio.run(bot_send_message(chat_id, static_response))
logger.info(f"Static 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():
"""Sets the webhook for the Telegram bot with proxy configuration."""
webhook_url = f"https://measmonysuon-flyingbird.hf.space/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.")
# Notify power user
await bot_send_message(POWER_USER_ID, "πŸš€ The webhook has been successfully connected! πŸŽ‰")
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
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}")
def run_flask_app():
"""Launches the Flask app and sets the Telegram webhook."""
asyncio.run(set_telegram_webhook())
app.run(host="0.0.0.0", port=5000, debug=True)
if __name__ == "__main__":
run_flask_app()