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.

python --version. Expected output: Python 3.11.6 or similar.cd, pip install.
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-dotenvExpected 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 mainExpected 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.
.env and in the PaaS variables, never in code.env listed in .gitignorerequirements.txt generated and committedpython bot.py
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.
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.
Status: practical guide. Some statements come from vendors; verify in your environment.
Build a Telegram bot connected to an LLM in Python: getting a token, handling messages, dialogue memory, and deploying to a server.
Machine data: Citation Map JSON · JSON-LD · Semantic Embeddings — separate stage.
| Entity | Type | Role |
|---|---|---|
| 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 или разделах гайда |
No independent confirmation is provided; source claims and editorial conclusions are separated below.
| Source | Type | Role |
|---|---|---|
| github.com | внешний источник | ссылка из тела гайда |
Cite as: AI Release. Telegram-бот с ИИ на Python: от нуля до деплоя. ai-release.org.