DEV Community

Cover image for Building a Discourse bot: API keys, signed webhooks, and rate limits
Nathan Tarbert
Nathan Tarbert

Posted on Edited on Originally published at answerloops.com

Building a Discourse bot: API keys, signed webhooks, and rate limits

I work on answerLoops, an open-source tool that answers community support questions, and one of our channels is Discourse. Getting the Discourse side right took more trial and error than I expected, so here's the short version of what a bot that reads a forum and replies actually needs. Four pieces: auth, hearing about new posts, replying, and rate limits.

1. Authenticate as a bot, not as yourself

Discourse expects two headers on every API call: Api-Key and Api-Username. The key proves you can call the API, and the username is the account the action is attributed to. Query-string credentials stopped being supported in April 2020 (apart from a few endpoints like RSS feeds), so headers are the only route for new code. The Discourse REST API documentation thread spells this out.

Admin keys are generated at /admin/api/keys. Create a dedicated account first, something like answerloops-bot, and tie the key to that single user. Replies then show up under a name your community recognizes as automated, and a key locked to one user can't be talked into acting as somebody else. Give the account enough trust level to post in the categories you care about, or Discourse will reject its replies.

If you choose a granular key, the scope that lets a bot post replies is topics → write. Discourse has no granular scope for webhooks: only an admin account can manage them, so a bot running as a regular user can't create its own webhook. Add it yourself in the Discourse admin, as described next.

2. Hear about new posts: webhooks beat polling

You can poll the forum on a timer and diff the results, but you're always either late or wasteful, and every poll counts against your rate limit. Discourse can call you instead. In Admin → API → Webhooks, add a webhook, subscribe it to the Topic Event and Post Event groups, set the content type to application/json, and leave TLS verification on.

One catch if your forum and your bot run on the same private network: Discourse refuses a webhook URL that resolves to a private address, such as localhost or a 192.168.x.x host, until you add that host to the allowed internal hosts site setting. A public https:// URL needs no change.

Each delivery is signed. The X-Discourse-Event-Signature header carries sha256= followed by an HMAC-SHA256 of the raw request body, computed with the secret you set on the webhook. Verify it before trusting the payload:

import crypto from 'crypto'

export function verifyDiscourseSignature(
  rawBody: string,
  header: string | null,
  secret: string
): boolean {
  if (!header || !secret) return false
  const expected =
    'sha256=' + crypto.createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex')
  const a = Buffer.from(header)
  const b = Buffer.from(expected)
  return a.length === b.length && crypto.timingSafeEqual(a, b)
}
Enter fullscreen mode Exit fullscreen mode

Two details that bite people. Hash the raw body exactly as it arrived, not a re-serialized copy of the parsed JSON, or the signatures won't match. And compare in constant time, as above, rather than with ===.

Once the signature checks out, you only need one event: post_created. A new topic's first post fires it too, so that single event covers new topics and replies. Answer everything else, including the setup ping, with a 200 and do nothing. A non-2xx tells Discourse the delivery failed, and it will try again.

3. Reply with one call

Posting an answer is a single request: POST /posts.json with the topic and the text.

curl -X POST https://forum.example.com/posts.json \
  -H "Api-Key: <your-api-key>" \
  -H "Api-Username: answerloops-bot" \
  -H "Content-Type: application/json" \
  -d '{"topic_id": 1234, "raw": "Here is what the docs say about that..."}'
Enter fullscreen mode Exit fullscreen mode

raw is Markdown, so links and code blocks work. The response includes the new post's id; store it so you can tell later which posts your bot wrote.

4. Stay under the rate limits

Discourse documents its defaults in a Meta thread on global rate limits:

Limit Default
Admin API keys 60 requests per minute, shared across all admin keys
User API keys 20 requests per minute, 2,880 per day
Per IP address 200 requests per minute, 50 per 10 seconds

The same thread says global limits can't be changed on Discourse's hosted Free, Starter, Pro or Business plans, so design for the defaults if you don't run the server. If you get a 429, Discourse's guidance is to respect it and slow down rather than retry immediately. Webhooks make this mostly a non-issue, since you only call the API when you have something to post. A self-hosted forum can change these numbers.

Mistakes that cost us time

  • The bot answering itself. Your reply fires a post webhook like any other post. Skip any post authored by your bot's username or you'll build a loop. Skip system posts too (a user id of 0 or below) and anything that isn't a regular post, such as whispers and moderator notices.
  • Replying to a one-word bump. A "+1" or "thanks" doesn't need an answer. We ignore posts under ten characters, unless the post is a follow-up in a topic we're already answering. There, a short "that worked, thanks" is part of the conversation.
  • Assuming every endpoint is documented. It isn't, and the Meta REST API thread says so itself. Start from the official API reference, and when something is missing, watch what the Discourse web app calls in your browser's network tab.
  • Confidently wrong answers. The hard part of an answer bot isn't the API, it's knowing when not to answer. We gate every reply on a confidence score and hold low-confidence drafts for a person.

If you'd rather not build this yourself, the Discourse integration in answerLoops does all of the above. The original version of this article, with a little more on how we use it, is on the answerLoops blog.

Top comments (13)

Collapse
 
paullovelace profile image
Paul Lovelace •

The bot-answering-itself loop is the mistake I'd have made first — your own reply firing the post webhook is so obvious in hindsight and so easy to miss while you're wiring it up. The confidence gate is the part I'd actually steal though: knowing when not to answer is the whole job for a support bot. How do you set that threshold in practice — fixed score, or does it move with how busy the human queue is?

Collapse
 
nathan_tarbert profile image
Nathan Tarbert •

Hey Paul, I really appreciate that! I completely agree that knowing when not to answer is just as important as knowing how to answer.

We use a configurable confidence threshold that is set in the platform. A separate read only AI agent evaluates the generated answer against the available knowledge sources, assessing both how well-supported the answer is and whether it fully addresses the question.

The threshold doesn't dynamically adjust based on the human queue. I'd be hesitant to lower the quality bar simply because the support team is busy. That could ultimately create more work and erode community trust.

I'd recommend starting with human approval enabled, reviewing the quality of the answers, and adjusting the threshold as you build trust in the system.

Your point about queue volume is interesting, though. How would you approach that without compromising answer quality?

Collapse
 
jal_c_68347 profile image
Jalissia_C •

Can I control which parts of my Discourse community the bot monitors?

Collapse
 
nathan_tarbert profile image
Nathan Tarbert •

Hi Jalissia, you can choose specific categories or monitor the entire forum. For example, you might want AI-assisted answers in your technical support category while leaving general discussions entirely human-led. Every community operates differently, so having that flexibility is important.

Collapse
 
johnywalker21 profile image
johny walker •

Thanks for this answer. I actually had the same question.

Collapse
 
johnsnow221 profile image
ethan_snow •

Can the bot pull answers from our existing documentation and previous community conversations? Is this specific to Discourse, or does it apply to other communities?

Collapse
 
nathan_tarbert profile image
Nathan Tarbert •

Yes, answerLoops uses your connected knowledge sources and relevant, previously resolved tickets to generate answers.

One of the benefits is that knowledge your team has already shared can continue helping other community members, rather than requiring someone to answer the same question repeatedly.

This process works across the other communities that are supported, such as Discord, Slack, Circle, etc.

Collapse
 
hajusef_908 profile image
Hajeem Usef •

Great article. Our community is hosted in Discourse and this looks like it would be really helpful.

Collapse
 
nathan_tarbert profile image
Nathan Tarbert •

Thanks Hajeem, I'm curious if your community is technical or non-technical.

Do you have frequent questions that keep coming back up?

Collapse
 
danny_9746 profile image
Danny T •

How do you prevent the bot from responding to every message in a discussion?

Collapse
 
nathan_tarbert profile image
Nathan Tarbert •

Hi Danny, once a conversation is being tracked, subsequent replies are added to the existing ticket without automatically generating another AI response. Your team retains the context and can decide when further assistance is needed. Nobody wants a bot interrupting a productive conversation between community members :)

Collapse
 
cameran-755 profile image
Cameran •

What happens if someone asks a follow-up question in the same Discourse thread? Does the bot try to answer again?

Collapse
 
nathan_tarbert profile image
Nathan Tarbert •

Currently, follow-up messages are added to the existing ticket without triggering another automatic AI response. We wanted to avoid a situation where the bot keeps jumping into an ongoing conversation. The team retains the conversation context and can decide how best to respond.