A personal chat assistant in your pocket, built in an evening

APIDeepSeekFreeKey · Updated 2026-11-22 · 8 min read

Phone on a bedside table with a paper airplane
An assistant that lives where you already chat.

Personal assistants that live in a messaging app are one of the most popular hobby projects of the year. People describe ultra-cheap hybrid stacks where an agent runs on a small server, talks through Telegram by text and voice, and mixes a low-cost cloud model with local ones. Others build terminal-native agents with their own interfaces. The common thread is the wish for an assistant that is always reachable, cheap to run and fully under the owner's control.

This guide builds the core of such a bot: a Python program that receives Telegram messages, keeps a short conversation history per chat, calls an OpenAI-compatible model and sends the reply back. It handles rate limits properly, splits long answers, and keeps the backend in configuration, so you can start on the keyless free-ai endpoint on this site and later move to DeepSeek's API or a local model by changing three values.

This site is independent and not affiliated with DeepSeek. free-ai is an open-weight model of about 35B parameters, text only, with no SLA. That makes it a good fit for a personal or small-group bot and a poor fit for a business-critical service, which deserves a paid provider.

Frequently asked questions

What does a Telegram bot need to talk to a language model?

A bot token from Telegram's BotFather, a small program that receives updates, and an API to generate replies. The program forwards each message, plus recent history, to the model and sends the answer back to the chat.

How does polling differ from webhooks?

With polling, your program repeatedly asks Telegram for new messages, which works anywhere, even on a laptop. With webhooks, Telegram pushes messages to a public HTTPS URL you provide. Polling is simpler to start; webhooks scale better.

Why does the bot need its own conversation memory?

The API is stateless: every request must contain the context the model should consider. The bot stores recent messages per chat and sends them with each new question.

What are the rate limits when a bot uses the free endpoint?

Limits apply per IP, and all bot users share the server's IP. That means one request per second with short bursts, two in parallel and a daily cap of 10,000 requests or 10 million tokens for the whole bot. Fine for personal use; too tight for a large public bot.

Can the bot handle voice messages?

The model is text only, so voice needs a transcription step first, for example a local speech-to-text model on the same machine. The transcript is then sent to the model like any other message.

Which is better for a bot: a free endpoint or a paid API?

For a personal assistant or a small group of friends, a free endpoint is often enough. For a public bot with many users, a paid provider gives higher limits, stronger models and a support channel.

Where should the Telegram token be stored?

In an environment variable or a secrets file on the server, never in the source code or a public repository. Anyone with the token can control the bot.

Step by step

  1. Create the bot — Use Telegram's BotFather to create a bot and copy its token into an environment variable on your server.
  2. Install dependencies — Run pip install python-telegram-bot openai on a machine with Python 3.10 or newer.
  3. Configure the backend — Set LLM_BASE_URL, LLM_KEY and LLM_MODEL, or leave the defaults to use the keyless free-ai endpoint.
  4. Run and test — Start the script, send the bot a message, and try /reset to confirm memory clears.
  5. Run as a service — Install a systemd unit or a container with a restart policy so the bot survives crashes and reboots.

What you are building

The finished bot is a single Python file of about seventy lines. It uses the python-telegram-bot library for messaging and the official openai package for the model, pointed at any OpenAI-compatible base URL. It remembers the last few exchanges in each chat, has a command to clear memory, and serialises model calls so it never exceeds the endpoint's limits.

Everything about the backend lives in environment variables: base URL, key and model name. Switching providers is a restart, not a rewrite.

Requirements

Python 3.10 or newer, a Telegram account, and any always-on machine: a home server, a small VPS or a single-board computer. Polling needs no public address.

What it does not do

No images, no tool use, no voice out of the box. Those are extensions you can add later once the core loop works.

Getting a bot token

Open a chat with Telegram's official BotFather account, send the command to create a new bot, choose a display name and a username ending in 'bot', and you receive a token. Treat it like a password. Store it in an environment variable on the machine that will run the bot.

While you are there, you can set a description and a list of commands so users see them in the menu. This bot uses two: /start and /reset.

Restrict who can use it

For a personal assistant, note your own numeric user ID and make the bot ignore everyone else. Otherwise strangers who find it will share your limits.

Single-board computer running on a bookshelf
Any always-on machine can host the bot.

The bot code

Install the dependencies with pip install python-telegram-bot openai, save the file below, set the environment variables and run it. The comments explain each part. The semaphore and the small delay keep model calls within one request per second and two in parallel, the limits that apply to the bot's server IP on this endpoint.

Why the history is trimmed

Keeping only the last eight exchanges bounds the request size, keeps answers fast and stays well inside the 32,000-token context, even when someone pastes long text.

Why replies are split

Telegram limits a single message to about four thousand characters. Splitting at that length avoids errors on long answers; splitting on paragraph boundaries reads even better.

# bot_apideepseekfreekey.py
import asyncio, os, time
from openai import AsyncOpenAI, RateLimitError, APIStatusError
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, filters

TOKEN = os.environ["TELEGRAM_TOKEN"]
ALLOWED = {int(x) for x in os.environ.get("ALLOWED_USERS", "").split(",") if x}
client = AsyncOpenAI(base_url=os.environ.get("LLM_BASE_URL", "https://api.apideepseekfreekey.com/v1"),
                     api_key=os.environ.get("LLM_KEY", "free"))
MODEL = os.environ.get("LLM_MODEL", "free-ai")
SYSTEM = "You are a concise personal assistant. Answer in the user's language."
HISTORY_TURNS = 8
gate = asyncio.Semaphore(2)
last_call = 0.0

async def ask(messages):
    global last_call
    async with gate:
        for attempt in range(4):
            wait = last_call + 1.05 - time.monotonic()
            if wait > 0:
                await asyncio.sleep(wait)
            last_call = time.monotonic()
            try:
                r = await client.chat.completions.create(model=MODEL, messages=messages, max_tokens=1200)
                return r.choices[0].message.content
            except RateLimitError:
                await asyncio.sleep(2 * (attempt + 1))
            except APIStatusError as e:
                if e.status_code != 503:
                    raise
                await asyncio.sleep(3)
    return "The model is busy right now, please try again in a minute."

async def start(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text("Hi! Send me a message. /reset clears our conversation.")

async def reset(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    ctx.chat_data["history"] = []
    await update.message.reply_text("Memory cleared.")

async def chat(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
    if ALLOWED and update.effective_user.id not in ALLOWED:
        return
    history = ctx.chat_data.setdefault("history", [])
    history.append({"role": "user", "content": update.message.text})
    del history[:-HISTORY_TURNS * 2]
    await update.message.chat.send_action("typing")
    reply = await ask([{"role": "system", "content": SYSTEM}] + history)
    history.append({"role": "assistant", "content": reply})
    for i in range(0, len(reply), 4000):
        await update.message.reply_text(reply[i:i + 4000])

app = ApplicationBuilder().token(TOKEN).concurrent_updates(True).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("reset", reset))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
app.run_polling()

Running it reliably

For a quick test, run the file in a terminal with the variables exported. For daily use, run it as a service so it restarts after crashes and reboots. On Linux, a small systemd unit is the usual choice; on other systems, a process manager or a container with a restart policy does the same job.

Log errors to a file or the system journal. When something goes wrong at three in the morning, a log line that says '503 from upstream' saves a lot of guessing.

Check on the bot now and then even when nothing seems wrong. A daily log line with the number of messages handled and the number of retries tells you early if usage is creeping toward the shared limits or if the upstream has become less reliable.

Keep secrets out of the unit file in shared systems

On a machine others can read, use an EnvironmentFile with restricted permissions instead of putting the token directly in the unit.

# /etc/systemd/system/assistant-bot.service
[Unit]
Description=Telegram assistant bot
After=network-online.target

[Service]
Environment=TELEGRAM_TOKEN=replace-with-your-token
Environment=ALLOWED_USERS=123456789
ExecStart=/usr/bin/python3 /opt/bot/bot_apideepseekfreekey.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
Hikers crossing a narrow footbridge in turns
All bot users share one server IP, so calls cross in turn.

Shared limits: the one thing to understand

A browser app calling the free endpoint spreads load across visitors, because each one has their own IP. A bot is different: every request comes from your server, so every user of the bot shares one IP's allowance. One request per second and two in flight is plenty for one person or a family group, but a bot shared in a busy public channel will queue up quickly.

The code above already handles this gracefully by serialising calls and retrying on 429 and 503. If your bot grows, switch the environment variables to a paid provider with higher limits. The retry patterns are explained in more detail in handling 429 and 503 errors.

Daily cap

The allowance of 10,000 requests or 10 million tokens per day resets at 00:00 UTC. For a personal assistant that is far more than enough; for a public bot it may not be.

Making it more useful

Once the core loop works, small additions go a long way. A per-chat system prompt lets each group give the bot a different role. A command to summarise the conversation so far is handy for long discussions. Saving history to a small SQLite database lets memory survive restarts.

Voice is a popular next step. Telegram delivers voice notes as audio files; a local speech-to-text model turns them into text, which then flows through the same ask function. The model itself stays text only.

Accents and formatting

If replies in languages with diacritics look wrong, check your text handling before blaming the model. Fixing broken accents covers the usual causes.

Markdown in replies

Models like to use Markdown. Either send replies as plain text, as the code does, or enable a parse mode and escape the text with your library's helper.

  • /role to set a custom system prompt per chat
  • /summary to condense the conversation
  • SQLite storage for history that survives restarts
  • Local transcription for voice notes
  • A daily digest message on a schedule
Tape recorder beside a notebook
Voice notes need transcription before a text model can read them.

Hybrid local and cloud setups

Many builders mix backends: a small local model for private notes and quick tasks, a hosted model for harder questions. Because the bot reads its backend from configuration, you can run two instances with different settings, or add a command that switches the model per chat. Local runners that expose an OpenAI-compatible server plug straight in.

Keep the trade-offs in mind. Local models keep data on your machine but are slower and weaker on modest hardware; hosted models are faster and stronger but see your messages. The comparison in local versus hosted models helps you decide which conversations go where.

Route by sensitivity

A simple rule, such as a command prefix that forces the local model, gives you control over what leaves your machine without complex logic.

Privacy and honesty with your users

If other people use your bot, tell them what happens to their messages. They pass through Telegram and through your server, and their content is sent to the model provider. On this endpoint each request leaves a technical log with time, IP, User-Agent, country, endpoint, status, latency, sizes and tokens; conversations are not stored as state by the API, but your bot keeps recent history in memory.

Never give the bot access to accounts or data it does not need, and never use shared or leaked API keys to save money. A bot running on someone else's leaked key can stop at any moment and exposes every conversation to whoever controls that account.

A short notice

A line in the /start reply such as 'messages are processed by an AI service; do not send passwords or personal data' sets expectations honestly.

Small and large mailboxes at a lane end
Route private messages locally and the rest to a hosted model.
Try the free API

Open the home page and send a request to the keyless endpoint straight from your browser, no account or key needed.

Read also