Python Telegram Bot 不接收来自网络迷你应用程序的数据

问题描述 投票:0回答:1

我正在用 Python 开发一个 Telegram 机器人,它必须从网络迷你应用程序接收数据。当用户单击按钮时,迷你应用程序应该向机器人发送数据。 我按照 Telegram 官方文档配置迷你应用程序和机器人以相互通信。我还在 BotFather 中禁用了群组消息隐私,以便机器人可以接收所有消息。

机器人应该打开一个网页,用户将文本放入专用区域,机器人将用户输入的内容发送到 Discord webhook

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>

当用户在小应用程序中单击“Envoyer le texte”时,机器人不会按预期接收数据。没有错误,但是handle_message函数好像没有被触发

我按照官方 Telegram 文档在迷你应用程序和机器人之间建立通信。我在迷你应用程序中使用“Telegram.WebApp.sendData”方法将数据发送到机器人,并将机器人配置为使用带有过滤器的“MessageHandler”监听传入消息,以处理非命令消息。我还通过 BotFather 禁用了群组消息隐私。我还向 ChatGPT 寻求帮助,他告诉我我的代码看起来不错,但不知道该怎么办。

机器人应将用户在

中输入的内容发送至 Discord
python python-3.x telegram telegram-bot python-telegram-bot
1个回答
0
投票

数据将通过

Message.web_app_data
而不是
Message.text
获得。请使用
filters.StatusUpdate.WEB_APP_DATA
捕获这些消息,如 此示例中所示。


免责声明:我目前是

python-telegram-bot
的维护者。

© www.soinside.com 2019 - 2024. All rights reserved.