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

使用python-telegram-bot开发Telegram bot时如何实现alert弹窗提示

实现Telegram Bot点击按钮弹出alert弹窗方案

你需要调用Telegram Bot API提供的answerCallbackQuery接口,python-telegram-bot库已经对该接口做了封装,操作非常简单。
你图中展示的模态弹窗效果,只需要将该接口的show_alert参数设置为True即可实现。

适配版本:python-telegram-bot v20.x(当前官方推荐主流版本)

代码示例如下:

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, CommandHandler, CallbackQueryHandler, ContextTypes

# 发送带inline按钮的测试消息
async def send_test_msg(update: Update, context: ContextTypes.DEFAULT_TYPE):
    # 定义回调按钮
    test_keyboard = [
        [InlineKeyboardButton("点击触发alert", callback_data="trigger_alert")]
    ]
    reply_markup = InlineKeyboardMarkup(test_keyboard)
    await update.message.reply_text("点击下方按钮测试弹窗效果:", reply_markup=reply_markup)

# 处理按钮点击回调,返回alert弹窗
async def alert_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    callback = update.callback_query
    # 核心应答逻辑
    await callback.answer(
        text="你要的alert弹窗内容\n支持换行展示,最多200字符",
        show_alert=True
    )

if __name__ == "__main__":
    # 替换为你自己的机器人token
    bot = ApplicationBuilder().token("YOUR_BOT_TOKEN").build()
    bot.add_handler(CommandHandler("test", send_test_msg))
    bot.add_handler(CallbackQueryHandler(alert_callback))
    bot.run_polling()

适配版本:python-telegram-bot v13.x(旧版本)

代码示例如下:

from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext

def send_test_msg(update: Update, context: CallbackContext):
    test_keyboard = [
        [InlineKeyboardButton("点击触发alert", callback_data="trigger_alert")]
    ]
    reply_markup = InlineKeyboardMarkup(test_keyboard)
    update.message.reply_text("点击下方按钮测试弹窗效果:", reply_markup=reply_markup)

def alert_callback(update: Update, context: CallbackContext):
    callback = update.callback_query
    callback.answer(
        text="你要的alert弹窗内容\n支持换行展示,最多200字符",
        show_alert=True
    )

if __name__ == "__main__":
    updater = Updater("YOUR_BOT_TOKEN")
    updater.dispatcher.add_handler(CommandHandler("test", send_test_msg))
    updater.dispatcher.add_handler(CallbackQueryHandler(alert_callback))
    updater.start_polling()
    updater.idle()

关键参数说明

  • text:弹窗中展示的文本内容,最多支持200个字符,超出部分会被自动截断
  • show_alert:布尔值,设为True时弹出需要用户手动点击确认的模态弹窗(就是你要的效果),设为False时仅展示顶部临时toast提示

注意事项

每个用户点击触发的回调请求必须调用一次answer方法,否则按钮会一直显示加载状态,30秒后Telegram会自动返回操作失败提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:57:05