EN ▾
Get API key

Telegram Bot API Key: Add an Uncensored LLM

A Telegram bot has one token from BotFather. To make it answer with a language model you add a second credential, the LLM API key, and send each message to an OpenAI-compatible endpoint. Here is the whole path, with code.

Updated

Paper plane flying through a glowing key gateway into chat bubbles, illustrating a Telegram bot linked to an LLM API

Key points

  • The Telegram token and the LLM key are different secrets with different jobs.
  • Use base URL https://api.mimoapi.cc/v1 and model uncensored with the standard OpenAI SDK.
  • Keep history in chat_data, trim it, and split replies at Telegram's 4,096 character limit.
  • Stay under 8 concurrent requests per full key and handle 429 with a five second wait.

Step by step: from nothing to a bot that answers

The fastest way to get a telegram bot api key working with a language model is to collect two credentials and then write about forty lines of code. Here is the order that avoids dead ends.

  1. Create the bot. In Telegram, open a chat with BotFather, send /newbot, choose a name and a username ending in bot. BotFather replies with the bot token. That token is what people usually mean by a bot's API key.
  2. Create the model key. Sign up with Google or with email and password, then open the API key page and copy your key. New users can claim $0.50 of trial credit there with one click; it is valid for 7 days, needs no card and is limited to one per person.
  3. Test the model key alone with the curl call in the next section.
  4. Install the libraries: pip install python-telegram-bot openai.
  5. Export both secrets as environment variables and run the bot.

The model side is a hosted, OpenAI-compatible text API. It runs one open-weight model, tuned to answer without content refusals for lawful adult use, operated by an independent provider. It is not the official API of any model vendor. Everything below uses the base URL https://api.mimoapi.cc/v1 and the model ID uncensored.

Check the LLM key from the command line first

Telegram bots fail quietly. When something is wrong, the user just sees no reply, and the error sits in a log you may not be watching. So prove the model key works before it goes anywhere near the bot.

export LLM_API_KEY="paste-your-key-here"

curl https://api.mimoapi.cc/v1/models \
  -H "Authorization: Bearer $LLM_API_KEY"

curl https://api.mimoapi.cc/v1/chat/completions \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"uncensored","messages":[{"role":"user","content":"Reply with the word ready."}],"max_tokens":10}'

The first call lists the available model, and the second returns a normal chat completion. If you get an authentication error, the key was pasted wrongly, usually with a stray space or a missing character. The response headers include X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency, which are useful when you want a bot command that reports the remaining balance to the owner. The docs show the same request in other languages.

A working bot with per-chat memory

This example uses python-telegram-bot version 20 or newer, which is built on asyncio. It keeps a short history per chat in chat_data, shows the typing indicator while the model works, and offers a /reset command to clear memory.

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

llm = AsyncOpenAI(
    base_url="https://api.mimoapi.cc/v1",
    api_key=os.environ["LLM_API_KEY"],
)

SYSTEM = "You are Vesper, a private writing partner for adult fiction authors. Be direct, stay in the scene, and keep replies under 200 words."

async def reset(update: Update, context: ContextTypes.DEFAULT_TYPE):
    context.chat_data["history"] = []
    await update.message.reply_text("Memory 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[:-20]

    await context.bot.send_chat_action(update.effective_chat.id, "typing")
    resp = await llm.chat.completions.create(
        model="uncensored",
        messages=[{"role": "system", "content": SYSTEM}] + history,
        max_tokens=500,
        temperature=0.85,
    )
    text = resp.choices[0].message.content or "..."
    history.append({"role": "assistant", "content": text})

    for i in range(0, len(text), 4000):  # Telegram allows 4,096 characters per message
        await update.message.reply_text(text[i:i + 4000])

app = ApplicationBuilder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(CommandHandler("reset", reset))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, chat))
app.run_polling()

Polling is the simplest way to run a bot: the script asks Telegram for new messages in a loop, so it works behind a home router with no public address. If you later move to webhooks, the model call stays exactly the same.

Long replies, typing status and splitting

Telegram limits a text message to 4,096 characters. A model reply with a 1,000 token limit will normally fit, but a bot that writes chapters will not, which is why the loop above slices at 4,000 characters. Slicing at a fixed number can cut a word in half. A cleaner approach is to split on the last paragraph break before the limit.

def split_text(text, limit=4000):
    parts = []
    while len(text) > limit:
        cut = text.rfind("\n\n", 0, limit)
        if cut == -1:
            cut = text.rfind(" ", 0, limit)
        if cut == -1:
            cut = limit
        parts.append(text[:cut].strip())
        text = text[cut:].strip()
    if text:
        parts.append(text)
    return parts

The typing indicator expires after about five seconds, and the model may take longer on a big reply. For slow answers, send the action again from a background task every four seconds until the request returns. Or switch on streaming (stream: true) and edit one message with edit_message_text as chunks arrive, once every second or two to stay clear of Telegram's flood limits. A streamed request keeps its concurrency slot until the stream ends, so count that in your budget.

Structured replies with JSON mode and tools

Bots are not limited to chat. A common pattern is a command that turns messy input into structured data: a to-do item, an expense line or a character sheet. JSON mode makes the model return one valid JSON object, which your code can parse without scraping text.

import json

async def parse_note(raw: str) -> dict:
    resp = await llm.chat.completions.create(
        model="uncensored",
        response_format={"type": "json_object"},
        messages=[
            {"role": "system", "content": "Return a JSON object with keys title, tags (list of strings) and due (ISO date or null)."},
            {"role": "user", "content": raw},
        ],
        max_tokens=200,
        temperature=0,
    )
    return json.loads(resp.choices[0].message.content)

Mention the word JSON and the keys you want in the prompt, as shown, and keep the temperature low. For actions that must run real code, such as fetching a stored note or toggling a setting, use tool calling instead: pass tools, run the function the model names, and send back the result as a role: "tool" message. The model can then phrase the outcome in your bot's voice.

Limits, retries and cost

A full key allows 8 requests at once and 300 per minute. A trial key allows 2 at once and 60 per minute. If a group chat becomes busy, extra requests get HTTP 429, with the code concurrency when too many run together and rate_limited when the per-minute count is exceeded. A temporary overload also returns 429 and a Retry-After: 5 header. Wrap the model call in a semaphore of 8 and retry after five seconds, and users will see a slightly slow reply instead of silence.

To estimate the bill, use the price of $0.15 per 1M input tokens and $0.50 per 1M output tokens. Say a private chat sends 2,000 input tokens (system prompt plus history) and gets 500 tokens back. Input is 2,000 x $0.15 / 1,000,000 = $0.0003. Output is 500 x $0.50 / 1,000,000 = $0.00025. One exchange costs $0.00055, so 10,000 exchanges cost $5.50. With a $20 top-up you could serve about 36,000 such exchanges ($20 / $0.00055 is roughly 36,363). Failed or refused requests are not charged, and credit never expires. Current top-up options are on the pricing page.

Security and house rules for the bot

Treat both secrets like passwords. Keep them in environment variables or a secrets manager. A leaked Telegram token lets a stranger control the bot, and a leaked model key lets them spend your credit. If the Telegram token leaks, ask BotFather to revoke it and issue a new one; if the model key leaks, stop using it and contact support. Do not log full request bodies if your users share private text; prompts sent to this API are not used for training, but your own logs are your responsibility.

Decide who may talk to the bot. A public bot with an uncensored model needs a gate. A simple allow-list of Telegram user IDs, checked at the top of every handler, is enough for a private writing tool. For a group, check the member list or use an invite flow. The service is for lawful adult use only, and sexual content involving minors is never permitted, so add a line to your bot's description that says the same.

Prefer hosting the model yourself? The Ollama comparison explains when a local setup makes sense and when a hosted endpoint is the easier choice.

Questions and answers

Where do I find my Telegram bot token?

Message BotFather in Telegram and send /newbot, or use /mybots to see an existing bot and its token. That token only controls the bot on Telegram. It is not the key for the language model.

Can I use the OpenAI Python SDK for the model calls?

Yes. Set base_url to https://api.mimoapi.cc/v1, pass your model key as api_key, and use the model ID uncensored. No other change is needed.

Does the bot need a server with a public address?

Not with polling. The script connects out to Telegram, so a laptop or a small VPS is enough. Webhooks need a public HTTPS address but are optional.

What happens when the credit runs out?

Requests fail until you top up, and the X-Balance-USD response header tells you how much is left. Add a check that warns the owner when the balance drops below a level you choose.

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.