EN ▾
Get API key

Discord Bot for News: Build One With an LLM API

A discord bot for news needs three parts: a way to fetch headlines, a model that turns them into a readable summary, and a slash command to ask for it. This guide builds all three in about 100 lines of Python.

Updated

Terminal at a desk taking in streams of feed items and sending out chat bubbles, illustrating a Discord news bot

Key points

  • The bot exposes an RSS reader to the model as a tool, so the model summarises real headlines instead of guessing.
  • Use the OpenAI SDK with base URL https://api.wannsfw.com/v1 and model uncensored.
  • Defer the Discord reply and cap messages at 2,000 characters.
  • One /news command costs about $0.0005, so 1,000 commands cost around $0.50.

How the bot works

The idea behind a discord bot for news is simple, and the one thing to get right is where the facts come from. A language model has no live knowledge of today's events. If you ask it for the news, it will invent something plausible. So the bot must hand the model real text and ask it only to summarise.

That is what tool calling is for. You describe a function, get_headlines, to the model. When a user asks "what is happening in tech?", the model replies with a request to call that function. Your code fetches the RSS feed, sends the result back as a role: "tool" message, and the model writes the summary from the entries it received. This API supports tools, tool_choice, streamed tool_calls and tool results, in the same format as the OpenAI SDK.

Why a model without content refusals? News is not always gentle. A bot for a community that follows crime reporting, conflict coverage or true-crime podcasts needs a summariser that does not refuse every grim headline. The model behind this API is tuned to answer without content refusals for lawful adult use. Run such a bot only in adult communities, and keep to the rules of Discord and of the news sources you use.

Prerequisites

  • Python 3.10 or newer.
  • A Discord application with a bot token, created in the Discord developer portal, and the bot invited to your server with the applications.commands scope.
  • An API key from the key page. A trial of $0.50 is available after sign-up with one click and no payment method.
  • One or more RSS or Atom feed URLs from sources whose terms allow this use.
pip install discord.py openai feedparser

Pick feeds with a clear purpose. Five narrow feeds that match your community's interests produce better summaries than one giant general feed, because the model sees fewer irrelevant items and you pay for fewer tokens. Check each publisher's terms before you republish their text in a channel; linking back to the original is the safe habit.

Put the secrets in environment variables, never in the source:

export API_KEY="your-api-key"
export DISCORD_TOKEN="your-discord-bot-token"

The tool: read a feed

Start with the function the model will call. feedparser is synchronous, so run it in a thread to avoid blocking the bot's event loop. Replace the example feed URLs with real ones.

import asyncio
import json
import feedparser

FEEDS = {
    "world": "https://example.com/world.rss",
    "tech": "https://example.com/tech.rss",
    "science": "https://example.com/science.rss",
}

async def get_headlines(section, limit=6):
    url = FEEDS.get(section)
    if not url:
        return json.dumps({"error": "unknown section"})
    parsed = await asyncio.to_thread(feedparser.parse, url)
    items = []
    for entry in parsed.entries[: max(1, min(int(limit), 10))]:
        items.append({
            "title": entry.get("title", ""),
            "link": entry.get("link", ""),
            "summary": entry.get("summary", "")[:400],
        })
    return json.dumps(items)

TOOLS = [{
    "type": "function",
    "function": {
        "name": "get_headlines",
        "description": "Fetch the latest headlines from one news section.",
        "parameters": {
            "type": "object",
            "properties": {
                "section": {"type": "string", "enum": list(FEEDS)},
                "limit": {"type": "integer", "minimum": 1, "maximum": 10},
            },
            "required": ["section"],
        },
    },
}]

Truncating each summary to 400 characters keeps the tool result small. That matters for cost, since every token you return is billed as input on the next call.

The model loop

The loop sends the question, checks whether the model asked for tools, runs them, and repeats until it gets plain text. A cap on rounds stops a confused model from looping forever.

import os
from openai import AsyncOpenAI

ai = AsyncOpenAI(api_key=os.environ["API_KEY"], base_url="https://api.wannsfw.com/v1")
gate = asyncio.Semaphore(2)

SYSTEM = (
    "You are a news desk assistant in a Discord server. "
    "Call get_headlines before answering any question about current events. "
    "Summarise only what the tool returned, in short bullet points, and give each link. "
    "If the tool returns nothing useful, say so."
)

async def answer(question):
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": question},
    ]
    async with gate:
        for _ in range(4):
            resp = await ai.chat.completions.create(
                model="uncensored",
                messages=messages,
                tools=TOOLS,
                tool_choice="auto",
                temperature=0.3,
                max_tokens=600,
            )
            msg = resp.choices[0].message
            if not msg.tool_calls:
                return msg.content or "No answer."
            messages.append(msg.model_dump(exclude_none=True))
            for call in msg.tool_calls:
                args = json.loads(call.function.arguments or "{}")
                result = await get_headlines(**args)
                messages.append({
                    "role": "tool",
                    "tool_call_id": call.id,
                    "content": result,
                })
    return "Stopped after too many tool rounds."

The semaphore of 2 matches a trial key, which allows 2 concurrent requests. On a full key you can raise it to 8. Keep in mind that a streamed request holds its concurrency slot until the stream ends; this bot does not stream, so each slot frees as soon as the reply arrives.

The Discord side

Discord expects an answer to a slash command within three seconds. A model call plus a feed fetch can take longer, so acknowledge first with defer, then send the real reply as a follow-up. Messages are limited to 2,000 characters, so cut long output.

import discord
from discord import app_commands

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

@tree.command(name="news", description="Summarise the latest headlines")
@app_commands.describe(topic="What do you want to know about?")
async def news(interaction: discord.Interaction, topic: str):
    await interaction.response.defer(thinking=True)
    try:
        text = await answer(topic)
    except Exception:
        text = "The news desk is busy. Try again in a moment."
    await interaction.followup.send(text[:1900])

@bot.event
async def on_ready():
    await tree.sync()
    print("ready as", bot.user)

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

Run the file, type /news topic: tech in your server, and the bot shows a "thinking" state for a few seconds before posting a bulleted summary with links. The first sync of slash commands can take a moment to appear in the client.

Scheduled digests and structured output

A daily digest is a small extension. Discord.py offers discord.ext.tasks for loops, so you can call answer("Give me today's top world and tech stories") every morning and post to a channel. Keep the prompt fixed so the cost per digest stays predictable.

If you want the model to return data instead of prose, for example to build embeds, use JSON mode with response_format={"type": "json_object"} and describe the shape in the system prompt, such as a list of objects with title, why_it_matters and link. Parse it with json.loads and wrap that call in a try block, since any model can occasionally produce a malformed reply.

Three safeguards are worth adding. Ask the model to quote only links that appeared in the tool result, to avoid fabricated URLs. Log the X-Request-Id header on failures so a bad answer can be traced. And rate-limit your own users, for example one command per user every 20 seconds, so one person cannot spend your credit.

Troubleshooting

  • The slash command does not appear. Check that the bot was invited with the applications.commands scope, and wait a minute after tree.sync(). Global commands can be slow to show up.
  • "The application did not respond". The reply took longer than three seconds and was not deferred. Make sure defer is the first awaited call in the handler.
  • The model answers without calling the tool. Make the system prompt firmer, for example "always call get_headlines first", or set tool_choice to a specific function for a command that always needs headlines. Lowering temperature also helps.
  • Arguments fail to parse. Wrap json.loads in a try block and send an error string back as the tool result. The model can then correct itself on the next round.
  • Empty feeds. Some sites block unknown clients or return a redirect. Test each feed URL in a browser, and set a clear user agent if the source asks for one.
  • HTTP 429. Lower the semaphore, or wait and retry. The error code tells you whether the cause was requests per minute or concurrency.

Keep a log line for each command with the user, topic, token usage and the X-Request-Id value. When someone reports a strange summary, that line lets you reproduce what happened.

What it costs and what limits apply

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Estimate one /news command with two model calls. The first call has about 400 tokens in and 60 out, because it only decides to use the tool. The second carries the question, the tool request and about 1,200 tokens of headlines, roughly 1,700 in and 300 out.

  • Input: 2,100 x $0.15 / 1,000,000 = $0.000315
  • Output: 360 x $0.50 / 1,000,000 = $0.00018
  • Per command: $0.000495

That is about $0.50 per 1,000 commands. The trial credit of $0.50, valid for 7 days, would cover roughly a thousand of them in this example, which is more than a small server will use in a week. After that, top up from $20 to $500 with USDT on TRC20 or USDC on Base; bonuses are +5% from $50, +10% from $100 and +15% from $200. Credit never expires, and failed or refused requests are not charged. See the pricing page.

On limits: a full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. If you exceed them you receive HTTP 429, with code rate_limited or concurrency, or a Retry-After: 5 header on brief overload. Catch the error, wait, and retry once. The quickstart covers the request format in more detail.

Questions and answers

Can the bot read live news without a feed?

No. The model has no live knowledge, so the bot has to fetch text itself, for example from RSS feeds, and pass it to the model through a tool or in the prompt.

Why does the bot need defer?

Discord requires a first response to a slash command within three seconds. Deferring buys time for the feed fetch and the model call, and you send the real answer as a follow-up.

How do I avoid made-up links?

Tell the model to cite only links present in the tool result, and keep the tool output small so the instruction is easy to follow. Spot-check the first outputs before opening the bot to a server.

Does this work with the standard OpenAI library?

Yes. Set base_url to https://api.wannsfw.com/v1, use your key, and set the model to uncensored. Tool calling, streaming and JSON mode follow the usual format.

Your key is one form away

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