1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { respondToDiscordCommand } from "https://esm.town/v/demo/respondToDiscordCommand";
import { naclValidateRequest } from "https://esm.town/v/demo/naclValidateRequest";
import process from "node:process";
export let discordInteractionHook = async (
req: express.Request,
res: express.Response,
) => {
// https://discord.com/developers/applications/<application_id>/information
const pub = process.env.personalBotPublicKey;
if (!(await naclValidateRequest(req, pub))) {
return res.status(401).end("invalid request signature");
}
// Handle ping request
// https://discord.com/developers/docs/interactions/receiving-and-responding#receiving-an-interaction
if (req.body["type"] == 1) {
res.json({ type: 1 });
return;
}
// Logic
console.log(req.body);
res.json(respondToDiscordCommand(req.body));
};
1
2
3
4
5
6
7
8
9
10
11
12
13
import { Buffer } from "node:buffer";
export let naclValidateRequest = async (req: express.Request, publicKey) => {
const { default: nacl } = await import("npm:tweetnacl@1.0.3");
const signature = req.get("X-Signature-Ed25519");
const timestamp = req.get("X-Signature-Timestamp");
const body = JSON.stringify(req.body); // rawBody is expected to be a string, not raw bytes
const isVerified = nacl.sign.detached.verify(
Buffer.from(timestamp + body),
Buffer.from(signature, "hex"),
Buffer.from(publicKey, "hex"),
);
return isVerified;
};
1
Next