Skip to main content
Integrations

Discord Bot

Build a Discord bot with discord.py and the OpenAI Python SDK using AICredits as the OpenAI-compatible API endpoint.

Use this page with an AI assistant

Opens a new chat with this docs URL and the correct AICredits base URLs.

Use discord.py with the OpenAI Python SDK to build a Discord bot that calls AICredits. Each message is billed through your AICredits wallet and appears in the usage dashboard.

Setup

Install the libraries in your bot project:

pip install discord.py openai

Set secrets as environment variables:

export DISCORD_BOT_TOKEN="your-discord-bot-token"
export AICREDITS_API_KEY="sk-your-aicredits-key"

Bot Example

bot.py
import asyncio
import os
from collections import defaultdict, deque

import discord
from openai import AsyncOpenAI, APIStatusError

client = AsyncOpenAI(
    base_url="https://api.aicredits.in/v1",
    api_key=os.environ["AICREDITS_API_KEY"],
)

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

history_by_channel: dict[int, deque[dict[str, str]]] = defaultdict(lambda: deque(maxlen=12))


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


@bot.event
async def on_message(message: discord.Message):
    if message.author.bot:
        return

    if bot.user not in message.mentions:
        return

    channel_history = history_by_channel[message.channel.id]
    prompt = message.content.replace(f"<@{bot.user.id}>", "").strip()
    channel_history.append({"role": "user", "content": prompt})

    messages = [
        {"role": "system", "content": "You are a concise Discord assistant."},
        *channel_history,
    ]

    async with message.channel.typing():
        try:
            response = await client.chat.completions.create(
                model="openai/gpt-4o-mini",
                messages=messages,
                max_tokens=600,
            )
        except APIStatusError as exc:
            if exc.status_code == 402:
                await message.reply("AICredits wallet balance is low or this key hit its budget limit.")
                return
            if exc.status_code == 429:
                await message.reply("Rate limit reached. Please try again in a moment.")
                return
            raise

    answer = response.choices[0].message.content or ""
    channel_history.append({"role": "assistant", "content": answer})
    await message.reply(answer[:1900])


asyncio.run(bot.start(os.environ["DISCORD_BOT_TOKEN"]))

Token and Cost Controls

  • Set max_tokens on every request so one Discord message cannot produce an unexpectedly long reply.
  • Keep a short per-channel history, such as the last 6 user/assistant turns.
  • Use a lower-cost default model like openai/gpt-4o-mini, then switch specific commands to larger models when needed.
  • Set an API-key budget cap in Dashboard → API Keys for bot deployments.

Verify

Mention the bot in a channel:

@your-bot Reply with "AICredits via Discord" and nothing else.

Then check Dashboard → Usage for the model, tokens, latency, and INR cost.

Troubleshooting

402 Payment Required — Add wallet credits or raise the key's budget cap.

429 Too Many Requests — Reduce parallel bot requests, add a queue, or lower the bot's Discord command fan-out.

Bot never responds — Enable the Discord message content intent for your bot and confirm the bot is invited with permission to read and send messages.