roles-bot/packages/bot/src/index.ts

68 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-04-05 14:44:17 +02:00
import "./commands/setup";
2023-04-06 21:32:43 +02:00
import {
APIApplicationCommandInteraction,
APIMessageComponentInteraction,
APIPingInteraction,
InteractionResponseType,
InteractionType,
} from "discord-api-types/v10";
import { COMMANDS, COMPONENTS } from "./registers";
import { verify } from "./utils/verify";
import respond from "./utils/respond";
2023-04-07 21:51:25 +02:00
import { CommandContext } from "./structs/contexts/CommandContext";
import { ComponentContext } from "./structs/contexts/ComponentContext";
2023-04-05 14:44:17 +02:00
console.log(COMMANDS);
2023-04-03 16:33:23 +02:00
export default {
2023-04-07 21:51:25 +02:00
fetch: async (request: Request, env: Env) => {
2023-04-06 21:32:43 +02:00
if (
!request.headers.get("X-Signature-Ed25519") ||
!request.headers.get("X-Signature-Timestamp")
)
return Response.redirect("https://xhyrom.dev");
2023-04-07 21:51:25 +02:00
if (!(await verify(request, env)))
2023-04-06 21:32:43 +02:00
return new Response("Invalid request signature", { status: 401 });
const interaction = (await request.json()) as
| APIPingInteraction
| APIApplicationCommandInteraction
| APIMessageComponentInteraction;
if (interaction.type === InteractionType.Ping)
return respond({
type: InteractionResponseType.Pong,
});
if (interaction.type === InteractionType.ApplicationCommand) {
const command = COMMANDS.find(
(cmd) => cmd.name === interaction.data.name,
);
if (!command) return new Response("Unknown command", { status: 404 });
2023-04-07 21:51:25 +02:00
try {
return respond({
type: InteractionResponseType.DeferredChannelMessageWithSource,
});
} finally {
command.run(new CommandContext(interaction, env));
}
2023-04-06 21:32:43 +02:00
}
const component = COMPONENTS.find(
(cmp) => cmp.id === interaction.data.custom_id,
);
if (!component) return new Response("Unknown component", { status: 404 });
2023-04-07 21:51:25 +02:00
try {
return respond({
type: InteractionResponseType.DeferredChannelMessageWithSource,
});
} finally {
component.run(new ComponentContext(interaction, env));
}
2023-04-03 16:33:23 +02:00
},
};