python-3.x - 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
解决方案
您应该使用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 的几乎所有内容。
推荐阅读
- javascript - React native check if a passed parameter is a valid color
- xamarin.forms - 模块化应用设计
- r - Why is an elementwise product of a matrix much faster with apply?
- php - 将数据追加到表中的新行
- r - 将对象上的信息存储为该对象的属性是不好还是好的做法?
- arrays - 将值从用户窗体中的 RefEdit 控件传递到变体数组
- javascript - 在不改变原始数组的情况下将数组中的对象相加的算法
- java - 获取 Play 框架的类路径 jar 的最简单方法是什么?
- angular - 为什么在 NgOninit 上更改父母数据不会导致 ExpressionChangedAfterItHasBeenCheckedError?
- twilio - VOIP 通信中正确形成的 200 ACK 响应的格式