Learn Coding
56 subscribers
21 links
Download Telegram
📌 Your First Bot — Full Code

import asyncio
from aiogram import Bot, Dispatcher
from aiogram.types import Message
from aiogram.filters import Command
import os
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")

bot = Bot(token=TOKEN)
dp = Dispatcher()

@dp.message(Command("start"))
async def start_handler(message: Message):
await message.answer(f"Hello {message.from_user.first_name}! I am alive!")

@dp.message(Command("help"))
async def help_handler(message: Message):
await message.answer("I am a bot. Send me a message and I will echo it back.")

@dp.message()
async def echo_handler(message: Message):
await message.answer(message.text)

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

if name == "main":
asyncio.run(main())


Run this with: python bot.py
Open Telegram, send your bot /start
It responds — your bot is alive
Please open Telegram to view this post
VIEW IN TELEGRAM
📌 Breaking Down the Code

load_dotenv() — loads your .env file so os.getenv() can read it

Bot(token=TOKEN) — creates the bot object that talks to Telegram

Dispatcher() — the brain of your bot, routes messages to the right handler

@dp.message(Command("start")) — a decorator
It tells the Dispatcher: when someone sends /start, run this function

message.from_user.first_name — the sender's first name
This is the OOP we covered last section — message is an object with attributes

message.answer() — sends a reply to the same chat
message.reply() — sends a reply that quotes the original message

The echo handler at the bottom has no filter
It catches every message that did not match any other handler
Order matters — put specific handlers first, catch-all last
Please open Telegram to view this post
VIEW IN TELEGRAM
🚨 Video Reference

Watch this for a full visual walkthrough of setting up aiogram v3

➡️ aiogram 3 beginner series — full playlist
➡️ Official aiogram 3 docs

🔖 Watch: Aiogram Basics: Build Your First Telegram Bot (15:00) + Lesson 1 — First Handlers (23:39)
Please open Telegram to view this post
VIEW IN TELEGRAM
✏️ Lecture 14 Homework

Get the echo bot running then extend it:

➡️ Add a /about command that tells the user what your bot does
➡️ Add a /time command that sends the current time

from datetime import datetime

@dp.message(Command("time"))
async def time_handler(message: Message):
now = datetime.now().strftime("%H:%M:%S")
await message.answer(f"Current time: {now}")


➡️ Make the echo handler only respond to text messages:

from aiogram.filters import F

@dp.message(F.text)
async def echo_handler(message: Message):
await message.answer(message.text)


Test all commands, screenshot the responses from your actual bot

⚠️ Next lecture drops in 2 days — Commands & Handlers
Please open Telegram to view this post
VIEW IN TELEGRAM
This media is not supported in your browser
VIEW IN TELEGRAM