import { verify_discord_signature } from "https://esm.town/v/mattx/verify_discord_signature";
import { formatInput } from "https://esm.town/v/rayman/formatInput";
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";
export async function mgsrBotEndpoint(request) {
const signatureTimestamp = request.headers.get("X-Signature-Timestamp");
const signatureEd25519 = request.headers.get("X-Signature-Ed25519");
console.log(signatureTimestamp);
console.log(signatureEd25519);
if (!signatureTimestamp || !signatureEd25519) {
return new Response("Signature headers missing!", { status: 400 });
}
const body = await request.json();
const verified = await verify_discord_signature(
process.env.discord_pubkey,
JSON.stringify(body),
signatureEd25519,
signatureTimestamp,
);
if (!verified) {
return new Response("Signature invalid", { status: 401 });
}
let responseBody;
let status = 200;
switch (body.type) {
case 1:
responseBody = JSON.stringify({ type: 1 });
break;
case 2:
responseBody = await handleApplicationCommands(body);
if (!responseBody) {
status = 400;
responseBody = "bad request";
}
break;
default:
status = 400;
responseBody = "bad request";
break;
}
return new Response(responseBody, {
status: status,
headers: { "Content-Type": "application/json" },
});
}
async function handleApplicationCommands(body) {
let response;
switch (body.data.name) {
case "ping":
response = {
type: 4,
data: {
content: `Hello World! example1 is: ${example1}`,
},
};
break;
case "eval":
const evalResponse = await fetch(
`https://api.val.town/v1/eval/${encodeURIComponent(body.data.options[0].value)}`,
{ headers: { "Content-Type": "application/json" } },
);
const evalText = await evalResponse.text();
response = {
type: 4,
data: {
content: `${JSON.stringify(evalText)}`,
},
};
break;
case "Undo Help":
response = {
type: 4,
data: {
content: "`/undo-record leaderboard:mgsr2 versus:1`",
flags: 64,
},
};
break;
case "Result Formatter":
const messageKey = body.data.target_id;
const content = body.data.resolved.messages[messageKey].content;
const resultString = formatInput(content);
response = {
type: 4,
data: {
content: `/game record leaderboard: mgsr2 result: ${resultString}`,
flags: 64,
},
};
break;