Models → Pricing → Docs → Blog → Changelog → Contact → Status →
Get started freeLog in

Build an AI Telegram Bot with the OpenAI SDK

About 70 lines of Python: the Telegram Bot API for messages, the OpenAI SDK for answers, gpt-6-luna on a free key. Memory per chat, error handling and running costs included.

A Telegram bot that answers questions with a language model needs two things: a way to receive and send Telegram messages, and a way to get an answer from a model. The Telegram Bot API handles the first with plain HTTPS calls. An OpenAI-compatible API handles the second.

This guide builds a complete bot in Python. It uses gpt-6-luna, one of the free models, so you can build and test it on a free FreeModel key. Swapping in another model later is a one-line change.

What you need

  • A Telegram bot token. In Telegram, open @BotFather, send /newbot, choose a name and a username. BotFather replies with a token.
  • A FreeModel API key. Sign up, verify once with Telegram to unlock the free tokens, then create a key at Dashboard → API Keys. Details in the free plan, explained.
  • Python 3.9+ and two packages: pip install openai requests.

Put both secrets in environment variables:

export TELEGRAM_BOT_TOKEN="123456789:AA..."   # from BotFather
export FREEMODEL_API_KEY="fm_..."             # from the FreeModel dashboard

How it works

  1. The bot asks Telegram for new messages with getUpdates, using long polling — the request waits up to 50 seconds for something to arrive.
  2. For each text message, it adds the message to that chat's short history and calls chat.completions.create on FreeModel.
  3. It sends the answer back with sendMessage.

No web server and no public URL are needed for this approach. The bot only makes outgoing requests.

The code

Save this as bot.py:

import os
import requests
from openai import OpenAI, APIStatusError

TELEGRAM_API = f"https://api.telegram.org/bot{os.environ['TELEGRAM_BOT_TOKEN']}"
client = OpenAI(api_key=os.environ["FREEMODEL_API_KEY"], base_url="https://freemodel.in/v1")

MODEL = "gpt-6-luna"
SYSTEM = "You are a helpful assistant in a Telegram chat. Answer briefly and clearly."
MAX_HISTORY = 10   # messages kept per chat
history = {}       # chat_id -> list of messages, in memory only


def tg(method, **params):
    return requests.post(f"{TELEGRAM_API}/{method}", json=params, timeout=60).json()


def ask_model(chat_id, text):
    msgs = history.setdefault(chat_id, [])
    msgs.append({"role": "user", "content": text})
    del msgs[:-MAX_HISTORY]
    try:
        res = client.chat.completions.create(
            model=MODEL,
            messages=[{"role": "system", "content": SYSTEM}] + msgs,
            max_tokens=1000,
        )
    except APIStatusError as e:
        msgs.pop()  # forget the question we could not answer
        if e.status_code == 402:
            return "The bot has used up its AI tokens for now. Please try again later."
        if e.status_code == 429:
            return "Too many questions at once. Please wait a moment and try again."
        return "Sorry, something went wrong. Please try again."
    except Exception:
        msgs.pop()
        return "Sorry, I could not reach the AI service. Please try again."
    answer = res.choices[0].message.content or "(no answer)"
    msgs.append({"role": "assistant", "content": answer})
    return answer


def main():
    offset = 0
    while True:
        try:
            updates = requests.get(f"{TELEGRAM_API}/getUpdates",
                                   params={"timeout": 50, "offset": offset}, timeout=60).json()
        except requests.RequestException:
            continue
        for upd in updates.get("result", []):
            offset = upd["update_id"] + 1
            msg = upd.get("message") or {}
            text = msg.get("text")
            if not text:
                continue
            chat_id = msg["chat"]["id"]
            if text.startswith("/start"):
                reply = "Hi! Ask me anything. Send /reset to start a new conversation."
            elif text.startswith("/reset"):
                history.pop(chat_id, None)
                reply = "Done, I forgot our conversation."
            else:
                tg("sendChatAction", chat_id=chat_id, action="typing")
                reply = ask_model(chat_id, text)
            for i in range(0, len(reply), 4000):   # Telegram allows 4096 characters per message
                tg("sendMessage", chat_id=chat_id, text=reply[i:i + 4000])


if __name__ == "__main__":
    main()

Run it with python bot.py, open your bot in Telegram and send a message.

What each part does

Chat memory

Language models do not remember earlier messages on their own; you send the conversation each time. The bot keeps the last 10 messages per chat. That bound matters: every message you resend counts as input tokens again, so an unbounded history makes each answer more expensive than the last.

Error handling

FreeModel uses standard HTTP status codes, which the OpenAI SDK raises as APIStatusError:

StatusMeaning for a bot
402Tokens used up. Nothing is charged; the bot should say so politely.
429Too many requests per minute for the key. Wait for the time in Retry-After.
403 upgrade_requiredA free key asked for a paid model.
404 model_not_foundModel ID typo. IDs must match GET /v1/models exactly.

Long answers

Telegram rejects messages over 4,096 characters, so the bot splits long answers. Setting max_tokens also keeps answers, and costs, in check.

What it costs to run

With a system prompt, a few turns of history and a short answer, a typical message is around 3,000 tokens in and out. Rough numbers:

SetupPlan tokens per messageMessages per month
Free plan, gpt-6-luna (1× on the free plan)3,000about 660
Starter ($1.20), deepseek-v4-flash (1×)3,00010,000
Starter, claude-sonnet-5 (3×)9,000about 3,300

The free plan also allows 30 requests per minute, 400K tokens per minute and 3 requests at once for the whole account, so it fits a bot for you or a small group. For a public bot, use a paid plan; how multipliers work explains the maths. A separate key for the bot lets you see its usage on its own in Dashboard → Usage.

Going further

  • Run only one copy. If two processes call getUpdates with the same token, Telegram answers the second with a conflict error.
  • Webhooks. Instead of polling, you can register an HTTPS URL with setWebhook and Telegram will POST each update to it. While a webhook is set, getUpdates does not work.
  • Groups. In privacy mode, the default, a bot in a group only sees commands and messages that mention it or reply to it.
  • Streaming. You can stream the answer and edit the Telegram message as it grows; see the streaming docs. Edit every second or so rather than on every chunk, to stay within Telegram's limits.
  • Persistent memory. The history dict is lost on restart. Store it in a small database if you need it to survive.

FAQ

Can I run the bot on the free plan?

Yes, with gpt-6-luna or another free model. The free plan has 1M tokens a month and 30 requests per minute for the whole account, which suits a bot for yourself or a small group. A public bot with many users needs a paid plan.

Why does my bot not answer in a group?

By default Telegram bots run in privacy mode and only see commands and messages that mention them in groups. Mention the bot, reply to it, or change privacy mode with BotFather.

Can I use a Claude model instead?

Yes. Change the model ID to a Claude model such as claude-sonnet-5. Claude models other than Claude Haiku 5.5 need a paid plan and use plan tokens at 3 times the token count.

Where should I keep the keys?

In environment variables on the machine that runs the bot. Both the Telegram bot token and the FreeModel key give control to whoever has them, so never put them in code you share.

Ready to build?

Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.