DEV Community

Anaam Hamid
Anaam Hamid

Posted on

How I structure a small Telegram bot in Python (aiogram) for a local business

Small businesses often ask me for the same thing: a Telegram bot that answers common questions, takes simple requests and pings the owner. Here is the structure I use. It stays small and is easy to hand over.

Layout

bot/
  main.py        # starts the bot
  handlers.py    # commands and message handlers
  config.py      # token and settings from environment variables
  data.json      # FAQ answers the owner can edit
Enter fullscreen mode Exit fullscreen mode

A minimal handler (aiogram 3)

import asyncio, json, os
from aiogram import Bot, Dispatcher, F
from aiogram.filters import Command
from aiogram.types import Message

bot = Bot(os.environ["BOT_TOKEN"])
dp = Dispatcher()
faq = json.load(open("data.json", encoding="utf-8"))

@dp.message(Command("start"))
async def start(m: Message):
    await m.answer("Hi! Ask about: " + ", ".join(faq))

@dp.message(F.text)
async def answer(m: Message):
    key = m.text.strip().lower()
    await m.answer(faq.get(key, "I will pass this to the owner."))

asyncio.run(dp.start_polling(bot))
Enter fullscreen mode Exit fullscreen mode

Why this shape

  • The owner edits data.json, not code.
  • The token lives in an environment variable, never in the repo.
  • Unknown questions get forwarded to a human, so the bot never invents answers.

Disclosure

I build bots like this for small teams and communities as a freelancer. If you want one, my Contra service starts at $45 and includes the full source code, setup notes and one round of changes: https://contra.com/s/XRvskAQg-custom-telegram-or-discord-bot-in-python

Questions about the code are welcome in the comments.

Top comments (0)