You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram Mini App无法向Bot传数据:内联按钮适配疑问

问题:Telegram Mini App 通过内联按钮启动后无法向Bot传输数据

我使用python-telegram-bot库开发Telegram Bot并对接Mini App,目前小程序可正常启动且能接收Bot发送的数据,但反向传输出现问题:小程序中调用tg.sendData后,Bot中的消息处理器未触发。

更新:我研究了多个Mini App示例,发现将InlineKeyboardButton替换为KeyboardButton、InlineKeyboardMarkup替换为ReplyKeyboardMarkup后,数据传输恢复正常。这是否意味着InlineKeyboardButton无法用于启动Mini App?但我见过部分Bot使用InlineKeyboardButton启动Mini App,是否需要额外配置才能让内联按钮实现数据传输?

Bot代码

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters
from telegram_token import TELEGRAM_TOKEN


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [
        [InlineKeyboardButton(
            "🕒 Set time",
            web_app=WebAppInfo(url="https://testsite.com/time-widget/test.html?time=9:33")
        )]
    ]

    await update.message.reply_text(
        "Press this button to set time:",
        reply_markup=InlineKeyboardMarkup(keyboard)
    )


async def handle_web_app_data(update: Update, context: ContextTypes.DEFAULT_TYPE):
    data = update.message.web_app_data.data
    await update.message.reply_text(f"Received data: {data}")


def main():
    application = Application.builder().token(TELEGRAM_TOKEN).build()

    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, handle_web_app_data))

    application.run_polling()


if __name__ == "__main__":
    main()

Mini App代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Time Picker</title>
  <script src="https://telegram.org/js/telegram-web-app.js?56"></script>
</head>
<body>
    <button id="sendTimeBtn">Send current time</button>

    <script>
        const tg = window.Telegram?.WebApp;
        
        function sendTime() {
            if (!tg) {
                alert('Works only in Telegram!');
                return;
            }
            
            // Get the current time
            const now = new Date();
            const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
            
            tg.sendData(`time:${time}`);
            
            tg.close();
        }

        if (tg) {
            tg.ready();
            document.getElementById('sendTimeBtn').addEventListener('click', sendTime);
        } else {
            document.body.innerHTML = '<p>Launch in Telegram!</p>';
        }
    </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Andrey Epifantsev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:42:36