Need an AI assistant at hand, but paid APIs look frightening on the billing side, and experiments on a laptop die the moment you close the lid? A Telegram bot with a free API as its brain is the first real project of every practitioner: one evening, zero rubles, a clear architecture. In practice this looks like a jobs bot monitoring hundreds of channels, or wrapper bots for quick access to models from a phone. Below is a full assembly guide: bot → free API → memory → deployment to a VPS.
The architecture in one diagram: a server and a free API
User → Telegram → your server (the bot script)
↓
free API (Groq / GLM Flash)
↓
reply → Telegram → userThe diagram holds no surprises: a user writes to the bot, Telegram delivers the message to your server, the bot script calls the free LLM API and returns the answer to the chat. The server is a VPS for RUB 200–300/month or a home machine. A VPS is preferable: a permanent IP (webhooks are not blocked), 24/7 operation and access from anywhere. The bot itself is a 40-line Python script; nothing more complex is required.
The skeleton below uses long polling: the connection to Telegram stays open and incoming messages arrive on their own. That makes life easier — you don’t need to open inbound ports on the VPS, and the dynamic address of a home machine doesn’t get in the way of experiments. The switch to webhooks comes later, under heavier load; for a start, polling is simpler and more reliable.
Why not “locally on a laptop”
A home machine is fine for experiments, but a laptop gets switched off, the provider’s IP is dynamic, and the bot “dies” every evening. For a production setup, take the minimal VPS plan: the bot script consumes a few dozen megabytes of memory, so the cheapest plan covers the task with room to spare.
Assembly in four steps: from @BotFather to the first reply
- Bot token: open @BotFather in Telegram → the /newbot command → the bot’s name and username → BotFather issues a token like 123456789:AA… Save it: this is full access to the bot; reissue it with the /revoke command.
- Free key: Groq (1000 RPD on the free tier) or GLM Flash (free forever). The step-by-step Groq quick start and GLM Flash setup are covered in separate guides of the catalog.
- Bot code: the skeleton below — paste in the two keys and run it.
- Deployment: a systemd service on the VPS — the bot lives 24/7 without your involvement.
Install the dependencies with one command:
pip install pyTelegramBotAPI requests python-dotenvThe bot skeleton — save it as bot.py:
import telebot, requests
BOT_TOKEN = "TOKEN_FROM_BOTFATHER"
API_URL = "https://api.groq.com/openai/v1/chat/completions"
API_KEY = "GROQ_KEY"
bot = telebot.TeleBot(BOT_TOKEN)
@bot.message_handler(func=lambda m: True)
def on_message(m):
r = requests.post(API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={"model": "openai/gpt-oss-20b",
"messages": [
{"role": "system", "content": "Answer briefly, in Russian."},
{"role": "user", "content": m.text}]}, timeout=30)
bot.reply_to(m, r.json()["choices"][0]["message"]["content"])
bot.infinity_polling()Run python bot.py — and the bot is already replying in the chat. The openai/gpt-oss-20b model is an open model on Groq’s servers: fast and free within the quota; the current list of models is returned by the /models endpoint of the same API. Telegram truncates long replies — ask the model to answer compactly in the system message.
Memory and personality: so the bot doesn’t reply into a vacuum
A bot without memory replies into a vacuum: every question is the first one as far as the model is concerned. Two levels solve the problem, and the third makes the bot feel like “your own”:
- dialogue context — the user’s last N messages kept in a dict keyed by chat_id, sent with every API call;
- prompt personality — role, tone and rules in the system message at the start of every call: “You are the studio’s on-duty assistant. Answer briefly, in Russian, without walls of list items”;
- persistent memory — the HISTORY dict resets on restart, so dump it into a JSON file on the server after each reply and load it at startup.
An extended version with memory, an allowlist and retries — the core that replaces the handler from the skeleton:
import os, time, requests
from dotenv import load_dotenv
load_dotenv()
API_URL = "https://api.groq.com/openai/v1/chat/completions"
API_KEY = os.getenv("GROQ_API_KEY")
ALLOWED = {123456789, 987654321} # allowlisted chat_id values
HISTORY = {} # chat_id -> messages
SYSTEM = "You are the on-duty assistant. Brief, in Russian, to the point."
def ask_llm(chat_id, user_text):
msgs = [{"role": "system", "content": SYSTEM}]
msgs += HISTORY.get(chat_id, [])[-8:] # tail of the dialogue
msgs.append({"role": "user", "content": user_text})
for attempt in range(3): # retries on 429
r = requests.post(API_URL,
headers={"Authorization": f"Bearer {API_KEY}"},
json={"model": "openai/gpt-oss-20b", "messages": msgs},
timeout=30)
if r.status_code == 429:
time.sleep(2 ** attempt) # 1, 2, 4 seconds
continue
answer = r.json()["choices"][0]["message"]["content"]
HISTORY.setdefault(chat_id, []).extend(
[{"role": "user", "content": user_text},
{"role": "assistant", "content": answer}])
return answer
return "The API is overloaded, try again in a minute."The /reset command and handler order
A dialogue can hit a dead end — the user must be able to reset the context. Add a command handler:
@bot.message_handler(commands=["reset"])
def on_reset(m):
HISTORY.pop(m.chat.id, None)
bot.reply_to(m, "Context cleared, starting fresh.")An important detail of pyTelegramBotAPI: handlers are checked in declaration order, and the first matching one processes the message. Declare the command handler above the universal func=lambda m: True, otherwise the catch-all will intercept /reset as plain text.
The levels of agent memory — working notes, rule files, context compression — are covered in the piece on CLAUDE.md and agent memory: the principle is the same — rules of behavior go into the system prompt, facts go into a persistent file.
The economics: zero rubles for months, a 20x margin
Groq on the free tier gives you 1000 RPD (as of fall 2026): a bot with a single user spends 20–50 requests per day — a 20x margin. GLM Flash has no daily ceilings in practice. Even with 10 users, the free quotas cover a chat bot’s load. A layer-by-layer reference:
| Layer | Free limit (fall 2026) | Role in the bot |
|---|---|---|
| Groq | 1000 RPD | primary: fast chat replies |
| GLM Flash | no daily ceilings in practice | strong answers on code and reasoning |
| Cerebras | 1 million tokens/day | the second layer as load grows |
As load grows, connect Cerebras (1 million tokens/day) as a second layer: all three providers speak the same OpenAI Chat Completions protocol, so switching is literally one line of code — only API_URL and the model name change. Add the “primary is down — switch to the backup” logic after the first week of operation: at the start, the 429 retries from the skeleton above are enough. And the piece on free tier layers teaches you to fold the limits of different providers into one pool.
Hygiene: secrets, 429 limits and a systemd deployment
- The bot token is a secret: keep it in .env on the server (load_dotenv in the code above already does this), not in the repository code; a compromised token is revoked with @BotFather via /revoke.
- Limit the circle: an allowlist of chat_id values — the bot answers only you and your own; strangers’ messages are silently ignored.
- Retries on 429: a free API throttles sometimes — a pause with a growing interval and a repeat are mandatory; the full breakdown is in the piece on 429 handling patterns.
- Logs: write user questions and API errors to a file or journald — this is the first line of debugging.
A systemd service in five minutes
Save the service description into the file /etc/systemd/system/tgbot.service:
[Unit]
Description=Telegram AI bot
After=network-online.target
[Service]
User=bot
WorkingDirectory=/opt/tgbot
ExecStart=/usr/bin/python3 /opt/tgbot/bot.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.targetThen three commands — reload the configuration, enable autostart and start right now:
sudo systemctl daemon-reload
sudo systemctl enable --now tgbot.service
journalctl -u tgbot.service -fRestart=always brings the bot back up 5 seconds after a crash, and journalctl with the -f flag shows the log in real time. Updated the code — sudo systemctl restart tgbot. A separate bot user instead of root is the minimal precaution: the process must not carry excess privileges.
Common questions
Which API should you pick for the bot? Groq — speed for chats: replies arrive almost instantly and the dialogue feels alive; GLM Flash — when you need strong code and reasoning. Both are free — keep both: one as the primary, the other as a fallback in case you hit limits or quality degrades.
Where do you get a VPS from Russia? Russian VPS providers at RUB 200–300/month are the norm; foreign ones — if the API you chose requires a different region. Payment is the main difference: Russian providers accept the usual methods, foreign ones may ask for a card from another bank.
A bot for clients or a business? Then a paid layer on the critical paths and a privacy rule: client data must not go into free APIs. Leave the free quotas for internal tasks and prototypes.
How do you add features? The /start and /reset commands (the list is set with BotFather via /setcommands — a command menu appears in the Telegram interface), inline buttons, accepting files from the user → a multimodal API — see the Google AI Studio guide. Add extensions as real need arises, not in advance: every new feature is a new point of failure.
One evening to build, zero rubles for months of operation — a Telegram bot is the “Hello World” of the free pipeline and the best way to master the code + API + deployment trio. Concrete action: open @BotFather, run /newbot and launch the skeleton from this article today. The guide is current as of fall 2026.
