Discord Bot Image Recognition With a Text LLM API
A text API cannot look at a picture, so the honest design is two steps: something else describes the image, and the language model answers the description. Here is how to wire that up in a Discord bot.
Updated

Key points
- This API is text only. It does not read image attachments, so a captioning or vision step must run first.
- The pipeline is attachment, caption text, chat completion, reply, all in one async handler.
- Cap parallel calls with a semaphore: a full key allows 8 concurrent requests and 300 per minute.
- A reply with 1,500 input and 200 output tokens costs $0.000325, so 10,000 replies cost about $3.25.
Start with what this API can and cannot do
People who search for discord bot image recognition usually want one of two things: a bot that tells what is in an uploaded picture, or a bot that reacts intelligently to pictures in a chat. The API on this site covers only the second half. It is a hosted, OpenAI-compatible text model with the ID uncensored. It accepts text and returns text. It does not accept image input, and it does not generate images, audio or video.
That limit does not make it useless for image-aware bots. Recognition is one job, conversation is another, and you can split them. A vision or captioning tool turns the picture into words. This API takes the words, your persona prompt and the channel history, and writes the reply. The quality of the final answer depends on how good the caption is, so choose the recognition tool for your needs and check its current terms and pricing yourself.
The rest of this article builds the conversation half, with a clean place to plug in whichever recognition tool you pick.
The pipeline
- A member posts a message, perhaps with an attachment.
- The bot checks whether the message is addressed to it (a mention or a command prefix).
- For each image attachment, the bot calls your recognition function and gets a short text description.
- The bot assembles a chat prompt: persona as the system message, recent channel messages as history, the user's text plus the image description as the latest message.
- The bot calls
POST /v1/chat/completionsand posts the answer back.
Step three is the only place where images matter. Everything else is ordinary text chat. If you later swap the recognition tool, nothing else in the bot changes.
Setting up the Discord side
Create an application in the Discord developer portal, add a bot user and copy its token. Keep the token in an environment variable, never in code or a repository. To read message text, enable the Message Content privileged intent for the bot in the portal and in your code; without it, messages arrive with empty content. Invite the bot to your server with permission to read and send messages in the channels you choose.
If your server hosts adult fiction or roleplay, keep the bot confined to channels your server rules and Discord's current community guidelines allow for that, and keep the model prompt aligned with them. The model is tuned for lawful adult use, and one rule is fixed: no sexual content involving minors.
Install the libraries with pip install discord.py openai. Get an API key from the key page; the free $0.50 trial credit is enough to test everything below, with a trial limit of 2 concurrent requests and 60 per minute.
The bot
This version keeps short per-channel history in memory, calls a placeholder describe_image for attachments, and splits long answers to fit Discord's 2,000-character message limit.
import asyncio
import os
from collections import defaultdict, deque
import discord
from openai import AsyncOpenAI
llm = AsyncOpenAI(base_url="https://api.nsfwimageapi.com/v1", api_key=os.environ["LLM_KEY"])
slots = asyncio.Semaphore(6) # stay under 8 concurrent on a full key
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
PERSONA = "You are Ember, a witty narrator bot for an adult fiction server. Keep replies under 150 words."
history = defaultdict(lambda: deque(maxlen=12))
async def describe_image(attachment: discord.Attachment) -> str:
"""Plug in your own vision or captioning service here.
It must return a short plain-text description of the image."""
return f"[image attached: {attachment.filename}, no description available]"
def chunks(text: str, size: int = 1900):
for i in range(0, len(text), size):
yield text[i:i + size]
@bot.event
async def on_message(message: discord.Message):
if message.author == bot.user or bot.user not in message.mentions:
return
text = message.clean_content.replace("@" + bot.user.display_name, "").strip()
for att in message.attachments:
if att.content_type and att.content_type.startswith("image/"):
text += "\n(Image description: " + await describe_image(att) + ")"
channel_log = history[message.channel.id]
channel_log.append({"role": "user", "content": text})
async with message.channel.typing():
async with slots:
resp = await llm.chat.completions.create(
model="uncensored",
messages=[{"role": "system", "content": PERSONA}, *channel_log],
temperature=0.8,
max_tokens=400,
)
answer = resp.choices[0].message.content
channel_log.append({"role": "assistant", "content": answer})
for part in chunks(answer):
await message.reply(part)
bot.run(os.environ["DISCORD_TOKEN"])A few details are deliberate. The deque with maxlen=12 keeps the prompt from growing forever, which controls cost. The semaphore sits around the API call only, so slow Discord replies do not hold a slot. The image description goes in as plain text in the user message, so the model treats it as context the user supplied.
Handling rate limits and errors
A busy server can fire many mentions at once. A full key allows 8 concurrent requests and 300 requests per minute. Over the limit, the API answers 429 with the error code rate_limited or concurrency, and on temporary overload it adds a Retry-After: 5 header. The OpenAI Python SDK retries 429 responses by default, and for a small bot that is enough. For a large one, put a queue in front of the semaphore and tell the user "one moment" when the queue is long.
Also catch exceptions around the call and post a short apology instead of leaving the channel silent. Failed requests are not charged, so a retry does not cost you.
If you stream replies by editing a message as tokens arrive, remember that a streamed request holds its concurrency slot until the stream ends, and that Discord limits how often a message can be edited. For most bots, waiting for the full answer and sending it once is simpler and cheaper to run.
What it costs to run
Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Suppose each reply sends 1,500 input tokens (persona, 12 messages of history, the new message and an image caption) and generates 200 output tokens.
- Input: 1,500 / 1,000,000 x $0.15 = $0.000225.
- Output: 200 / 1,000,000 x $0.50 = $0.0001.
- Per reply: $0.000325.
- For 10,000 replies: 10,000 x $0.000325 = $3.25.
The caption text barely changes this. A 100-token description adds 100 / 1,000,000 x $0.15 = $0.000015 per reply. The recognition tool you choose will likely cost more than the text reply, so look at its pricing before you commit to it. Top-ups start at $20 in USDT on TRC20 or USDC on Base, with bonuses from $50; the pricing page has the full list.
Ideas for making the bot better
After the basics work, a few additions pay off quickly. Store each channel's history in a small database instead of memory, so a restart does not wipe the conversation. Give each channel its own persona prompt so a roleplay room and a general chat room behave differently. Add a slash command that lets moderators reset or pause the bot.
For image-aware features, think about what a short caption gives the model. A caption such as "a dog on a beach at sunset" is enough for a friendly reply, but not enough to judge fine detail. Ask your recognition tool for the level of detail the conversation needs and no more, since longer captions add input tokens on every following turn while the image stays in the history.
One more habit: log the request ID from each response next to the Discord message ID. When a user reports a strange answer, you can trace it to one exact call.
Next steps
Once the loop works, add a per-user cooldown, a command to reset the channel history, and a moderation rule for your own server. The quickstart covers tool calling and JSON mode, which are handy if you want the bot to return structured actions such as "post this to the gallery channel". For the wider picture of what a text layer does in an adult-content stack, read the page on the uncensored LLM API for adult content.
More guides
Questions and answers
Can this API recognize what is in an image?
No. It is text only and does not accept image input. Use a separate vision or captioning tool and pass its text description to the model.
Does it work with discord.py?
Yes. Use the OpenAI Python SDK with the base URL https://api.nsfwimageapi.com/v1 and the model ID uncensored inside any discord.py event handler.
How many users can the bot serve at once?
A full key allows 8 concurrent requests and 300 per minute. A trial key allows 2 concurrent and 60 per minute.
How do I keep the bot from replying too slowly?
Set max_tokens to a modest value, keep the history short, and send the reply once complete. Show the typing indicator while the request runs.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.