Skip to content
Guides

Discord Bot Image Generation: Images and Clips by API

Discord bot image generation with slash commands: the bot, the API call, posting images and clips, budgets per server and a key kept off Discord.

Updated 6 min read

Discord bot image generation takes three steps: the slash command defers its reply, your bot sends the prompt to an image API and waits for the job, then it posts the file in the channel. With Frameport, one key on the bot's server reaches every model in the catalog, so the same bot can draw with Nano Banana 2.1 at $0.085 an image, edit an attached picture with Frameport Image 1, and make short clips with Grok Imagine.

This guide builds that bot in Python with discord.py: three commands, the request behind each one, how the result gets back to Discord, and the budgets that stop one server from spending your whole balance.

Discord bot image generation in brief

Discord gives a bot three seconds to answer a slash command, and an image or a clip takes longer than that. So each command defers first, which shows "thinking" in the channel, then does the work. Discord's documentation says the interaction token then stays valid for 15 minutes for follow-up messages, which covers most images; the code below falls back to a plain channel message for a clip that takes longer.

CommandModelWhat it sendsPrice
/imagine promptNano Banana 2.1The prompt only$0.085 an image
/edit picture instructionFrameport Image 1The attached picture as a reference, and the instruction$0.025 an image
/clip promptGrok ImagineThe prompt, 5 seconds at 480p$0.465 a clip

Nano Banana 2.1 reads no pictures, so it fits a pure text command. Frameport Image 1 takes up to 10 reference pictures and edits by instruction, which is what an image editor command needs. For clips with sound, swap in Frameport Motion 1, from $0.10 for 5 seconds at 480p.

Set up the bot and the key

  1. In the Discord developer portal, create an application, add a bot and copy its token. Invite it with the bot and applications.commands scopes, and the permissions to send messages and attach files.
  2. Create a Frameport account, add funds, and create an API key for this bot alone. It starts with fp_live_.
  3. Put both secrets in the environment of the machine that runs the bot, never in the code, a repository or a Discord message.
export DISCORD_TOKEN="..."
export FRAMEPORT_API_KEY="fp_live_..."
pip install discord.py

The key spends your balance, so it lives only where the bot runs. Users never see it: they send a command, your server makes the call. A key of its own also means the bot's spend shows under its name in the dashboard, and you can revoke it without touching your other apps (authentication).

From slash command to API request

The whole bot fits in one file. Each command builds a request body, generate() quotes it, checks the server's budget, submits it and waits, and post_result() hands the file to Discord:

bot.py
import asyncio
import datetime
import io
import mimetypes
import os

import aiohttp
import discord
from discord import app_commands

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}
DAILY_BUDGET = float(os.environ.get("SERVER_DAILY_BUDGET", "5"))  # your dollars, per server per day
RATIOS = {"1:1": 1, "3:4": 3 / 4, "4:3": 4 / 3, "9:16": 9 / 16, "16:9": 16 / 9}

spent = {}  # (server id, UTC day) -> dollars charged; use a database in production
session = None


class Refused(Exception):
    """Refused or failed: nothing was charged."""


class Bot(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        global session
        session = aiohttp.ClientSession()
        await self.tree.sync()  # global commands can take a while to show up


bot = Bot()


async def api(method, path, body=None, key=None):
    headers = {**HEADERS, "Idempotency-Key": key} if key else HEADERS
    async with session.request(method, f"{API}{path}", headers=headers, json=body) as res:
        return await res.json()


async def generate(interaction, path, body):
    if interaction.guild_id is None:
        raise Refused("use this command in a server")
    today = (interaction.guild_id, datetime.datetime.now(datetime.timezone.utc).date())
    quote = await api("POST", "/generations/quote", body)
    if quote.get("error"):
        raise Refused(quote["error"]["message"])
    if spent.get(today, 0) + quote["price_usd"] > DAILY_BUDGET:
        raise Refused("this server has used its budget for today")
    # The interaction id makes a retried submit return the first job instead of a second one
    gen = await api("POST", path, {**body, "max_cost_usd": quote["price_usd"]}, key=f"discord-{interaction.id}")
    if gen.get("error"):
        raise Refused(gen["error"]["message"])
    while gen["status"] in ("queued", "running"):
        await asyncio.sleep(3)
        gen = await api("GET", f"/generations/{gen['id']}")
    if gen["status"] == "failed":
        raise Refused(gen["error"]["message"])
    spent[today] = spent.get(today, 0) + gen["cost_usd"]
    return gen


async def reply(interaction, **message):
    # The interaction token lasts 15 minutes; past that, post as the bot
    if discord.utils.utcnow() - interaction.created_at < datetime.timedelta(minutes=14):
        await interaction.followup.send(**message)
    else:
        await interaction.channel.send(**message)


async def post_result(interaction, gen, caption):
    output = gen["outputs"][0]
    async with session.get(output["url"]) as res:  # a signed link: it opens without the key
        data = await res.read()
    name = "result" + (mimetypes.guess_extension(output["content_type"]) or "")
    try:
        await reply(interaction, content=caption, file=discord.File(io.BytesIO(data), filename=name))
    except discord.HTTPException as err:
        if err.status != 413:
            raise
        # Over this server's upload limit: post the signed link, which opens for about an hour
        await reply(interaction, content=f"{caption}\n{output['url']}")


async def run(interaction, path, body, caption):
    await interaction.response.defer(thinking=True)  # within Discord's three seconds
    try:
        gen = await generate(interaction, path, body)
        await post_result(interaction, gen, caption)
    except Refused as err:
        await reply(interaction, content=f"Nothing was made and nothing was charged: {err}")


def per_user(interaction):
    return (interaction.guild_id, interaction.user.id)


@bot.tree.command(description="Generate an image from a prompt")
@app_commands.checks.cooldown(1, 30, key=per_user)
async def imagine(interaction: discord.Interaction, prompt: str):
    body = {"model": "nano-banana-2-1", "prompt": prompt, "aspect_ratio": "1:1"}
    await run(interaction, "/images/generations", body, f"{interaction.user.mention}: {prompt[:300]}")


@bot.tree.command(description="Edit a picture with an instruction")
@app_commands.checks.cooldown(1, 30, key=per_user)
async def edit(interaction: discord.Interaction, picture: discord.Attachment, instruction: str):
    if not (picture.content_type or "").startswith("image/"):
        await interaction.response.send_message("Attach a PNG, JPEG or WebP picture.", ephemeral=True)
        return
    shape = picture.width / picture.height if picture.width and picture.height else 1
    body = {
        "model": "fp-image-1",
        "prompt": f"Edit the picture: {instruction}. Keep everything else as it is.",
        "reference_images": [picture.url],
        "aspect_ratio": min(RATIOS, key=lambda name: abs(RATIOS[name] - shape)),
    }
    await run(interaction, "/images/generations", body, f"{interaction.user.mention}: {instruction[:300]}")


@bot.tree.command(description="Make a short clip from a prompt")
@app_commands.checks.cooldown(1, 120, key=per_user)
async def clip(interaction: discord.Interaction, prompt: str):
    body = {"model": "grok-imagine", "prompt": prompt, "duration": 5, "resolution": "480p", "aspect_ratio": "16:9"}
    await run(interaction, "/videos/generations", body, f"{interaction.user.mention}: {prompt[:300]}")


@bot.tree.error
async def on_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.CommandOnCooldown):
        await interaction.response.send_message(f"Wait {error.retry_after:.0f} s for the next one.", ephemeral=True)
    else:
        raise error


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

Three details carry the design:

  • The quote comes first. POST /v1/generations/quote takes the same body and answers with price_usd without holding or starting anything, so the bot can refuse a request the server's budget no longer covers before any money moves (quotes).
  • max_cost_usd caps each request at the quoted price. A request that would cost more is refused with 400 max_cost_exceeded, also before anything is held.
  • The Idempotency-Key is the interaction's id. If your bot retries a submit after a network error, the API returns the first job rather than starting and charging a second one (idempotency).

The bot uses aiohttp, which discord.py installs, because a blocking HTTP call would freeze every other command while one job runs. A generation moves from queued to running to succeeded or failed, and reads are not counted against your limits. For the image endpoint's fields, see the images reference; for the same calls in a script, the image generation API guide for Python.

Posting the result back to Discord

Each output carries a signed url that opens without a key for about an hour, and a content_type. The bot downloads the file and attaches it, so the image stays in the channel after that link expires.

  • Size limits. Discord sets how large an attachment may be, and its interaction object carries an attachment_size_limit field in bytes. The code catches the 413 an oversized upload gets and posts the signed link instead. A clip at 480p is the easiest way to stay under the limit.
  • Your own copy. Files are not kept forever on our side. A bot that keeps a gallery copies each file to its own storage and posts that link (files).
  • The 15-minute token. A clip that outlasts the interaction token is posted with the bot's own token, in the same channel, with the user mentioned.

A bot that serves many servers should stop polling each job. Add an endpoint under Webhooks in the dashboard, and Frameport posts the generation to your server the moment it settles, signed with your endpoint's secret (webhooks). Keep a table of generation ids and the channels that asked for them, and post when the delivery arrives. Polling vs webhooks weighs the two, and how to combine them.

Budgets and abuse

A public bot spends your money on behalf of strangers, so give it limits at every level:

  • Per server, per day. The spent table above refuses requests past SERVER_DAILY_BUDGET. In production, keep it in a database, so a restart does not reset it.
  • Per user. The cooldowns stop one person from queuing a hundred jobs: one image every 30 seconds, one clip every two minutes.
  • Per workspace. All the keys of a workspace share 60 requests that start work a minute and 20 jobs running at once. Past either, the API answers 429 with a Retry-After header, and the bot passes the message on (rate limits).
  • Per request. max_cost_usd refuses anything priced above the quote.
  • A record. Log the Discord user id next to each generation id, so you can act on a report about an image.

Every workspace starts with its content filter on, and a public server is where it belongs. A prompt it blocks is refused with 400 content_filtered before anything is held. The filter is a workspace setting shared by every key, so a bot that needs another setting runs in a workspace of its own. In that workspace, only an owner or an admin aged 18 or older can turn the filter off, in Settings; then our own models, such as Frameport Image 1, render with no content filter. That is what an unrestricted Discord bot means here, and it has limits: models from other makers, such as Nano Banana 2.1 and Grok Imagine, keep their makers' policies and may refuse, and the acceptable use policy applies either way: nothing involving minors, no real identifiable people without their consent, nothing illegal. You answer for what people make through your keys, and Discord's own rules apply to what your bot posts. A refused request costs nothing.

Give the bot a key of its own, kept on the server (API key security), and to let people start from their own pictures, see how to upload an image to the API.

FAQ

How do I make a Discord bot that generates images?

Register a slash command, defer the reply as soon as it arrives, send the prompt to an image API from your bot's server, wait for the job, then post the file as an attachment. The script above does all of it with discord.py and one Frameport key.

Can I use Midjourney in my own Discord bot?

Not through Frameport: Midjourney is not in the catalog. The bot above uses models that are, such as Nano Banana 2.1 and Frameport Image 1, on one key. The Midjourney API alternative compares the options.

Can a Discord bot edit pictures?

Yes. Take the picture as an attachment option and send its URL in reference_images to a model that edits by instruction, such as Frameport Image 1 or Nano Banana Pro, with the change written in the prompt.

Why does my bot say "The application did not respond"?

It did not answer within Discord's three seconds. Defer the reply first, then generate: interaction.response.defer() must run before any slow call.

Is there a free Discord AI image generator bot?

Not one that renders for free. Your account, the API key and price quotes cost nothing, and a job that fails is never charged, but each image or clip is paid from a prepaid balance, from $0.025 an image. You can try the prompts in the Studio before you wire them into the bot.

Pricing6 min read

Cheapest Image Generation API Models (2026)

The cheapest image generation API models in our catalog, what each gives up for its price, and how batches and per-image billing set the real cost.

Start building.

Your API key is free. Top up from $10 when you are ready.