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

aiogram框架中如何实现等待用户回复的功能?

aiogram框架等待用户回复的实现方案

aiogram主要有两种实现等待用户回复的方式,不同版本写法有差异:

方案1:状态机实现(全版本支持,官方推荐)

适合所有场景,尤其是多步骤收集信息的流程,逻辑清晰不容易出问题。

aiogram 2.x 示例

  1. 先定义状态类并配置存储
from aiogram import Bot, Dispatcher, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup

# 定义状态组
class Form(StatesGroup):
    waiting_for_name = State() # 等待用户输入姓名的状态

# 初始化时绑定存储,状态才会生效
storage = MemoryStorage()
bot = Bot(token="你的机器人TOKEN")
dp = Dispatcher(bot, storage=storage)
  1. 编写触发逻辑和接收逻辑
@dp.message_handler(commands=["start"])
async def start(message: types.Message):
    await message.reply("Send me your name")
    # 切换到等待姓名的状态,后续用户的消息会优先交给对应状态的handler处理
    await Form.waiting_for_name.set()

# 处理等待姓名状态下的用户消息
@dp.message_handler(state=Form.waiting_for_name)
async def process_name(message: types.Message, state: FSMContext):
    # 直接从message.text获取用户输入的姓名
    name = message.text
    await message.reply(f"你好,{name}!")
    # 处理完成后结束状态,如果需要保留数据可以用state.update_data存储
    await state.finish()

aiogram 3.x 示例

3.x版本取消了旧的handler装饰器,状态机写法有小幅调整:

from aiogram import Bot, Dispatcher, types, F
from aiogram.filters import Command
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.context import FSMContext
from aiogram.fsm.storage.memory import MemoryStorage

class Form(StatesGroup):
    waiting_for_name = State()

storage = MemoryStorage()
dp = Dispatcher(storage=storage)
bot = Bot(token="你的机器人TOKEN")

@dp.message(Command("start"))
async def start(message: types.Message, state: FSMContext):
    await message.answer("Send me your name")
    await state.set_state(Form.waiting_for_name)

# 加F.text过滤只接收文本消息,避免用户发图片/语音等内容时报错
@dp.message(Form.waiting_for_name, F.text)
async def process_name(message: types.Message, state: FSMContext):
    name = message.text
    await message.answer(f"你好,{name}!")
    await state.clear() # 清空状态

方案2:next_step_handler 实现(仅aiogram 2.x支持)

适合简单的单步等待场景,代码更轻量化:

@dp.message_handler(commands=["start"])
async def start(message: types.Message):
    await message.reply("Send me your name")
    # 注册下一条消息的处理函数,用户接下来发的内容会直接传给process_name
    dp.register_next_step_handler(message, process_name)

async def process_name(message: types.Message):
    name = message.text
    await message.reply(f"你好,{name}!")

注意事项

  • 内存存储仅适合测试用,生产环境如果需要重启不丢失状态,可以替换成Redis存储
  • 可以给处理用户输入的handler加过滤器,限制只能接收特定类型的内容,避免异常

内容的提问来源于stack exchange,提问作者V-MazOriginal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:39:03