1

How can I do this: I got my tgbot using aiogram and I need this bot to handle replied messages. For example: A user in chat replied some message and the bot should handle the users message and also the message that user replied.

I've tried:

@dp.message_handler(lambda message: message.chat.id == chat_id, commands='add')
async def add_to_db(message: types.Message, state: FSMContext):
    await bot.send_message(message.chat.id, 'Сейчас добавлю')
    await bot.send_message(message.chat.id, message.text)
    await state.finish()

That code reacts to command 'add', and I need the bot to learn which message was replied with this command.

Javad
  • 2,033
  • 3
  • 13
  • 23
Artem
  • 13
  • 1
  • 4

1 Answers1

2

types.Message has attribute reply_to_message and it is types.Message object too:

@dp.message_handler(lambda message: message.chat.id == chat_id, commands='add')
async def add_to_db(message: types.Message, state: FSMContext):

    # message.reply_to_message is a types.Message object too
    try:
        msg = message.reply_to_message.text # if replied
    except AttributeError:
        msg = 'not replied'
    
    await message.answer(f'Replied message text: {msg}')
    await message.answer(f'Message text: {message.text}')
    await state.finish()
Maksim K.
  • 156
  • 5
  • Thank you so mutch, that solved my problem – Artem Apr 06 '22 at 15:04
  • 1
    You could mark my answer as "Accepted" – Maksim K. Apr 06 '22 at 15:19
  • 1
    Better check `message.reply_to_message` for `None` instead of catching `AttributeError`. Imagine some time you may misspell an attribute like `text` as `txet` and won't find an error because of this `except AttributeError`. – evgfilim1 Apr 06 '22 at 19:08