EN ▾
Get API key

Telegram Bot API GitHub Examples With an LLM Backend

Searching for a telegram bot api github example usually ends with a repo that echoes messages back. This article takes that skeleton and plugs in a chat model over an OpenAI-compatible API, with streaming, memory and sane handling of limits.

Updated

A chat bubble sending messages along a glowing path to a server, representing a Telegram bot with an LLM backend

How a Telegram bot with an LLM backend works

If you are looking at a telegram bot api github repository as a starting point, the shape is almost always the same. Telegram exposes an HTTP Bot API. Your program either asks Telegram for new messages (long polling with getUpdates) or tells Telegram to push them to a public URL (a webhook set with setWebhook). For each text message you decide what to send back, and Telegram delivers the reply to the chat.

Adding a language model changes one step. Instead of echoing the text, the handler sends the conversation to a chat completions endpoint and returns what the model writes. Since our API is OpenAI-compatible, the model call is the same code you would write for any OpenAI client, with a different base URL and key. The model ID is uncensored.

Telegram bots are popular for fiction, roleplay and companion characters because the chat interface is already there. The people on the other end are adults using a lawful tool for stories and conversation, and your bot should say so in its description. The model is tuned to answer without content refusals for lawful adult use, and one limit is fixed: no sexual content involving minors. If you run a public bot, state that rule in the bot's /start message and enforce your own moderation on top.

What you need before writing code

  • A bot token. You get one by messaging the official BotFather account in Telegram and creating a new bot.
  • An API key for the LLM endpoint. The API key page explains sign-up, and new users can claim $0.50 of trial credit with one click, no card needed.
  • Python 3.10 or newer, plus the python-telegram-bot and openai packages.

Project layout and secrets

Most of the repos you will find on GitHub for this are small: one file for the bot, one for settings, a requirements file and a README. A clean layout has these files.

  • bot.py: handlers and the model call
  • requirements.txt: pinned dependencies
  • .env.example: variable names with fake values
  • .gitignore: lists .env
  • README.md: how to run it

The single most common mistake in public bot repos is a committed token. Telegram bot tokens and API keys give full control of whatever they belong to, so treat them like passwords. Put them in environment variables, list .env in .gitignore, and commit only an example file with fake values. If a token ever lands in a commit, rotate it right away; deleting the file in a later commit does not remove it from history.

# .env.example  (copy to .env and fill in; .env stays out of git)
TELEGRAM_BOT_TOKEN=123456:replace-me
UNFILTERED_API_KEY=replace-me
UNFILTERED_BASE_URL=https://api.unfilteredgpt.cc/v1
LLM_MODEL=uncensored

When you deploy from GitHub, use the host's secret store or GitHub Actions secrets instead of baking values into an image. The code reads everything from the environment, so the same file runs on your laptop and on a server.

A working bot in one file

This version answers every text message, keeps the last few turns per chat, and sends a typing indicator while the model works. Install the packages with pip install python-telegram-bot openai and load the variables from your shell or a tool such as python-dotenv.

import os
from openai import AsyncOpenAI
from telegram import Update
from telegram.ext import (
    ApplicationBuilder, CommandHandler, MessageHandler,
    ContextTypes, filters,
)

client = AsyncOpenAI(
    base_url="https://api.unfilteredgpt.cc/v1",
    api_key=os.environ["UNFILTERED_API_KEY"],
)

SYSTEM = (
    "You are a storytelling partner for adult users. "
    "Stay in character, keep replies under 250 words, and never write "
    "sexual content involving minors."
)
MAX_TURNS = 12  # user+assistant pairs kept per chat


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.chat_data["history"] = []
    await update.message.reply_text("Ready. Send a message to begin. Use /reset to start over.")


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


async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
    history = context.chat_data.setdefault("history", [])
    history.append({"role": "user", "content": update.message.text})
    del history[: -MAX_TURNS * 2]

    await context.bot.send_chat_action(chat_id=update.effective_chat.id, action="typing")
    resp = await client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "system", "content": SYSTEM}] + history,
        max_tokens=600,
        temperature=0.9,
    )
    text = resp.choices[0].message.content or "(no reply)"
    history.append({"role": "assistant", "content": text})
    await update.message.reply_text(text[:4096])


def main():
    app = ApplicationBuilder().token(os.environ["TELEGRAM_BOT_TOKEN"]).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()


if __name__ == "__main__":
    main()

Three details matter. Telegram caps a text message at 4096 characters, so the code slices the reply. chat_data is held in memory, so history disappears when the process restarts; swap in SQLite or Redis once the bot matters to anyone. And max_tokens is optional on this API, but a limit stops one runaway reply from eating your balance.

Streaming replies by editing one message

Long answers feel slow in a chat window. The fix is to send a placeholder, stream tokens from the API with stream: true, and edit the placeholder as text arrives. Telegram limits how fast you can edit, so update every second or so, not on every token.

import time
from openai import AsyncOpenAI
from telegram.error import BadRequest

client = AsyncOpenAI(
    base_url="https://api.unfilteredgpt.cc/v1",
    api_key=os.environ["UNFILTERED_API_KEY"],
)


async def safe_edit(msg, text):
    try:
        await msg.edit_text(text[:4096])
    except BadRequest:
        pass  # "message is not modified" and similar harmless cases


async def stream_reply(update, messages):
    msg = await update.message.reply_text("...")
    stream = await client.chat.completions.create(
        model="uncensored",
        messages=messages,
        stream=True,
        max_tokens=700,
    )
    buf, last = "", 0.0
    async for chunk in stream:
        if not chunk.choices:
            continue  # the final chunk carries usage, not text
        delta = chunk.choices[0].delta.content
        if delta:
            buf += delta
            if time.monotonic() - last > 1.2:
                await safe_edit(msg, buf)
                last = time.monotonic()
    await safe_edit(msg, buf or "(no reply)")
    return buf

Streaming over SSE ends with a usage record, which is why the loop skips chunks with no choices. Remember that a streamed request holds its concurrency slot until the stream finishes. A slow reader or a stuck loop keeps that slot busy, which matters in the next section.

Rate limits, errors and many users at once

A bot with ten active chats can easily send ten requests at once. A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 concurrent and 60 per minute. Over a limit the API returns HTTP 429 with the error code rate_limited (too many requests per minute) or concurrency (too many at once). On temporary overload it also answers 429, with a Retry-After: 5 header.

Put a semaphore in front of the model call so extra messages wait instead of failing, and retry once on 429.

import asyncio
import os
from openai import AsyncOpenAI, RateLimitError

client = AsyncOpenAI(
    base_url="https://api.unfilteredgpt.cc/v1",
    api_key=os.environ["UNFILTERED_API_KEY"],
)
slots = asyncio.Semaphore(6)  # stay under the 8-request cap on a full key


async def complete(messages):
    async with slots:
        for attempt in range(2):
            try:
                r = await client.chat.completions.create(
                    model="uncensored", messages=messages, max_tokens=600
                )
                return r.choices[0].message.content or ""
            except RateLimitError:
                await asyncio.sleep(5)  # matches Retry-After: 5
    return "The service is busy. Please try again in a moment."

Use a smaller number, such as 1 or 2, if you are still on the trial key. The response headers help with monitoring: X-Balance-USD shows your remaining credit, and X-Request-Id is what you quote if you contact support. The OpenAI SDK exposes headers through client.chat.completions.with_raw_response.create(...).

Failed or refused requests are not charged, so retries after an error do not cost you extra.

What it costs to run a bot

Price is $0.15 per 1M input tokens and $0.50 per 1M output tokens, from prepaid credit. A typical chat turn in the bot above re-sends the system prompt and up to 12 earlier pairs. Take 1,500 input tokens and 300 output tokens as a realistic average.

  • Input per message: 1,500 tokens x $0.15 / 1M = $0.000225.
  • Output per message: 300 tokens x $0.50 / 1M = $0.00015.
  • One message: $0.000375.
  • 1,000 messages: $0.375 (that is 1.5M input tokens for $0.225 plus 0.3M output tokens for $0.15).

A $20 top-up therefore covers a little over 53,000 messages at this size. Shorter history lowers the input side, and a smaller max_tokens lowers the output side. Top-ups run from $20 to $500 in any whole amount, with +5% from $50, +10% from $100 and +15% from $200, and credit never expires, so a hobby bot can sit idle without losing money. Details are on the pricing page.

Long context, tools and polishing the repo

The context window is 100,000 tokens, prompt plus completion. For a Telegram bot that means you rarely need to summarize history early. Twelve turns is a cost choice, not a technical limit. A story bot can keep far more of a conversation if you accept the higher input bill, and you can store a short summary of older turns instead of dropping them.

Tool calling and JSON mode are available too. A bot can expose a dice roller or a character sheet lookup as a tool and let the model decide when to call it, or ask for JSON output to drive inline keyboards. See the API docs for request examples.

Before you push to GitHub

  1. Check git status and git diff --staged for anything that looks like a token.
  2. Write the README so a stranger can run the bot: list the environment variables, the Python version and the start command.
  3. Add a line about the bot's intended audience and the minors rule.
  4. Pin dependency versions in requirements.txt so a future release does not break your bot.
  5. Choose a license on purpose, even a permissive one, so others know what they may do with the code.

That gives you a repo that is safe to publish and useful to others who find it with the same search.

Questions and answers

Can I use the OpenAI Python SDK in a Telegram bot with this API?

Yes. Create the client with base_url set to https://api.unfilteredgpt.cc/v1 and your key, then call chat.completions.create with the model uncensored. Nothing else in the bot changes.

Should I use polling or a webhook?

Long polling is simpler and works behind any firewall, so start there. Switch to a webhook when you run on a server with a public HTTPS address and want lower idle overhead.

Why did my bot get HTTP 429?

You passed 8 concurrent requests or 300 per minute on a full key (2 and 60 on a trial key), or the service was briefly overloaded. The error code is rate_limited or concurrency, and waiting 5 seconds before retrying is the right response.

Is it safe to put my keys in a GitHub repo?

No. Keep the bot token and API key in environment variables or a secret store, ignore the .env file in git, and rotate any key that was ever committed.

How do I stop the bot from forgetting the conversation?

Store each chat's messages in a database such as SQLite and load the last turns on every message. The model itself keeps no memory between requests, so you send the history each time.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Start with trial credit

Email and password, key on screen right away.