← All guides AI Release
RU Subscribe to @ai_releaseorg

An AI-powered Telegram bot in Python: from scratch to deploy

Updated: 19.10.2026 · AI Release · @ai_releaseorg
An AI-powered Telegram bot in Python: from scratch to deploy

This guide solves one concrete problem: you have an idea for a Telegram bot that answers with an AI model, but you have never shipped one — you do not know how to get a token, how to call a model from Python, or how to keep the bot alive after you close your laptop. By the end you will have a working bot running in the cloud. The steps below work on Windows 10/11, macOS 12+, and Ubuntu 22.04+, with Python 3.10 or newer. No prior experience with Telegram bots is required, only basic Python.

Requirements and Preparation

Illustration: Requirements and Preparation
Illustration: Requirements and Preparation

Step-by-Step Instructions

Illustration: Step-by-Step Instructions
Illustration: Step-by-Step Instructions

1. Create the bot and copy the token. Open Telegram, search for @BotFather, press Start, send /newbot, then give a display name (for example My AI Helper) and a username that must end in bot (for example my_ai_helper_bot). Expected result: BotFather replies with Use this token to access the HTTP API: 1234567890:AAE... and a link to your new bot. Why it works: the token is the only credential your code needs; every Telegram API call carries it.

2. Create the project folder and a virtual environment. A virtual environment is an isolated folder of packages, so this project cannot break your other Python projects.

mkdir ai-tg-bot && cd ai-tg-bot
python -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install aiogram openai python-dotenv

Expected result: your prompt starts with (.venv) and pip prints Successfully installed aiogram-... openai-... python-dotenv-.... Why it works: aiogram is the framework that receives Telegram updates for you, openai is the client for the model API, and python-dotenv reads secrets from a file.

3. Put your secrets in a .env file. Create a file named exactly .env in the project root:

TELEGRAM_TOKEN=1234567890:AAE...
LLM_API_KEY=sk-...

Expected result: the file exists next to your code, and git status never shows it (add .env to .gitignore). Why it works: code and secrets stay separate, so you can back up or share the repository without leaking keys.

4. Write the minimal bot with an AI call. Create bot.py:

import asyncio, os
from dotenv import load_dotenv
from aiogram import Bot, Dispatcher, types
from openai import AsyncOpenAI

load_dotenv()
bot = Bot(os.getenv("TELEGRAM_TOKEN"))
dp = Dispatcher()
client = AsyncOpenAI(api_key=os.getenv("LLM_API_KEY"))

@dp.message()
async def answer(message: types.Message):
    reply = await client.chat.completions.create(
        model="your-model-name",
        messages=[{"role": "user", "content": message.text}],
    )
    await message.answer(reply.choices[0].message.content)

asyncio.run(dp.start_polling(bot))

Expected result: python bot.py starts and prints nothing; no traceback. Why it works: start_polling is a loop where the bot asks Telegram "any new messages?" and hands each one to your handler. Replace your-model-name with the exact model id from your provider's dashboard.

5. Test it locally. Open your bot in Telegram (the link BotFather gave you), press Start, and send Hello. Expected result: the bot answers within a few seconds, and your terminal shows one incoming update. If nothing arrives, the problem is almost always the token, not the model.

6. Add a system prompt so the bot has a role. Insert a first message before the user message:

messages=[
    {"role": "system", "content": "You are a concise assistant. Answer in under 80 words."},
    {"role": "user", "content": message.text},
],

Expected result: the same question now returns a shorter, on-topic answer. Why it works: the system message is a permanent instruction the model reads before every reply. This is the cheapest way to change behaviour — no fine-tuning needed. For more text-focused patterns like translation or summarizing, see AI for text work.

7. Push the code to GitHub. Run:

git init && git add . && git commit -m "first bot"
git remote add origin https://github.com/<your-name>/ai-tg-bot.git
git push -u origin main

Expected result: the repository page shows bot.py, requirements.txt, and .gitignore, but not .env. Generate requirements.txt with pip freeze > requirements.txt first.

8. Deploy to a PaaS. Create a new service from your GitHub repo. Set the start command to python bot.py, add TELEGRAM_TOKEN and LLM_API_KEY in the environment variables section, and deploy. Expected result: the build log ends with the service running, and the bot answers even after you shut your laptop down. Why it works: the PaaS installs requirements.txt, injects the variables as real environment variables, and keeps the process alive.

Common Problems and Solutions

Illustration: Common Problems and Solutions
Illustration: Common Problems and Solutions

Problem 1: Unauthorized or a 401 error on startup. The screen shows a traceback ending in something like TelegramUnauthorizedError: Unauthorized. This means Telegram rejected your token. Fix: open BotFather, send /mybots, choose your bot, open API Token, and copy the token again. Paste it into .env with no spaces and no quotes, then restart. If it still fails, check that load_dotenv() runs before Bot(...) is created — otherwise the variable is None.

Problem 2: Conflict: terminated by other getUpdates request. The log repeats TelegramConflictError. This happens when two copies of the bot run at once — usually your laptop and the cloud server. Fix: stop the local copy with Ctrl+C, or scale the cloud service down to one instance. Only one process may poll a token at a time.

Problem 3: The bot stays silent in a group chat. In private chat it answers, in a group it does not. Telegram gives bots privacy mode by default, so they only see messages that mention them or reply to them. Fix: send /setprivacy to BotFather, pick the bot, choose Disable, then remove the bot from the group and add it again. The setting only applies after a re-add.

FAQ

Do I need a paid API key to start?

No. Several providers offer free tiers or free models, and the code above does not change — only the base URL and the model id change. A list of free options is in How to use AI models for free in 2026.

Can I just run the bot on my laptop forever?

Technically yes, but the bot dies the moment you close the lid or lose Wi-Fi. A PaaS is the practical answer, and most offer a free or very cheap tier for a single small process.

Does the bot remember the previous messages?

Not with the code above — each request sends only the current message. To add memory, keep a list per chat id and append old user and assistant messages to the messages array. Keep the list short, because every stored message costs tokens.

What if I want the bot to do multi-step tasks, not just answer?

That is agent territory: the bot decides which tool to call, runs it, and continues. The ideas and patterns are collected in AI agents for task automation. Start with the plain bot first — the agent version is the same code plus a loop.

🤖 AI summary

AI Release Knowledge Layer
Machine-readable description · Version 1.0

Status: practical guide. Some statements come from vendors; verify in your environment.

1. Summary

Build a Telegram bot connected to an LLM in Python: getting a token, handling messages, dialogue memory, and deploying to a server.

Inside: direct answers, key facts, entities, context, reliability, unknowns and sources.

Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.

Full Knowledge Layer: sections 2–8

2. Direct answers

What is this guide about?
Build a Telegram bot connected to an LLM in Python: getting a token, handling messages, dialogue memory, and deploying to a server. → details (AR-GUIDE-TELEGRAMBO-001)
What is required?
A computer running Windows 10/11, macOS 12+, or Ubuntu 22.04+.; Python 3.10 or newer. Check it with python --version. Expected output: Python 3.11.6 or similar.; A Telegram account. You will talk to @BotFather — the official Telegram bot that creates other bots.; A bot token from BotFather (a token is a long… → details (AR-GUIDE-TELEGRAMBO-003)
Which topics does it cover?
Telegram бот Python, ИИ бот, aiogram, бот с нейросетью → details (AR-GUIDE-TELEGRAMBO-002)

3. Key facts

  1. A computer running Windows 10/11, macOS 12+, or Ubuntu 22.04+. — evidence; status: заявление источника.
  2. Python 3.10 or newer. Check it with python --version. Expected output: Python 3.11.6 or similar. — evidence; status: заявление источника.
  3. A Telegram account. You will talk to @BotFather — the official Telegram bot that creates other bots. — evidence; status: заявление источника.

4. Entities

EntityTypeRole
Telegram bot Pythonтема/инструментупоминается в заголовке, TL;DR или разделах гайда
AI botтема/инструментупоминается в заголовке, TL;DR или разделах гайда
aiogramтема/инструментупоминается в заголовке, TL;DR или разделах гайда
bot with neural networkтема/инструментупоминается в заголовке, TL;DR или разделах гайда
Windowsплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
macOSплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Telegramплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
GitHubплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
Pythonплатформа/технологияупоминается в заголовке, TL;DR или разделах гайда
OpenAIкомпанияупоминается в заголовке, TL;DR или разделах гайда

5. Context

  • Guide — describes → An AI-powered Telegram bot in Python: from scratch to deploy (AR-GUIDE-TELEGRAMBO-001).

6. Reliability

Confirmed

No independent confirmation is provided; source claims and editorial conclusions are separated below.

Source claims

  • Product features, versions, prices and limits come from vendors and the guide.
  • Commands and steps are recommendations, not guaranteed results.

AI Release analysis

  • Structure, comparison and selection criteria are editorial.
  • The guide does not replace an independent audit or legal advice.

7. Unknowns

  • Current versions, prices and limits.
  • Independent benchmarks and quality checks.
  • Terms of use and data policy.

8. Sources

SourceTypeRole
github.comвнешний источникссылка из тела гайда

Cite as: AI Release. Telegram-бот с ИИ на Python: от нуля до деплоя. ai-release.org.