机器人的消息发送后,您需要在aigram中接受用户的消息

问题描述 投票:0回答:1

我的机器人发送一条消息,例如“输入要兑换的数量:”,我需要接受用户在此消息之后发送的消息。

我尝试通过“message.text”,但我从用户那里收到了上一条消息,即“Exchange”

@router.message(F.text == "💱 Exchange")
async def exchange(msg: Message):
    State.id = msg.from_user.id
    State.first_name = msg.from_user.first_name
    State.last_name = msg.from_user.last_name
    State.is_premium = msg.from_user.is_premium
    State.is_bot = msg.from_user.is_bot
    await msg.answer('Enter the amount of clicks what u want to exchange to $NOT: 💱')
    need_message = msg.text
    print(need_message)
python-3.x python-telegram-bot aiogram
1个回答
0
投票

您需要使用 aiogram 内置的有限状态机(FSM)

首先要做的事情:配置存储

from aiogram.fsm.storage.memory import MemoryStorage


storage = MemoryStorage()

dp = Dispatcher(storage=storage)

那么你需要创建状态组

from aiogram.fsm.state import State, StatesGroup

class UserState(StatesGroup):
    exchange_amount = State()

那么你需要修改现有的处理程序

from aiogram.fsm.context import FSMContext

@router.message(F.text == "💱 Exchange") # no need to filter state here
async def exchange(msg: Message, state: FSMContext): # adding state var
    State.id = msg.from_user.id
    State.first_name = msg.from_user.first_name
    State.last_name = msg.from_user.last_name
    State.is_premium = msg.from_user.is_premium
    State.is_bot = msg.from_user.is_bot
    await msg.answer('Enter the amount of clicks what u want to exchange to $NOT: 💱')
    need_message = msg.text
    print(need_message)
    await state.set_state(UserState.exchange_amount)

那么你需要一个处理程序来处理不同的状态

@router.message(UserState.exchange_amount)
async def exchange_amount_handler(msg: Message, state: FSMContext):
    amount = msg.text
    ... # do whatever you need
    await state.clear() # clear state to enable main menu options or set another to continue routing

有关状态的更多信息:https://docs.aiogram.dev/en/latest/dispatcher/finite_state_machine/index.html

© www.soinside.com 2019 - 2024. All rights reserved.