Getting Started with Aiogram 3: A Comprehensive Guide

Getting Started with Aiogram 3: A Comprehensive Guide

Getting Started with Aiogram 3: A Comprehensive Guide

Introduction

Aiogram 3 is a powerful and asynchronous Python framework for building Telegram bots. It simplifies bot development by providing a clean and structured API with support for middlewares, filters, state management, and more.

In this guide, we'll explore how to install and use Aiogram 3, covering essential topics such as command handling, message processing, state management, and webhook deployment. We'll also provide links to official documentation and other useful resources.


1. Installation

To install Aiogram 3, run the following command:

pip install -U aiogram

Additionally, you may need aiohttp and python-dotenv for handling webhooks and environment variables:

pip install aiohttp python-dotenv

πŸ”— Official documentation: https://docs.aiogram.dev/en/latest/


2. Setting Up a Basic Bot

Create a new Python script (e.g., bot.py) and initialize your bot:

import asyncio
from aiogram import Bot, Dispatcher
from aiogram.types import Message
from aiogram.filters import Command
from aiogram.enums import ParseMode

TOKEN = "YOUR_BOT_TOKEN"

bot = Bot(token=TOKEN, parse_mode=ParseMode.HTML)
dp = Dispatcher()

@dp.message(Command("start"))
async def start_command(message: Message):
    await message.answer("Hello! I am your Aiogram 3 bot.")

async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

Replace YOUR_BOT_TOKEN with your actual Telegram bot token, which you can get from @BotFather.


3. Handling Messages and Commands

Text Message Handler

@dp.message()
async def echo(message: Message):
    await message.answer(f"You said: {message.text}")

Adding More Commands

@dp.message(Command("help"))
async def help_command(message: Message):
    await message.answer("Use /start to begin and /help to see this message.")

4. State Management with FSM (Finite State Machine)

Aiogram 3 provides built-in state management for handling user interactions.

Installing Required Dependencies

pip install aiogram[redis]

Example: Collecting User Data in Steps

from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import State, StatesGroup

class Form(StatesGroup):
    name = State()
    age = State()

@dp.message(Command("register"))
async def start_register(message: Message, state: FSMContext):
    await message.answer("What's your name?")
    await state.set_state(Form.name)

@dp.message(Form.name)
async def process_name(message: Message, state: FSMContext):
    await state.update_data(name=message.text)
    await message.answer("How old are you?")
    await state.set_state(Form.age)

@dp.message(Form.age)
async def process_age(message: Message, state: FSMContext):
    user_data = await state.get_data()
    await message.answer(f"Registration complete! Name: {user_data['name']}, Age: {message.text}")
    await state.clear()

5. Webhooks: Deploying the Bot

Setting Up Webhook

If you want to use webhooks instead of long polling, follow these steps:

from aiogram.webhook.aiohttp_server import SimpleRequestHandler
from aiohttp import web

WEBHOOK_URL = "https://yourdomain.com/webhook"

async def on_startup():
    await bot.set_webhook(WEBHOOK_URL)

async def on_shutdown():
    await bot.delete_webhook()

app = web.Application()
SimpleRequestHandler(dp, bot).register(app, path="/webhook")

web.run_app(app, host="0.0.0.0", port=8000)

πŸ”— Webhook documentation: https://docs.aiogram.dev/en/latest/webhook/


6. Deploying the Bot to a Server

Popular hosting options include:

Example for running the bot in the background using screen:

screen -S aiogram_bot
python bot.py

πŸ”— Guide for deploying with Docker: https://docs.aiogram.dev/en/latest/docker/


7. Additional Resources

Here are some useful links for Aiogram 3 development:


Conclusion

Aiogram 3 provides a powerful way to build Telegram bots efficiently using Python. With its clean API, robust state management, and webhook support, it's an excellent choice for developers looking to create scalable and efficient bots.

If you have any questions or need further guidance, check out the official Aiogram documentation and community channels. πŸš€