EN ▾
Get API key

Discord Bot for Twitter Posts: Draft Them With an LLM

Updated

A Discord bot for Twitter posts can turn a rough topic into several ready drafts inside a channel your team already uses. This article shows the workflow, a system prompt, working Python code and the limits you should plan around.

Isometric illustration of a chat channel feeding a relay that outputs three draft post cards

What this bot does and what it does not

A Discord bot for Twitter posts is, in practice, a drafting desk. Someone types a slash command such as /draft with a topic, a tone and maybe a few facts. The bot sends that to an LLM, gets back a handful of short drafts, and shows them in the channel. People react, edit, and copy the winner into X by hand or through whatever scheduler you already use.

That design is deliberate. Keeping a human between the model and the public account avoids a whole class of problems: a draft that sounds fine in isolation but lands badly in context, a claim the model made up, or an automation setup that breaks the rules of the platform. Rules about automated posting change, so check X's current developer terms before you connect any script to an account. Nothing below needs those credentials.

It also means the bot never has to read X. This service is a text model behind an OpenAI-compatible endpoint. It cannot browse, it cannot see your timeline, and it does not know what happened this morning. Whatever it should know, you put in the prompt.

Why use an uncensored model for this at all? Some teams write for audiences where a filtered model keeps refusing: dark humour accounts, horror and fiction communities, edgy brand voices, adult-oriented creators who work within the law. The model here is tuned to answer without content refusals for lawful adult use. It still has one hard limit: no sexual content involving minors.

The workflow in five steps

  1. Collect input. The slash command takes a topic (required), a tone (optional) and a block of facts (optional). Facts matter most, because they keep the model from inventing details.
  2. Build the prompt. A fixed system prompt carries your voice rules; the user message carries the topic and facts.
  3. Call the API. One request to POST /v1/chat/completions with model uncensored and JSON mode on, asking for a list of drafts.
  4. Check the result in code. Parse the JSON, drop drafts that are too long or empty, strip banned words you keep in a list.
  5. Post to the channel. Number the drafts so the team can react with 1, 2 or 3.

Slash commands give you three seconds to respond before Discord marks the interaction as failed. A model call takes longer than that, so call defer() first and send the answer as a follow-up. The code below does this.

A system prompt that gives usable drafts

Vague prompts produce vague posts. The prompt below states the job, the voice, the format and the failure cases. Edit the voice section for your account; keep the rest.

SYSTEM = '''You write short social posts for one account.
Voice: dry, specific, a little sarcastic. No hashtags unless asked.
No emojis. No questions that end with 'right?'.
Use only facts given in the user message. If a fact is missing, write around it.
Never invent numbers, quotes or names.
Return JSON only, in this shape:
{"drafts": ["...", "...", "..."]}
Write exactly 3 drafts. Each draft must be under 260 characters.'''

Two details are worth explaining. First, the instruction to use only given facts is what stops the made-up statistic, the most common way a drafted post embarrasses you. Second, the stated limit is 260 while the real one is higher, which leaves slack because models count characters poorly. You enforce the true limit in code, not in the prompt.

The bot, start to finish

Install the two libraries with pip install discord.py openai, set DISCORD_TOKEN and LLM_API_KEY as environment variables, and run the file. If you do not have a Discord token yet, the docs cover the API side, and Discord's own developer portal creates the bot token in a couple of minutes.

import os, json
import discord
from discord import app_commands
from openai import AsyncOpenAI

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

SYSTEM = '''You write short social posts for one account.
Voice: dry, specific, a little sarcastic. No hashtags unless asked.
Use only facts given in the user message. Never invent numbers or quotes.
Return JSON only: {"drafts": ["...", "...", "..."]}
Write exactly 3 drafts, each under 260 characters.'''

LIMIT = 280

client = discord.Client(intents=discord.Intents.default())
tree = app_commands.CommandTree(client)


@tree.command(name="draft", description="Draft three short posts")
@app_commands.describe(topic="What the post is about", facts="Facts the model may use")
async def draft(interaction: discord.Interaction, topic: str, facts: str = ""):
    await interaction.response.defer(thinking=True)
    user = f"Topic: {topic}\nFacts: {facts or 'none'}"
    try:
        resp = await llm.chat.completions.create(
            model="uncensored",
            messages=[
                {"role": "system", "content": SYSTEM},
                {"role": "user", "content": user},
            ],
            response_format={"type": "json_object"},
            temperature=0.9,
            max_tokens=500,
        )
        drafts = json.loads(resp.choices[0].message.content)["drafts"]
    except Exception as exc:
        await interaction.followup.send(f"Draft failed: {type(exc).__name__}. Try again.")
        return
    good = [d for d in drafts if isinstance(d, str) and 0 < len(d) <= LIMIT]
    if not good:
        await interaction.followup.send("No usable drafts came back. Run it again.")
        return
    body = "\n\n".join(f"**{i}.** {d}" for i, d in enumerate(good, 1))
    await interaction.followup.send(body[:1900])


@client.event
async def on_ready():
    await tree.sync()


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

The Discord message limit is 2,000 characters, which is why the final send is cut at 1,900. Three drafts of 280 characters fit comfortably, so the cut only matters if something goes wrong.

To test the API call without Discord, run this and look at the JSON:

curl https://api.nsfwttsapi.com/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"uncensored","messages":[{"role":"user","content":"Reply with the JSON {\"drafts\":[\"hello\"]}"}],"response_format":{"type":"json_object"}}'

Settings that change the output

Temperature and seed

Short posts reward variety, so run temperature around 0.8 to 1.0. If you want to reproduce a draft you liked, pass a seed and keep the other settings fixed. Seed is passed through to the model, so treat it as a strong hint for repeatability rather than a guarantee.

Penalties and stop sequences

If the drafts keep opening with the same phrase, raise frequency_penalty a little, to 0.3 or 0.5. A stop sequence is useful when you use plain text instead of JSON: ask for drafts separated by a line containing --- and cut parsing at the third.

max_tokens

It is optional, since the completion can use whatever is left of the 100,000-token window. For a drafting bot, set it anyway. A cap of 500 tokens protects you if the model rambles or the JSON never closes, and it keeps each request cheap.

Why JSON mode and not regex

With response_format set to json_object the reply is a JSON object you can parse. You still wrap the parse in a try block, because a cut-off reply is not valid JSON, and you still validate the field types, as the code above does.

Honest limits: text only, no live data, a big context

This API generates text. It does not make images, so a post that needs a picture still needs another tool. It also does not know the current state of any account, trend or news story. A model working from training knowledge will sound confident about things that changed last week. The fix is the facts field: paste in the release notes, the headline, the quote you are allowed to use.

The context window is 100,000 tokens for prompt plus completion, which is large for this job. You can paste a whole blog post or a changelog and ask for five angles. You can also keep a style file of your twenty best past posts in the system prompt so the model imitates your actual voice. Remember that input tokens are billed on every call, so a 6,000-token style file costs 6,000 input tokens each time it is sent.

Rate limits are generous for a drafting bot. A full key allows 8 concurrent requests and 300 requests per minute. If you exceed them the API returns HTTP 429 with the error code rate_limited or concurrency; on temporary overload it returns 429 with a Retry-After: 5 header. Wait that long and retry once. A small team clicking /draft will not get near the ceiling.

The model is also not a fact checker. Read every draft before it goes out, and reject anything that states a claim you did not supply.

What it costs to run

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. A typical draft request has a system prompt of about 150 tokens, a topic and facts block of about 650 tokens, and an output of about 400 tokens. That is 800 input and 400 output.

  • Input: 800 x $0.15 / 1,000,000 = $0.00012
  • Output: 400 x $0.50 / 1,000,000 = $0.0002
  • Total: $0.00032 per request

A thousand drafting requests cost $0.32. Even a busy channel will spend cents per day. Failed or refused requests are not charged, and credit never expires, so an idle bot costs nothing. You top up with any whole amount from $20 to $500, paid in crypto (USDT on TRC20 or USDC on Base), and top-ups from $50, $100 and $200 earn a 5%, 10% and 15% bonus. Details are on the pricing page.

New users can claim $0.50 of trial credit with one click on the key page after sign-up, enough for roughly 1,500 drafting requests at the cost above. Get the key from the key page; the trial key allows 2 concurrent requests and 60 requests per minute, which is plenty for testing.

Questions and answers

Can the bot post to X on its own?

You can add that step, but this article keeps a person in the loop on purpose. Check X's current developer terms on automated posting before you connect any account.

Does the model know what is trending on X right now?

No. It is a text model with no browsing or live data, so paste the facts and context you want it to use into the prompt.

How many drafts can I request in one call?

As many as fit your output budget. Three to five works well, and asking for them in one JSON object is cheaper than making several calls because the system prompt is sent only once.

Is my prompt data used for training?

No. Prompts are not used for training.

Why did my request return 429?

You passed the limit of requests per minute or concurrent requests, or the service was briefly overloaded. Wait the number of seconds in Retry-After, which is 5 on overload, and retry.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.