Learning objectives
After reading this article you will be able to:
- Understand how Discord delivers interactions over the Gateway and to an Interactions Endpoint URL
- Build an HTTP endpoint that verifies the Ed25519 signature and answers the PING
- Pick the right path for the kind of bot you have
Every Discord slash command, button, select menu or modal becomes an interaction, and Discord has to deliver it to your app somehow. There are two ways: over the Gateway WebSocket connection, which is the default and what discord.js and discord.py use, or as an HTTP request to a URL you own, the Interactions Endpoint URL.
For interactions, the two paths are mutually exclusive, and the choice changes where the bot runs, what it can listen to and how you protect the front door. If you're still building the commands, start with how to create slash commands.
What is each path?#
The Gateway is a persistent WebSocket connection your process opens to Discord to receive real-time events. Interactions arrive as the INTERACTION_CREATE event, alongside everything the bot's intents allow: messages, members, reactions, voice. The reply still goes out over HTTP: the bot calls the interaction's callback endpoint.
HTTP interactions work the other way around, like a webhook. You enter a public HTTPS URL in the Interactions Endpoint URL field under General Information in the Developer Portal, and Discord sends a POST to it for every interaction. Your server replies in the HTTP response body itself, with status 200 and the response object, or with a bodiless 202 and a separate callback.
The same response rules apply to both: 3 seconds for the initial response and a 15-minute lifetime for the interaction token. REST API calls with the bot token (creating a channel, assigning a role) also work in both.
How do they compare side by side?#
| Gateway | HTTP (Interactions Endpoint URL) | |
|---|---|---|
| Connection | A WebSocket the bot opens and keeps | One POST from Discord per interaction |
| What it receives | Interactions plus the events of its intents | Interactions only: commands, buttons, menus, modals, autocomplete |
| Public URL | Not needed | Required, over HTTPS |
| Inbound security | Bot token on the connection | Verify the Ed25519 signature of every request |
| Online status | Yes, while the session is open | Shows as offline |
| Intents and sharding | Required (sharding from 2,500 servers) | Don't apply to interactions |
| How to reply | POST to the interaction callback |
In the HTTP response body |
| Where it fits | An always-on process | A web server or a function that handles requests |
| Tooling | discord.js, discord.py, JDA and the like | A web framework and signature verification, or hikari's RESTBot |
The sharding row matters most for large bots. Each Gateway connection serves up to 2,500 servers, and beyond that Discord requires splitting the bot into shards, as explained in what is Discord sharding. An HTTP endpoint receives interactions from every server at the same URL, so scaling becomes an ordinary web server problem.
What does only the Gateway deliver?#
Anything that isn't an interaction arrives only over the Gateway. That includes:
- Messages.
MESSAGE_CREATE, edits and deletes come from theGUILD_MESSAGESintent, and their text requires the privileged Message Content intent. Prefix bots (!command), moderation filters and per-message XP depend on it, as shown in Discord privileged intents errors. - Members and presence. Members joining and leaving (privileged
GUILD_MEMBERSintent) and each person's status and activity (GUILD_PRESENCES, also privileged). - Voice. Joining a voice channel starts with a voice state update sent over the Gateway. Without the connection there is no music bot, not even with an audio server like Lavalink.
- The rest of the server. Reactions, threads, roles, channels and scheduled events.
- The green dot. The bot's online status exists while its Gateway session is open.
Discord also has webhook events, a separate URL on the Developer Portal's Webhooks page that receives a small set of events: app authorized or deauthorized, purchases (entitlements), and Social SDK lobby and DM messages. The documentation itself warns that they are not real-time or guaranteed to arrive in order. They don't replace the Gateway for server messages.
How do you build an HTTP interactions endpoint?#
There are four steps:
- Copy the Public Key from General Information in the Developer Portal. It isn't the bot token and isn't secret, but it is what verifies requests.
- Verify every request: the
X-Signature-Ed25519header is an Ed25519 signature over theX-Signature-Timestampvalue concatenated with the raw body. An invalid signature gets a401. - Answer the
PING(type: 1) with{"type": 1}. That is what Discord sends when you save the URL. - Paste the URL (for example,
https://your-domain/interactions) and save.
Discord also runs routine checks that deliberately send invalid signatures. If your endpoint accepts one, the URL is removed and you get a warning by email and system DM.
In Node.js, Discord's official discord-interactions package handles steps 2 and 3 (npm install express discord-interactions, with "type": "module" in package.json):
import express from "express";
import {
InteractionResponseFlags,
InteractionResponseType,
InteractionType,
verifyKeyMiddleware,
} from "discord-interactions";
const app = express();
// No express.json() on this route: the signature is computed over the raw body.
// The middleware returns 401 on invalid signatures and PONG to the PING.
app.post("/interactions", verifyKeyMiddleware(process.env.DISCORD_PUBLIC_KEY), (req, res) => {
const interaction = req.body;
if (interaction.type !== InteractionType.APPLICATION_COMMAND) return res.sendStatus(400);
if (interaction.data.name === "ping") {
return res.send({
type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
data: { content: "Pong!" },
});
}
if (interaction.data.name === "report") {
// 1) acknowledge in under 3 s: the user sees "thinking..."
res.send({
type: InteractionResponseType.DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,
data: { flags: InteractionResponseFlags.EPHEMERAL },
});
// 2) finish the work and edit the original response (the token lasts 15 minutes)
const url = `https://discord.com/api/v10/webhooks/${interaction.application_id}/${interaction.token}/messages/@original`;
buildReport()
.then((content) =>
fetch(url, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
}),
)
.catch((err) => console.error("failed to edit the response", err));
return;
}
return res.sendStatus(400);
});
async function buildReport() {
await new Promise((r) => setTimeout(r, 5000)); // slow work: database, API, image
return "Report ready.";
}
app.listen(Number(process.env.PORT) || 3000, "0.0.0.0");In Python, verification uses PyNaCl, as in Discord's documentation example (pip install flask pynacl):
import os
from flask import Flask, abort, jsonify, request
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
app = Flask(__name__)
verify_key = VerifyKey(bytes.fromhex(os.environ["DISCORD_PUBLIC_KEY"]))
@app.post("/interactions")
def interactions():
signature = request.headers.get("X-Signature-Ed25519", "")
timestamp = request.headers.get("X-Signature-Timestamp", "")
body = request.get_data(as_text=True) # raw body, before parsing JSON
try:
verify_key.verify(f"{timestamp}{body}".encode(), bytes.fromhex(signature))
except (BadSignatureError, ValueError):
abort(401, "invalid request signature")
interaction = request.get_json()
if interaction["type"] == 1: # PING
return jsonify({"type": 1}) # PONG
if interaction["type"] == 2 and interaction["data"]["name"] == "ping":
return jsonify({"type": 4, "data": {"content": "Pong!"}})
abort(400)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 3000)))In production, run Flask behind a WSGI server such as gunicorn. Command registration doesn't change: it's the same PUT to the API a Gateway bot uses.
How does the 3-second deadline change on each path?#
The rule is the same; the shape changes. Over the Gateway, the bot calls deferReply() (discord.js) or defer() (discord.py) and edits later. Over HTTP, the defer is the type 5 response itself (DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE), and the edit is a PATCH to /webhooks/{application_id}/{token}/messages/@original, as in the example above. These endpoints use the interaction token, not the bot's, and aren't bound to the application's global rate limit.
The catch with HTTP is what happens after the response. Some function platforms freeze or stop execution as soon as the response is sent, so the work after the defer never finishes. Others take time to cold start, and that time comes out of the 3 seconds. If your host behaves this way, check whether it allows background work. The broader comparison is in serverless vs containers.
When should you choose each one?#
| Scenario | Recommended path |
|---|---|
| Music bot or anything that joins voice channels | Gateway |
| Moderation, XP, welcome messages or prefix commands | Gateway |
| Only slash commands, buttons and modals, and you already run a web API | HTTP |
| Bot in many servers that only answers commands | HTTP, with no sharding for interactions |
| You need events and want interactions in a separate web service | Gateway for events and HTTP for interactions |
| First bot, still learning | Gateway with discord.js or discord.py |
There is no universal winner. The Gateway puts everything in one process and has more examples and libraries, at the cost of a connection that must stay up, reconnect on its own and, as the bot grows, be split into shards. HTTP drops the persistent connection and the intents, at the cost of a public URL, signature verification on every request, a bot with no online status and no events beyond interactions.
When in doubt, start with the Gateway: most tutorials use it, and switching later only means moving the interaction handler to an HTTP route. If your bot is in Python, hikari supports both modes, as covered in which Python library to use.
How to do this on Square Cloud#
Both paths run on Square Cloud, as different kinds of application. A Gateway-only bot is a background application: it receives no inbound traffic and needs no subdomain, and it uses at least 256 MB from the plan's RAM pool. The platform supports discord.js, discord.py or any Gateway library, with an average latency of about 30 ms to the Discord Gateway.
An interactions endpoint is a web application. It gets a *.squareweb.app subdomain with HTTPS on every plan, which can be your Interactions Endpoint URL (for example, https://your-bot.squareweb.app/interactions). Listen on 0.0.0.0 on the port in the PORT variable, as in the examples above, and keep DISCORD_PUBLIC_KEY in the application's environment variables. Each web application uses at least 512 MB.
Containers are always on, with no cold start or sleeping when idle, so the process is already up when the interaction arrives. Hobby costs R$12.49 per month with 1 GB of RAM. See Discord bot hosting.
Bot hosting
Keep your bot online 24/7 with automatic restarts
FAQs
Can I receive interactions over the Gateway and HTTP at the same time?
No. Discord's documentation says the two paths are mutually exclusive for interactions. With an Interactions Endpoint URL set, they arrive over HTTP, but the app can still open a Gateway connection to receive other events.
Does an HTTP-only bot show as online?
No. Online status comes from the Gateway session: Discord's documentation says that when the session is closed, the bot appears offline. An app that only receives interactions over HTTP never opens that session, so it shows as offline in the member list, but it answers commands normally.
Why won't Discord accept my Interactions Endpoint URL?
When you save it, Discord sends a PING and expects status 200 with a PONG (type 1). If the endpoint doesn't answer the PING or doesn't verify signatures, returning 401 for invalid ones, the URL isn't validated. It also has to be publicly reachable over HTTPS.
Does an HTTP bot need intents or sharding?
Not to receive interactions. Intents and sharding are rules of the Gateway connection, and sharding becomes mandatory at 2,500 servers. An HTTP endpoint receives interactions from every server at the same URL.
More in Bots
See all 39 articles- How much does it cost to host a Discord bot?The cost of hosting a Discord bot depends on RAM, uptime, database and outside services. Learn how to estimate your own bill and where the money goes.
- Running a bot on your phone or PC vs hosting itA bot on your PC or phone (Termux) goes offline when the device shuts down, sleeps or loses its network. Compare the three options and when each one fits.
- How to host a Discord bot 24/7To keep a Discord bot online 24/7, run its process on an always-on machine with automatic restarts. Compare your PC, a VPS with pm2 or systemd, and bot hosting.
- Why your Discord bot keeps going offline (and how to fix it)A Discord bot goes offline when the process dies, the token is invalid, an intent is disabled or memory runs out. Learn to diagnose each cause and fix it.