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

如何在循环中暂停发送消息,等待用户点击InlineKeyboardButton

实现aiogram中暂停发送等待用户点击「Next result」按钮的功能

核心思路是将ID列表分批发送,每批发送完成后显示「Next result」按钮,用户点击后触发回调事件继续发送下一批,同时用字典记录每个用户的发送进度。

步骤1:定义进度存储结构

用字典临时存储用户的发送进度(生产环境建议用数据库或会话存储):

user_progress = {}  # 键为用户ID,值为当前发送到的ID索引

步骤2:处理用户输入并初始化发送

当用户提交ID列表后,初始化进度并发送第一批内容:

@dp.message_handler(content_types=types.ContentTypes.TEXT)
async def handle_id_input(message: types.Message):
    # 从用户消息中提取ID列表,这里模拟示例数据
    id_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    batch_size = 3  # 每次发送3个ID,可按需调整
    user_id = message.from_user.id

    # 初始化用户进度
    user_progress[user_id] = 0
    # 发送第一批结果
    await send_batch(user_id, id_list, batch_size, message.bot)

步骤3:编写批次发送函数

负责构造消息内容和按钮,发送指定批次的ID:

async def send_batch(user_id, id_list, batch_size, bot):
    current_idx = user_progress[user_id]
    end_idx = min(current_idx + batch_size, len(id_list))
    current_ids = id_list[current_idx:end_idx]

    # 构造发送文本
    text = "当前结果:\n" + "\n".join(map(str, current_ids))

    # 构造Inline键盘
    keyboard = InlineKeyboardMarkup()
    # 如果还有未发送的ID,显示Next按钮
    if end_idx < len(id_list):
        keyboard.add(InlineKeyboardButton(
            "Next result",
            callback_data=f"next_batch_{user_id}_{end_idx}"
        ))

    # 发送消息
    await bot.send_message(user_id, text, reply_markup=keyboard)

    # 更新用户进度
    user_progress[user_id] = end_idx

步骤4:处理按钮点击回调

监听「Next result」按钮的点击事件,触发下一批发送:

@dp.callback_query_handler(lambda c: c.data.startswith("next_batch_"))
async def handle_next_batch(callback_query: types.CallbackQuery):
    # 解析回调数据
    data_parts = callback_query.data.split("_")
    user_id = int(data_parts[2])
    next_idx = int(data_parts[3])

    # 这里需获取对应用户的ID列表,生产环境建议从数据库/会话中读取
    id_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    batch_size = 3

    # 更新进度并发送下一批
    user_progress[user_id] = next_idx
    await send_batch(user_id, id_list, batch_size, callback_query.bot)

    # 结束按钮加载状态
    await callback_query.answer()

关键注意点

  • 多用户场景下,user_progress字典能保证各用户进度独立,生产环境推荐改用Redis或数据库存储
  • batch_size可根据消息长度限制调整,避免单条消息过长
  • 必须调用callback_query.answer(),否则用户点击按钮后会一直显示加载状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:18:18