Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,11 +25,23 @@ logger = logging.getLogger(__name__)
|
|
| 25 |
|
| 26 |
app = Flask(__name__)
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
@app.route(f'/webhooks/{WEBHOOK_SECRET}', methods=['POST'])
|
| 29 |
def handle_update():
|
| 30 |
"""Handles incoming updates from Telegram."""
|
| 31 |
payload = request.json
|
| 32 |
-
logger.debug(f"Received payload: {payload}")
|
| 33 |
|
| 34 |
if payload.get('message'):
|
| 35 |
message_text = payload['message'].get('text')
|
|
@@ -37,9 +49,8 @@ def handle_update():
|
|
| 37 |
|
| 38 |
if message_text:
|
| 39 |
try:
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
asyncio.run(bot_send_message(chat_id, static_response))
|
| 43 |
logger.info(f"Static response sent to chat_id {chat_id}")
|
| 44 |
|
| 45 |
except Exception as e:
|
|
@@ -50,20 +61,8 @@ def handle_update():
|
|
| 50 |
|
| 51 |
return jsonify({'status': 'ok'}), 200
|
| 52 |
|
| 53 |
-
async def delete_webhook():
|
| 54 |
-
"""Deletes any existing webhook."""
|
| 55 |
-
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
| 56 |
-
response = await client.post(f"https://api.telegram.org/bot{BOT_TOKEN}/deleteWebhook")
|
| 57 |
-
result = response.json()
|
| 58 |
-
if result.get('ok'):
|
| 59 |
-
logger.info("Existing webhook deleted.")
|
| 60 |
-
else:
|
| 61 |
-
logger.error(f"Failed to delete existing webhook: {result}")
|
| 62 |
-
|
| 63 |
async def set_telegram_webhook():
|
| 64 |
"""Sets the webhook for the Telegram bot with proxy configuration."""
|
| 65 |
-
await delete_webhook() # Delete existing webhook before setting a new one
|
| 66 |
-
|
| 67 |
webhook_url = f"https://measmonysuon-flyingbird.hf.space/webhooks/{WEBHOOK_SECRET}"
|
| 68 |
retry_attempts = 5
|
| 69 |
retry_delay = 1 # seconds
|
|
@@ -78,8 +77,6 @@ async def set_telegram_webhook():
|
|
| 78 |
result = response.json()
|
| 79 |
if result.get('ok'):
|
| 80 |
logger.info("Webhook set successfully.")
|
| 81 |
-
# Notify power user
|
| 82 |
-
await bot_send_message(POWER_USER_ID, "🚀 The webhook has been successfully connected! 🎉")
|
| 83 |
return
|
| 84 |
elif result.get('error_code') == 429:
|
| 85 |
retry_after = result['parameters'].get('retry_after', retry_delay)
|
|
@@ -92,21 +89,9 @@ async def set_telegram_webhook():
|
|
| 92 |
logger.error(f"Request exception: {e}")
|
| 93 |
return
|
| 94 |
|
| 95 |
-
async def bot_send_message(chat_id, text):
|
| 96 |
-
"""Send a message to the specified chat ID using the proxy configuration."""
|
| 97 |
-
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
| 98 |
-
response = await client.post(
|
| 99 |
-
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
|
| 100 |
-
data={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
|
| 101 |
-
)
|
| 102 |
-
if response.status_code == 200:
|
| 103 |
-
logger.info(f"Message sent successfully to chat_id {chat_id}")
|
| 104 |
-
else:
|
| 105 |
-
logger.error(f"Failed to send message: {response.text}")
|
| 106 |
-
|
| 107 |
def run_flask_app():
|
| 108 |
"""Launches the Flask app and sets the Telegram webhook."""
|
| 109 |
-
asyncio.run(set_telegram_webhook())
|
| 110 |
app.run(host="0.0.0.0", port=5000, debug=True)
|
| 111 |
|
| 112 |
if __name__ == "__main__":
|
|
|
|
| 25 |
|
| 26 |
app = Flask(__name__)
|
| 27 |
|
| 28 |
+
async def bot_send_message(chat_id, text):
|
| 29 |
+
"""Send a message to the specified chat ID using the proxy configuration."""
|
| 30 |
+
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
| 31 |
+
response = await client.post(
|
| 32 |
+
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
|
| 33 |
+
data={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
|
| 34 |
+
)
|
| 35 |
+
if response.status_code == 200:
|
| 36 |
+
logger.info(f"Message sent successfully to chat_id {chat_id}")
|
| 37 |
+
else:
|
| 38 |
+
logger.error(f"Failed to send message: {response.text}")
|
| 39 |
+
|
| 40 |
@app.route(f'/webhooks/{WEBHOOK_SECRET}', methods=['POST'])
|
| 41 |
def handle_update():
|
| 42 |
"""Handles incoming updates from Telegram."""
|
| 43 |
payload = request.json
|
| 44 |
+
logger.debug(f"Received payload: {payload}")
|
| 45 |
|
| 46 |
if payload.get('message'):
|
| 47 |
message_text = payload['message'].get('text')
|
|
|
|
| 49 |
|
| 50 |
if message_text:
|
| 51 |
try:
|
| 52 |
+
response_text = "This is a static response for testing purposes."
|
| 53 |
+
asyncio.run(bot_send_message(chat_id, response_text))
|
|
|
|
| 54 |
logger.info(f"Static response sent to chat_id {chat_id}")
|
| 55 |
|
| 56 |
except Exception as e:
|
|
|
|
| 61 |
|
| 62 |
return jsonify({'status': 'ok'}), 200
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
async def set_telegram_webhook():
|
| 65 |
"""Sets the webhook for the Telegram bot with proxy configuration."""
|
|
|
|
|
|
|
| 66 |
webhook_url = f"https://measmonysuon-flyingbird.hf.space/webhooks/{WEBHOOK_SECRET}"
|
| 67 |
retry_attempts = 5
|
| 68 |
retry_delay = 1 # seconds
|
|
|
|
| 77 |
result = response.json()
|
| 78 |
if result.get('ok'):
|
| 79 |
logger.info("Webhook set successfully.")
|
|
|
|
|
|
|
| 80 |
return
|
| 81 |
elif result.get('error_code') == 429:
|
| 82 |
retry_after = result['parameters'].get('retry_after', retry_delay)
|
|
|
|
| 89 |
logger.error(f"Request exception: {e}")
|
| 90 |
return
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
def run_flask_app():
|
| 93 |
"""Launches the Flask app and sets the Telegram webhook."""
|
| 94 |
+
asyncio.run(set_telegram_webhook()) # Set the webhook before starting the Flask app
|
| 95 |
app.run(host="0.0.0.0", port=5000, debug=True)
|
| 96 |
|
| 97 |
if __name__ == "__main__":
|