首页 > 解决方案 > Aiogram 等待用户回复

问题描述

我如何在 iagram 上写等待用户回复?它需要像:

#!python3
@dp.message_handler(commands["start"]):
async def start(message: types.Message):
    bot.reply("Send me your name")
    name = #Here need func that will await message

标签: python-3.xasync-awaittelegram-botaiogram

解决方案


您应该使用FSM,这是 aiogram 的内置功能。

您的案例示例:

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


bot = Bot(token='BOT TOKEN HERE')

# Don't forget to use storage, otherwise answers won't be saved.
# You can find all supported storages here:
# https://github.com/aiogram/aiogram/tree/dev-2.x/aiogram/contrib/fsm_storage
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)


class Form(StatesGroup):
    name = State()


@dp.message_handler(commands=['start'])
async def start(message: types.Message):
    """Conversation entrypoint"""

    # Set state
    await Form.name.set()
    await message.reply("Send me your name")


# You can use state='*' if you want to handle all states
@dp.message_handler(state='*', commands=['cancel'])
async def cancel_handler(message: types.Message, state: FSMContext):
    """Allow user to cancel action via /cancel command"""

    current_state = await state.get_state()
    if current_state is None:
        # User is not in any state, ignoring
        return

    # Cancel state and inform user about it
    await state.finish()
    await message.reply('Cancelled.')


@dp.message_handler(state=Form.name)
async def process_name(message: types.Message, state: FSMContext):
    """Process user name"""

    # Finish our conversation
    await state.finish()
    await message.reply(f"Hello, {message.text}")  # <-- Here we get the name

这就是它的样子:

上面的代码在行动

aiogram FSM 的官方文档非常糟糕,但有一个示例可以帮助您发现 FSM 的几乎所有内容。


推荐阅读