TG Bot Webapp sendData 无法返回 Bot 问题
在优化图床机器人登录环节,使用Webapp获取Token后通过sendData传回Bot实现登录。如图:
问题
环境:Python Telegram Bot v20+
Python Bot 端:
# 添加登录按钮
login_url = "xxxxxxx" # web 登录地址
inline_buttons = [[InlineKeyboardButton("🔐 登录", url=login_url)]]
await update.message.reply_text("⭐️ 请先登录,点击下方“🔐 登录”按钮", reply_markup=InlineKeyboardMarkup(inline_buttons))# 添加处理器
app.add_handler(MessageHandler(filters.StatusUpdate.WEB_APP_DATA, handle_webapp_data))# 处理返回 webapp data
async def handle_webapp_data(update: Update, context: ContextTypes.DEFAULT_TYPE):
# 处理登录返回数据逻辑WebAPP 端:
// 仅部分代码
<script>
tg.sendData(JSON.stringify(payload));
</script>使用浏览器Dev Tool发现sendData成功调用,在Bot的handle_webapp_data中添加Log输出发现:
$$ 竟然一点输出都没有 $$
于是查阅了一番,在Stack Overflow上找到了答案
原来sendData不支持InlineKeyboardButton,仅支持KeyboardButton
上方的登录按钮为InlineKeyboardButton,而下方的为KeyboardButton
解决方案
将登录按钮更换为KeyboardButton即可
# WEB_LOGIN_BASE 是登录web地址
web_info = WebAppInfo(url=WEB_LOGIN_BASE)
kb_button = KeyboardButton("🔐 登录", web_app=web_info)
reply_markup = ReplyKeyboardMarkup([[kb_button]], resize_keyboard=True, one_time_keyboard=True)
await update.message.reply_text("⭐ 请先登录,点击下方“🔐 登录”按钮", reply_markup=reply_markup) 当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »