update to async

This commit is contained in:
Shay
2022-04-06 17:45:50 -07:00
parent a641c5031b
commit e3ea5532ea
3 changed files with 57 additions and 41 deletions

83
app.js
View File

@@ -22,7 +22,7 @@ const activeGames = {};
/**
* Interactions endpoint URL where Discord will send HTTP requests
*/
app.post('/interactions', function (req, res) {
app.post('/interactions', async function (req, res) {
// Interaction type and data
const { type, id, data } = req.body;
@@ -89,58 +89,69 @@ app.post('/interactions', function (req, res) {
*/
if (type === InteractionType.MESSAGE_COMPONENT){
// custom_id set in payload when sending message component
let componentId = data.custom_id;
const componentId = data.custom_id;
if (componentId.startsWith('accept_button_')) {
// get the associated game ID
let gameId = componentId.replace('accept_button_', '');
const gameId = componentId.replace('accept_button_', '');
// Delete message with token in request body
let url = DiscordAPI(`/webhooks/${process.env.APP_ID}/${req.body.token}/messages/${req.body.message.id}`);
client({ url, method: 'delete' }).catch(e => console.error(`Error deleting message: ${e}`));
return res.send({
"type": InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
"data": {
// Fetches a random emoji to send from a helper function
"content": "What's your object of choice?",
// Indicates it'll be an ephemeral message
"flags": 64,
"components": [{
"type": ComponentType.ACTION,
const url = DiscordAPI(`webhooks/${process.env.APP_ID}/${req.body.token}/messages/${req.body.message.id}`);
try {
await res.send({
"type": InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
"data": {
// Fetches a random emoji to send from a helper function
"content": "What's your object of choice?",
// Indicates it'll be an ephemeral message
"flags": 64,
"components": [{
"type": ComponentType.SELECT,
// Append game ID
"custom_id": `select_choice_${gameId}`,
"options": getShuffledOptions()
"type": ComponentType.ACTION,
"components": [{
"type": ComponentType.SELECT,
// Append game ID
"custom_id": `select_choice_${gameId}`,
"options": getShuffledOptions()
}]
}]
}]
}
});
}
});
await client({ url, method: 'delete' });
return;
} catch (err) {
console.error(`Error sending message: ${err}`);
}
} else if (componentId.startsWith('select_choice_')) {
// get the associated game ID
let gameId = componentId.replace('select_choice_', '');
const gameId = componentId.replace('select_choice_', '');
if (activeGames[gameId]) {
// Get user ID and object choice for responding user
let userId = req.body.member.user.id;
let objectName = data.values[0];
const userId = req.body.member.user.id;
const objectName = data.values[0];
// Calculate result from helper function
let resultStr = getResult(activeGames[gameId], {id: userId, objectName});
const resultStr = getResult(activeGames[gameId], {id: userId, objectName});
// Remove game from storage
delete activeGames[gameId];
// Update message with token in request body
let url = DiscordAPI(`/webhooks/${process.env.APP_ID}/${req.body.token}/messages/${req.body.message.id}`);
client({ url, method: 'patch', data: {
"content": `Nice choice ${getRandomEmoji()}`,
"components": []
}}).catch(e => console.error(`Error deleting message: ${e}`));
const url = DiscordAPI(`webhooks/${process.env.APP_ID}/${req.body.token}/messages/${req.body.message.id}`);
// Send results
return res.send({
"type": InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
"data": { "content": resultStr }
});
try {
// Send results
await res.send({
"type": InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
"data": { "content": resultStr }
});
await client({ url, method: 'patch', data: {
"content": `Nice choice ${getRandomEmoji()}`,
"components": []
}});
return;
} catch (err) {
console.error(`Error sending message: ${err}`);
}
}
}
}

View File

@@ -1,10 +1,10 @@
import { getRPSChoices } from "./game.js";
import { capitalize, DiscordAPI } from "./utils.js";
export function HasGuildCommands(client, appId, guildId, commands) {
export async function HasGuildCommands(client, appId, guildId, commands) {
if (guildId === '' || appId === '') return;
commands.forEach((c) => HasGuildCommand(client, appId, guildId, c));
commands.forEach(c => HasGuildCommand(client, appId, guildId, c));
}
// Checks for a command
@@ -18,7 +18,7 @@ async function HasGuildCommand(client, appId, guildId, command) {
const installedNames = data.map((c) => c["name"]);
// This is just matching on the name, so it's not good for updates
if (!installedNames.includes(command["name"])) {
await InstallGuildCommand(client, appId, guildId, command);
InstallGuildCommand(client, appId, guildId, command);
} else {
console.log(`"${command["name"]}" command already installed`)
}
@@ -33,7 +33,11 @@ export async function InstallGuildCommand(client, appId, guildId, command) {
// API URL to get and post guild commands
const url = DiscordAPI(`applications/${appId}/guilds/${guildId}/commands`);
// install command
return client({ url, method: 'post', data: command});
try {
await client({ url, method: 'post', data: command});
} catch (e) {
console.error(`Error installing guild command: ${e}`);
}
}
// Get the game choices from game.js

View File

@@ -7,7 +7,8 @@ export function VerifyDiscordRequest(clientKey) {
const isValidRequest = verifyKey(buf, signature, timestamp, clientKey);
if (!isValidRequest) {
return res.status(401).end('Bad request signature');
res.status(401).send('Bad request signature');
throw new Error('Bad request signature');
}
}
}