Python Telegram Bot 无法从网页小程序接收数据

0 投票
1 回答
129 浏览
提问于 2025-04-14 17:56

我正在用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。

1 个回答

0

这些数据将通过 Message.web_app_data 来获取,而不是通过 Message.text。请使用 filters.StatusUpdate.WEB_APP_DATA 来捕捉这些消息,具体用法可以参考 这个例子


免责声明:我现在是 python-telegram-bot 的维护者。

撰写回答