mattx-examplebotendpoint.express.val.run
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { fetch } from "https://esm.town/v/std/fetch";
import { example1 } from "https://esm.town/v/stevekrouse/example1?v=3";
import process from "node:process";
import { verify_discord_signature } from "https://esm.town/v/mattx/verify_discord_signature";
export let examplebotendpoint = async (req: Request) => {
const headers = { "Content-type": "application/json" };
const text = await req.text();
const body = JSON.parse(text);
if (
!req.headers.get("X-Signature-Timestamp") ||
!req.headers.get("X-Signature-Ed25519")
) {
return Response.json({ error: "bad request" }, { status: 400 });
}
const verified = await verify_discord_signature(
process.env.discord_pubkey,
text,
req.headers.get("X-Signature-Ed25519"),
req.headers.get("X-Signature-Timestamp"),
);
if (!verified) {
return Response.json({ error: "signature invalid" }, { status: 401 });
}
switch (body.type) {
case 1: // PING
return Response.json({ type: 1 }, { headers }); // PONG
case 2: // APPLICATION_COMMAND
// TODO: Probably don't use a nested switch here
switch (body.data.name) {
case "ping":
return Response.json({
type: 4,
data: {
content:
`Hello World! example1 is: ${example1}`,
},
}, { headers });
case "eval":
return Response.json({
type: 4,
data: {
content: `${await (await fetch(
"https://api.val.town/v1/eval/" +
encodeURIComponent(body.data.options[0].value),
{
"headers": { "Content-Type": "application/json" },
},
)).text()}`,
},
}, { headers });
default:
return Response.json({
type: 4,
data: {
content: "Unknown command.",
flags: (1 << 6), // EPHEMERAL
},
}, { headers });
}
default:
return Response.json({ error: "bad request" }, { status: 400 });
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023