A Telegram bot is one of the most satisfying first AI projects: it lives in an app you already check constantly, it works on every device, and Telegram handles all the messaging plumbing for free. This tutorial walks through creating the bot, connecting it to an LLM with conversation memory, and adding voice support — plus an interactive generator that produces ready-to-run Python starter code.
Step 1 — Create the bot with BotFather
Every Telegram bot is registered through @BotFather, an official bot that
issues credentials. Open a chat with it, send /newbot, choose a name and a
unique username ending in bot, and BotFather replies with an HTTP API
token that looks like 123456:ABC-DEF.... That token is your bot’s password —
keep it in an environment variable, never in source control.
Step 2 — Connect to the LLM with memory
Install python-telegram-bot and register a
message handler — a function called for every incoming text message. Inside
it you forward the user’s message to the OpenAI Chat Completions endpoint and
reply with the result.
The key detail is memory. Telegram delivers each message as an isolated
update, so you keep a dictionary keyed by chat_id, each holding that chat’s
running list of role-tagged messages (system, user, assistant). You resend
that history on every call — it is the bot’s memory — and append the reply
before the next turn. When the history grows near the model’s context limit, drop
or summarize the oldest turns.
Step 3 — Add voice, then deploy
To accept voice notes, add a handler for the VOICE filter: download the OGG
file Telegram provides, transcribe it with a speech-to-text model such as
Whisper, and feed the transcript in as a normal user turn. The reply can go back
as text or as synthesized audio.
For deployment, start with polling (the bot asks Telegram for updates in a loop) because it needs no public URL. Push the process to a free always-on host like Railway, Fly.io, or Render, set your tokens as environment variables, and you have a personal assistant in your pocket. Switch to webhooks later for lower latency and cost at scale.
Use the generator below to produce a starter bot.py, then read
how to build a chatbot with the OpenAI API
for deeper context handling and estimate spend with the
LLM API Cost Calculator.