Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To transform a serverless EVENT into types.Update in aiogram 3, follow these steps:

  1. First, import the necessary modules:
from aiogram.dispatcher import FSMContext
from aiogram.types import Message, CallbackQuery, InlineQuery, ChosenInlineResult, \
    Poll, PollAnswer, PreCheckoutQuery, ShippingQuery, ContentType, ChatActions
  1. Create a function to handle the EVENT:
async def handle_event(event):
    # handle the event here
  1. Inside the function, check the type of the event and create a corresponding types.Update instance:
async def handle_event(event):
    if event.type == "message":
        message = Message(**event.object)
        update = types.Update(message=message)
    elif event.type == "callback_query":
        callback_query = CallbackQuery(**event.object)
        update = types.Update(callback_query=callback_query)
    elif event.type == "inline_query":
        inline_query = InlineQuery(**event.object)
        update = types.Update(inline_query=inline_query)
    elif event.type == "chosen_inline_result":
        chosen_inline_result = ChosenInlineResult(**event.object)
        update = types.Update(chosen_inline_result=chosen_inline_result)
    elif event.type == "poll":
        poll = Poll(**event.object)
        update = types.Update(poll=poll)
    elif event.type == "poll_answer":
        poll_answer = PollAnswer(**event.object)
        update = types.Update(poll_answer=poll_answer)
    elif event.type == "pre_checkout_query":
        pre_checkout_query = PreCheckoutQuery(**event.object)
        update = types.Update(pre_checkout_query=pre_checkout_query)
    elif event.type == "shipping_query":
        shipping_query = ShippingQuery(**event.object)
        update = types.Update(shipping_query=shipping_query)
    elif event.type == "content_type":
        content_type = ContentType(**event.object)
        update = types.Update(content_type=content_type)
    elif event.type == "chat_actions":
        chat_actions = ChatActions(**event.object)
        update = types.Update(chat_actions=chat_actions)
  1. Once you have created the types.Update instance, you can pass it to your aiogram handlers:
from aiogram import Bot, Dispatcher

bot = Bot(token="YOUR_TOKEN")
dp = Dispatcher(bot)

@dp.message_handler()
async def handle_message(update: types.Update, state: FSMContext):
    message = update.message
    chat_id = message.chat.id
    text = message.text
    await bot.send_message(chat_id=chat_id, text=f"You said: {text}")

Note: This is just an example of how to handle a message using types.Update. Depending on your application, you may need to handle other types of events as well.