45 lines
1.3 KiB
JavaScript
45 lines
1.3 KiB
JavaScript
import 'dotenv/config';
|
|
import fetch from 'node-fetch';
|
|
import { verifyKey } from 'discord-interactions';
|
|
|
|
const baseURL = 'https://discord.com/api/v10/';
|
|
|
|
export function verifyDiscordRequest(clientKey) {
|
|
return function (req, res, buf, encoding) {
|
|
const signature = req.get('X-Signature-Ed25519');
|
|
const timestamp = req.get('X-Signature-Timestamp');
|
|
|
|
const isValidRequest = verifyKey(buf, signature, timestamp, clientKey);
|
|
if (!isValidRequest) {
|
|
res.status(401).send('Bad request signature');
|
|
throw new Error('Bad request signature');
|
|
}
|
|
};
|
|
}
|
|
|
|
export async function discordRequest(endpoint, options) {
|
|
const url = baseURL + endpoint;
|
|
|
|
if (options.body) {
|
|
options.body = JSON.stringify(options.body);
|
|
}
|
|
|
|
// Use node-fetch to make requests
|
|
const res = await fetch(url, {
|
|
headers: {
|
|
'Authorization': `Bot ${process.env.DISCORD_TOKEN}`,
|
|
'Content-Type': 'application/json; charset=UTF-8',
|
|
'User-Agent': 'DiscordBot (https://github.com/erynofwales/thirteenth-friend, 1.0.0)',
|
|
},
|
|
...options
|
|
});
|
|
|
|
if (!res.ok) {
|
|
const data = await res.json();
|
|
console.error('Request failed with status:', res.status);
|
|
throw new Error(JSON.stringify(data));
|
|
}
|
|
|
|
return res;
|
|
}
|
|
|