【问题标题】:Aiogram waiting user replyAiogram 等待用户回复
【发布时间】:2021-12-19 01:58:30
【问题描述】:
如何在 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.x
async-await
telegram-bot
aiogram
【解决方案1】:
您应该使用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
这就是它的样子:
Official documentation 用于 aiogram FSM 非常糟糕,但 an example 可以帮助您发现 FSM 几乎所有的东西。