Python Telegram Bot无法接收Web Mini App数据求助
Telegram Bot 无法接收 Web Mini App 数据的解决方案
问题描述
我正在开发一款Python Telegram Bot,功能是接收Web Mini App的数据:用户点击小程序按钮后数据发送至Bot,再转发到Discord Webhook。已按官方文档配置Bot与小程序通信,在BotFather中关闭群组消息隐私权限,但点击小程序「Envoyer le texte」按钮后,Bot未接收数据,无报错且handle_message函数未触发。
相关代码如下:
bot.py
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters import logging import json import httpx from datetime import datetime logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) TOKEN = "" DISCORD_WEBHOOK_URL = "" MINI_APP_URL="" # Discord async def send_message_to_discord(order_data): try: async with httpx.AsyncClient() as client: response = await client.post(DISCORD_WEBHOOK_URL, json={"content": json.dumps(order_data, indent=4), "username": "Test Bot"}) logger.info(f"Discord response: Status {response.status_code}, Body {response.text}") except Exception as e: logger.error(f"Failed to send message to Discord: {e}") # /start async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: keyboard = [[InlineKeyboardButton("Commander", web_app=WebAppInfo(url=MINI_APP_URL))]] reply_markup = InlineKeyboardMarkup(keyboard) await context.bot.send_message(chat_id=update.effective_chat.id, text='Welcome', reply_markup=reply_markup) # Mini App data processing async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: message = update.effective_message if message.web_app_data: data = json.loads(message.web_app_data.data) send_message_to_discord(data) else: logger.info("Received a message that doesn't contain web_app_data") # launch app def main(): application = Application.builder().token(TOKEN).build() application.add_handler(CommandHandler("start", start)) application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message)) application.run_polling() if __name__ == '__main__': main()
index.html
<!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>Test Mini App</title> <script src="https://telegram.org/js/telegram-web-app.js"></script> <style> body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; } .container { text-align: center; } input, button { margin-top: 20px; padding: 10px; font-size: 16px; } </style> </head> <body> <div class="container"> <h2>Welcome</h2> <p>Type Text :</p> <input type="text" id="deliveryOption" placeholder="Entrez l'option de livraison ici"> <br> <button id="sendOrder">Envoyer le texte</button> </div> <script> document.addEventListener('DOMContentLoaded', function() { const sendOrderButton = document.getElementById('sendOrder'); const deliveryOption = document.getElementById('deliveryOption'); sendOrderButton.addEventListener('click', function() { const orderData = { delivery: deliveryOption.value.trim(), }; if(orderData.delivery) { // Envoie les données au bot Telegram Telegram.WebApp.sendData(JSON.stringify(orderData)); } else { alert("Veuillez entrer une option de livraison."); } }); Telegram.WebApp.ready(); }); </script> </body> </html>
解决方案
1. 修正消息过滤器类型
Web Mini App发送的数据不属于普通文本消息,原过滤器filters.TEXT & ~filters.COMMAND无法匹配,导致handle_message不触发。需改用专门的Web App数据过滤器:
# 替换原MessageHandler的过滤器 application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, handle_message))
2. 补充异步函数的await关键字
调用异步函数send_message_to_discord时未加await,会导致函数无法正确执行,且异常无法被日志捕获:
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: message = update.effective_message if message.web_app_data: data = json.loads(message.web_app_data.data) await send_message_to_discord(data) # 添加await else: logger.info("Received a message that doesn't contain web_app_data")
3. 验证Mini App域名配置
确认BotFather中已正确配置Web App的域名:
- 发送
/mybots选择目标Bot - 进入
Bot Settings->Web App - 添加部署Mini App的HTTPS域名(localhost仅支持开发测试)
4. 增加日志排查
在handle_message开头添加日志,确认函数是否被触发:
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: logger.info("handle_message function triggered") # 添加日志 message = update.effective_message # 后续代码...
5. 调整Web App初始化顺序
将Telegram.WebApp.ready()移到事件监听前,避免潜在的初始化延迟问题:
document.addEventListener('DOMContentLoaded', function() { const sendOrderButton = document.getElementById('sendOrder'); const deliveryOption = document.getElementById('deliveryOption'); Telegram.WebApp.ready(); // 移到事件监听之前 sendOrderButton.addEventListener('click', function() { const orderData = { delivery: deliveryOption.value.trim(), }; if(orderData.delivery) { Telegram.WebApp.sendData(JSON.stringify(orderData)); } else { alert("Veuillez entrer une option de livraison."); } }); });
内容的提问来源于stack exchange,提问作者HARPONNAIT
相关产品推荐
相关产品推荐

