import { verify_discord_signature } from "https://esm.town/v/mattx/verify_discord_signature?v=8";
import { blob } from "https://esm.town/v/std/blob";
let bank = await blob.getJSON("bank");
let bets = await blob.getJSON("bets");
const starting_amount = 5;
if (!bank) {
bank = {};
await blob.setJSON("bank", bank);
}
if (!bets) {
bets = [];
await blob.setJSON("bets", bets);
}
export const handleDiscordInteraction = async (req: Request) => {
if (req.method === "GET") return new Response("GET Method Not Allowed", { status: 405 });
const body = await req.json();
const verified = await verify_discord_signature(
Deno.env.get("discordPublicKey"),
JSON.stringify(body),
req.headers.get("X-Signature-Ed25519"),
req.headers.get("X-Signature-Timestamp"),
);
const userId = await body.member?.user?.id;
if (bank[userId] === undefined) bank[userId] = starting_amount;
if (!verified) {
return new Response("signature invalid", {
status: 401,
statusText: "signature invalid",
});
}
if (body.type === 1)
return Response.json({ type: 1 });
if (body.type === 2) {
const command = body.data?.name;
const options = body.data?.options;
if (command === "balance") {
const amount = bank[userId];
return Response.json({
type: 4,
data: {
content: `You have ${amount} <:jopacoin:954159801049440297>`,
},
});
}
if (command === "tip") {
const recipientId = options[0].value;
const tipAmount = options[1].value;
if (tipAmount <= 0) {
return Response.json({
type: 4,
data: {
content: `You cannot tip less than 0 <:jopacoin:954159801049440297>, <@${userId}>. Nice try though.`,
},
});
}
if (tipAmount > bank[userId]) {
return Response.json({
type: 4,
data: {
content: `You cannot tip more than you have <:jopacoin:954159801049440297>, <@${userId}>. Nice try though.`,
},
});
}
bank[userId] -= tipAmount;
if (bank[recipientId] === undefined) {
bank[recipientId] = starting_amount;
}
bank[recipientId] += tipAmount;
await blob.setJSON("bank", bank);
return Response.json({
type: 4,
data: {
content: `<@${userId}> has tipped <@${recipientId}> ${tipAmount} <:jopacoin:954159801049440297>!`,
},
});
}
if (command === "bet") {
const party2 = options[0].value;
const betAmount = options[1].value;
const description = options[2].value;
if (betAmount <= 0) {
return Response.json({
type: 4,
data: {