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");
import { createAudioResource, createAudioPlayer, joinVoiceChannel, VoiceConnectionStatus } from '@discordjs/voice';
import { Client, GatewayIntentBits } from 'discord.js';
import googleTTS from 'google-tts-api';
const starting_amount = 5;
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] });
const pendingSimonSays = new Map();
client.on('voiceStateUpdate', async (oldState, newState) => {
const userId = newState.id;
if (pendingSimonSays.has(userId) && newState.channelId) {
const { guildId, channelId, message } = pendingSimonSays.get(userId);
const connection = joinVoiceChannel({
channelId: newState.channelId,
guildId: guildId,
adapterCreator: newState.guild.voiceAdapterCreator,
});
connection.on(VoiceConnectionStatus.Ready, async () => {
const url = googleTTS.getAudioUrl(message, {
lang: 'en',
slow: false,
host: 'https://translate.google.com',
});
const player = createAudioPlayer();
const resource = createAudioResource(url);
player.play(resource);
connection.subscribe(player);
player.on('stateChange', (oldState, newState) => {
if (newState.status === 'idle') {
connection.destroy();
pendingSimonSays.delete(userId);
}
});
});
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
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({