Guide

Free AI API for a Discord or Telegram bot

A chat bot sends one model request for each message. In a busy server, one free tier reaches its limit in minutes. This guide connects a Discord bot and a Telegram bot to FreeLLMAPI. FreeLLMAPI pools 45 free provider tiers behind one OpenAI-compatible key and moves to the next provider when a limit stops a request. The code is Python and is complete.

Plan for the limits first

Free tiers limit requests per minute and per day. A bot in a server with 200 active users can send thousands of requests per day. Failover spreads these requests over all your keys, but the total is still the sum of the free limits.

  • Answer only when asked. In Discord, answer only mentions. In Telegram groups, answer only commands or replies.
  • Limit each user. Allow one request per user every few seconds.
  • Keep the history short. Send the last 10 messages, not the full channel history.
  • Use a fast route. auto:fast ranks models by speed. Chat users wait less.
  • Fail politely. When every key is at its limit, tell the user to try again later.
Privacy: the bot sends user messages to the provider that answers. Some free tiers can use prompts to improve their models. Tell your users that an AI service reads their messages. Read which free LLM APIs train on your data and remove providers from your chain that you do not accept.

These free models have the fastest measured speed today. Many of them have high request limits:

Fast free chat models
ModelFree onContextFree limits (best offer)ToolsVision
Qwen3.8 27BBlazeAPI, ElectronHub, Gizmo +3 more262K30 req/min
250 req/day
70,000 tokens/min
~6M
YesYes
GPT-OSS 20BApi.Airforce, Cloudflare Workers AI, Groq +4 more131K30 req/min
1,000 req/day
8,000 tokens/min
200,000 tokens/day
~6M
YesNo
Nemotron 3.5 LightningElectronHub, Gizmo, Kilo Gateway +2 more1M20 req/min
50 req/day
50 req/day account-wide (1,000 after a $10 purchase)
YesNo
GPT-OSS 120BCloudflare Workers AI, ElectronHub, Groq +1 more131K30 req/min
1,000 req/day
8,000 tokens/min
200,000 tokens/day
~6M
YesNo
GPT-OSS 20B (via Groq)DreamPrompting131K100 req/min
5,000 req/day
500,000 tokens/day
500K tokens/day · 5,000 req/day
NoNo
GPT-OSS Safeguard 20BGroq131K30 req/min
1,000 req/day
8,000 tokens/min
200,000 tokens/day
~6M
YesNo
Groq Compound MiniDreamPrompting131K100 req/min
5,000 req/day
500,000 tokens/day
500K tokens/day · 5,000 req/day
NoNo
Gemini 3.5 Flash LiteElectronHub, Google AI Studio1M15 req/min
20 req/day
250,000 tokens/min
~3M
YesYes
Step 3.7 FlashElectronHub256K$0.25/week shared recurring creditYesYes
Gemini 3.1 Flash-LiteDreamPrompting, Google AI Studio1M100 req/min
5,000 req/day
500,000 tokens/day
500K tokens/day · 5,000 req/day
YesYes

Showing 10 of 215 matching free models. See all models.

Live data from the FreeLLMAPI catalog (version 2026.11.19, checked 19 November 2026). Free limits change often. The catalog is checked every day.

Shared code: the model call

Both bots use the same module. It keeps a short history for each chat, sends one session ID per chat and handles rate limits. Install FreeLLMAPI first and copy the unified key from the dashboard Keys page.

Install

curl -fsSL https://freellmapi.co/install.sh | bash

python3 -m pip install -U openai discord.py python-telegram-bot
export FREELLMAPI_API_KEY=<unified-key>

brain.py

import asyncio
import os
import time
from collections import defaultdict, deque

import openai
from openai import AsyncOpenAI

llm = AsyncOpenAI(
    base_url="http://localhost:3001/v1",
    api_key=os.environ["FREELLMAPI_API_KEY"],
    max_retries=2,
    timeout=60,
)

SYSTEM = "You are a helpful chat bot. Answer in short paragraphs."
history = defaultdict(lambda: deque(maxlen=10))  # chat id -> last 10 messages
last_call = {}  # user id -> time of the last request
COOLDOWN_S = 5

async def ask(chat_id: str, user_id: str, text: str) -> str:
    now = time.monotonic()
    if now - last_call.get(user_id, 0) < COOLDOWN_S:
        return "Please wait a few seconds before the next question."
    last_call[user_id] = now

    turns = history[chat_id]
    turns.append({"role": "user", "content": text[:4000]})
    messages = [{"role": "system", "content": SYSTEM}, *turns]

    for attempt in range(3):
        try:
            resp = await llm.chat.completions.create(
                model="auto:fast",
                messages=messages,
                max_tokens=800,
                extra_headers={"X-Session-Id": f"chat-{chat_id}"},
            )
            answer = resp.choices[0].message.content or "(no answer)"
            turns.append({"role": "assistant", "content": answer})
            return answer
        except openai.RateLimitError as err:
            header = err.response.headers.get("retry-after", "")
            wait = int(header) if header.isdigit() else 2 ** attempt
            if wait > 30:
                break
            await asyncio.sleep(wait)
        except openai.APIError:
            break
    turns.pop()  # forget the unanswered question
    return "All free models are busy now. Please try again later."

def split(text: str, size: int) -> list[str]:
    return [text[i:i + size] for i in range(0, len(text), size)] or [""]

The X-Session-Id header keeps one chat on one model for 30 minutes. The bot then keeps the same style in a conversation. If that model reaches its limit, the router moves to another model, which gets the same history.

The history and the cooldowns are kept in memory. They are lost when the bot restarts. For a bot that must remember long conversations, store the history in a database such as SQLite or Redis.

Discord bot with discord.py

  1. Open the Discord Developer Portal and create an application. Add a bot and copy its token.
  2. On the bot tab, go to Privileged Gateway Intents. Turn on Message Content.
  3. Invite the bot to your server with the bot scope and the Send Messages permission.
  4. Set the token in the DISCORD_TOKEN environment variable and run the script.

discord_bot.py

import os

import discord

from brain import ask, split

intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")

@client.event
async def on_message(message: discord.Message):
    if message.author.bot or client.user not in message.mentions:
        return
    text = message.content
    for tag in (f"<@{client.user.id}>", f"<@!{client.user.id}>"):
        text = text.replace(tag, "")
    text = text.strip()
    if not text:
        return
    async with message.channel.typing():
        answer = await ask(str(message.channel.id), str(message.author.id), text)
    parts = split(answer, 2000)  # Discord limit: 2000 characters
    await message.reply(parts[0])
    for part in parts[1:]:
        await message.channel.send(part)

client.run(os.environ["DISCORD_TOKEN"])

Telegram bot with python-telegram-bot

  1. In Telegram, open @BotFather and send /newbot. Copy the token.
  2. Set the token in the TELEGRAM_TOKEN environment variable.
  3. Run the script. Send a message to your bot.

telegram_bot.py

import os

from telegram import Update
from telegram.constants import ChatAction
from telegram.ext import Application, ContextTypes, MessageHandler, filters

from brain import ask, split

async def on_text(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.effective_chat.id
    await context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.TYPING)
    answer = await ask(str(chat_id), str(update.effective_user.id), update.message.text)
    for part in split(answer, 4096):  # Telegram limit: 4096 characters
        await update.message.reply_text(part)

def main() -> None:
    app = Application.builder().token(os.environ["TELEGRAM_TOKEN"]).build()
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text))
    app.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == "__main__":
    main()

The typing status in Telegram stays for 5 seconds or less. For slow models, send the chat action again during long requests. The code uses python-telegram-bot version 22, which is fully async.

Ready-made bot agents

If you do not want to write a bot, two agents can answer on Discord and Telegram and use FreeLLMAPI as their model. FreeLLMAPI has a setup command for each one. Each command supports --dry-run and makes a backup of the configuration first.

AgentSetup commandWhat it writes
OpenClawnpx freellmapi setup-openclaw --url http://localhost:3001 --api-key <unified-key>A freellmapi provider in ~/.openclaw/openclaw.json, default model freellmapi/auto
Hermes Agentnpx freellmapi setup-hermes --url http://localhost:3001 --api-key <unified-key>A custom model block in ~/.hermes/config.yaml

A running OpenClaw or Hermes gateway needs a restart after the setup command.

Run the bot and FreeLLMAPI on the same computer or server. The bot then reaches the gateway on localhost, and the gateway port stays closed to the internet. A small server or a Raspberry Pi is enough for both.

Troubleshooting

ProblemCauseFix
The Discord bot reads empty messagesMessage Content intent is offTurn it on in the portal and in intents.message_content
The bot answers its own messagesNo check for bot authorsReturn when message.author.bot is true
Discord error 50035 on long answersThe message is longer than 2000 charactersSplit the answer, as in the code above
"All free models are busy" in the eveningAll keys in the chain are at their daily limitAdd keys from more providers. Many daily limits reset at midnight UTC.
Slow answersA slow model or a long historyUse auto:fast and keep 10 messages or fewer
Connection refused from the botThe bot runs in Docker and uses localhostUse host.docker.internal or a shared Docker network
Use every one of these through one key. FreeLLMAPI is an open-source, self-hosted router that puts all these free tiers behind a single OpenAI-compatible endpoint and fails over when one is rate-limited. Browse the catalog or go live.

Frequently asked questions

Is there a free AI API for a Discord bot?

Yes. Several providers have free tiers that work with the openai Python package. FreeLLMAPI combines them behind one key, so a busy bot can use the limits of many providers.

Can I make a free AI Telegram bot?

Yes. Use python-telegram-bot for the bot and an OpenAI-compatible free API for the answers. The code on this page is complete.

How do I stop my AI bot from hitting rate limits?

Answer only mentions or commands, limit each user to one request every few seconds, keep the history short and add keys from more providers.

Why does my Discord bot get empty message content?

The Message Content intent is off. Turn it on in the Developer Portal on the bot tab, and set intents.message_content = True in the code.

What happens when all free models are at their limit?

FreeLLMAPI returns error 429 with a Retry-After header. The bot code catches it and tells the user to try again later.

Sources

All guides · Browse all free models

Keep reading

All posts →
Guide

Best free LLM APIs 2026

Ten genuinely free LLM APIs worth using — ranked, with real limits.

Guide

Unlimited free AI tokens?

No free AI API is unlimited. The closest real thing: 10.1 billion free tokens a month behind one key.

Guide

How to get a free LLM API key

Get a working key in minutes — no credit card required.