Skip to content

Commit

Permalink
Merge pull request #72 from Jesmaster/71-logging-fixes
Browse files Browse the repository at this point in the history
71 logging fixes
  • Loading branch information
Jesmaster authored Aug 28, 2022
2 parents 0cb1d62 + 2d2229f commit af117ba
Show file tree
Hide file tree
Showing 8 changed files with 637 additions and 572 deletions.
87 changes: 42 additions & 45 deletions commands/bgg-collection.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const {SlashCommandBuilder} = require("@discordjs/builders");
const xml2js = require("xml2js");

module.exports = {
data: new SlashCommandBuilder()
Expand All @@ -16,7 +15,7 @@ module.exports = {
*
* @param {string} cache_type
* @param {string} cache_key
* @return {JSON|boolean}
* @return {Promise<JSON|boolean>}
*/
cacheGet: async function(cache_type, cache_key) {
const
Expand Down Expand Up @@ -60,41 +59,45 @@ module.exports = {
*
* @param {String} username
*
* @throws {string}
* @return {Promise<JSON>}
*/
bggCollection: async function(username) {
const
cache_type = 'bgg_collection',
cache = await this.cacheGet(cache_type, username),
fetch = require('node-fetch'),
axios = require('axios').default,
xml2js = require('xml2js'),
parser = new xml2js.Parser();

if(cache !== false) {
return Promise.resolve(cache);
return cache;
}

return fetch('https://boardgamegeek.com/xmlapi2/collection?username='+username).then(async response => {
//First time collection requests return 202 where it builds results and you try again later.
if(response.status === 202) {
throw 'Building results';
}
else {
const content = await response.text();
const result = await parser.parseStringPromise(content);
this.cacheSet(cache_type, username, result);
const response = await axios('https://boardgamegeek.com/xmlapi2/collection?username='+username);

return result;
}
}
);
//First time collection requests return 202 where it builds results and you try again later.
if(response.status === 202) {
return 'Building results';
}
else {
const { data } = response;
const result = await parser.parseStringPromise(data);
await this.cacheSet(cache_type, username, result);

return result;
}
},
/**
* Create Discord Embed from BGG collection
* @return {module:"discord.js".MessageEmbed}
*
* @param {Object} results
* @param {string} username
* @param {User} user
* @return {import("discord.js").EmbedBuilder}
*/
collectionToEmbed: function(result, username, user) {
const Discord = require('discord.js');
const { EmbedBuilder, User } = require('discord.js');

let collection_url = `https://boardgamegeek.com/collection/user/${username}`;
let
Expand Down Expand Up @@ -123,7 +126,7 @@ module.exports = {
}
});

return new Discord.MessageEmbed()
return new EmbedBuilder()
.setColor('#3f3a60')
.setTitle(username + '\'s collection')
.setURL(collection_url)
Expand Down Expand Up @@ -159,44 +162,38 @@ module.exports = {
},
/**
* Send collection embed to channel
*
* @param {Object} result
* @param {import("discord.js").Interaction} interaction
* @param {string} username
*/
collectionPrintEmbed: function(result, interaction, username) {
const { user } = interaction.member;
if(typeof result === 'object' && result.items['$'].totalitems > 0) {
interaction.reply({ embeds: [this.collectionToEmbed(result, username, user)] });
interaction.editReply({ embeds: [this.collectionToEmbed(result, username, interaction.member.user)] });
}
else {
interaction.reply(`No results found for "${username}".`);
interaction.editReply(`No results found for "${username}".`);
}
},
/**
* Execute Discord Command
* @param {import("discord.js").Interaction} interaction
* @return {Promise<void>}
*/
execute: async function (interaction) {
const current = this;
await interaction.deferReply();
const username = interaction.options.getString('username');

let result = await this.bggCollection(username);
if (result === 'Building results') {
console.log(`Building collection results for ${username}`);

//Wait 2 seconds and then attempt call again.
await new Promise((resolve) => setTimeout(resolve, 2000));
result = await this.bggCollection(username);
}

current.bggCollection(username)
.then(result => {
console.log(`Collection results found for ${username}`);
current.collectionPrintEmbed(result, interaction, username)
})
.catch(async function(err) {
if(err === 'Building results') {
console.log(`Building collection results for ${username}`);

//Wait 2 seconds and then attempt call again. If it's still not ready
await new Promise((resolve) => setTimeout(resolve, 2000));
current.bggCollection(username)
.then(result => {
console.log(`Collection results found for ${username}`);
current.collectionPrintEmbed(result, interaction, username)
});
}
else {
throw err;
}
});
console.log(`Collection results found for ${username}`);
this.collectionPrintEmbed(result, interaction, username);
},
}
7 changes: 3 additions & 4 deletions commands/bgg-help.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ module.exports = {
/**
* Create Discord Embed for help
*
* @return {module:"discord.js".MessageEmbed}
* @return {module:"discord.js".EmbedBuilder}
*/
helpEmbed: (client) => {
const Discord = require('discord.js');
const { EmbedBuilder } = require('discord.js');

return new Discord.MessageEmbed()
return new EmbedBuilder()
.setColor('#3f3a60')
.setTitle('BGG Bot Commands')
.addFields(
Expand Down Expand Up @@ -40,7 +40,6 @@ module.exports = {
* @return {Promise<void>}
*/
execute: async function(interaction) {
console.log(interaction.message);
const { client } = interaction;

await interaction.reply({ embeds: [this.helpEmbed(client)] });
Expand Down
98 changes: 53 additions & 45 deletions commands/bgg-search.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const {SlashCommandBuilder} = require("@discordjs/builders");
const he = require("he");

module.exports = {
data: new SlashCommandBuilder()
Expand Down Expand Up @@ -29,27 +28,27 @@ module.exports = {
query = searchParams.toString(),
cache_type = 'bgg_search',
cache = await this.cacheGet(cache_type, query),
fetch = require('node-fetch');
axios = require('axios').default;

console.log(`Looking up search: ${name}...`);

if(cache !== false) {
return Promise.resolve(cache);
console.log(`Found cached entry for ${name}`);
return cache;
}

return fetch('https://boardgamegeek.com/search/boardgame?q='+name, {
const response = await axios('https://boardgamegeek.com/search/boardgame?q='+name, {
headers: {
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.9'
}
}).then(
response => {
return response.json().then (
json => {
this.cacheSet(cache_type, query, json);
return json;
}
);
}
)
});

const { data } = response;
console.log(`Found result for ${name}`);
await this.cacheSet(cache_type, query, data);

return data;
},
/**
* Preforms BGG API thing call.
Expand All @@ -62,27 +61,32 @@ module.exports = {
const
cache_type = 'bgg_thing',
cache = await this.cacheGet(cache_type, thing_id),
fetch = require('node-fetch'),
axios = require('axios').default,
xml2js = require('xml2js'),
parser = new xml2js.Parser();

console.log(`Looking up ${thing_id}...`);

if(cache !== false) {
return Promise.resolve(cache);
console.log(`Found cached entry for ${thing_id}`);
return cache;
}

return fetch('https://boardgamegeek.com/xmlapi2/thing?id='+thing_id).then(async response => {
const content = await response.text();
const result = await parser.parseStringPromise(content);
this.cacheSet(cache_type, thing_id, result);
return result;
});
const response = await axios('https://boardgamegeek.com/xmlapi2/thing?id='+thing_id);

const { data } = response;
console.log(`Looked up data for ${thing_id}`);
const result = await parser.parseStringPromise(data);
await this.cacheSet(cache_type, thing_id, result);

return result;
},
/**
* Pull from BGG Bot Cache
*
* @param {string} cache_type
* @param {string} cache_key
* @return {JSON|boolean}
* @return {Promise<JSON|boolean>}
*/
cacheGet: async function(cache_type, cache_key) {
const
Expand Down Expand Up @@ -147,19 +151,20 @@ module.exports = {
* Create Discord Embed from BGG thing
*
* @param {Object} item
* @return {module:"discord.js".MessageEmbed}
* @param {User} user
* @return {import("discord.js").EmbedBuilder}
*/
itemToSearchEmbed: function(item, user) {
const
Discord = require('discord.js'),
{ EmbedBuilder, User } = require('discord.js'),
he = require('he');

return new Discord.MessageEmbed()
return new EmbedBuilder()
.setColor('#3f3a60')
.setTitle(item.name instanceof Array ? item.name[0]['$'].value : item.name['$'].value)
.setURL(`https://boardgamegeek.com/${item['$'].type}/${item['$'].id}`)
.setThumbnail(item.thumbnail[0])
.setDescription(he.decode(item.description[0]).substr(0, 200)+'...')
.setDescription(he.decode(item.description[0]).substring(0, 200)+'...')
.setAuthor({ name: user.username, url: user.avatarURL(), iconURL: user.displayAvatarURL() })
.addFields(
{
Expand All @@ -176,6 +181,9 @@ module.exports = {
},
/**
* Send game embed to channel given thing_id
*
* @param {Object} bggSearchResult
* @param {import("discord.js").Interaction} interaction
*/
thingIdToSearchEmbed: async function(bggSearchResult, interaction) {
if(bggSearchResult.found) {
Expand All @@ -192,19 +200,19 @@ module.exports = {
* Create Discord Embed from BGG thing
*
* @param {Object} item
* @return {module:"discord.js".MessageEmbed}
* @return {module:"discord.js".EmbedBuilder}
*/
itemToSuggestEmbed: function(item, user) {
const
Discord = require('discord.js'),
{ EmbedBuilder } = require('discord.js'),
he = require('he');

return new Discord.MessageEmbed()
return new EmbedBuilder()
.setColor('#3f3a60')
.setTitle(item.name instanceof Array ? item.name[0]['$'].value : item.name['$'].value)
.setURL(`https://boardgamegeek.com/${item['$'].type}/${item['$'].id}`)
.setThumbnail(item.thumbnail[0])
.setDescription(he.decode(item.description[0]).substr(0, 200)+'...')
.setDescription(he.decode(item.description[0]).substring(0, 200)+'...')
.setFooter({ text: '( 👍 Interested | 📖 Can Teach | ❌ End Suggestion )'})
.setAuthor({ name: user.username, url: user.avatarURL(), iconURL: user.displayAvatarURL() })
.addFields(
Expand Down Expand Up @@ -239,7 +247,7 @@ module.exports = {
* Send game embed to channel given thing_id
*/
thingIdToSuggestEmbed: async function(bggSearchResult, interaction) {
const Discord = require('discord.js');
const { EmbedBuilder } = require('discord.js');

if(bggSearchResult.found) {
this.bggThing(bggSearchResult.thing_id)
Expand All @@ -259,47 +267,47 @@ module.exports = {

collector
.on('collect', (reaction, user) => {
let changedEmbed = new Discord.MessageEmbed(embed);
let { fields } = embed.toJSON();
let username = `<@${user.id}>\n${blank_char}`;
let field_delta = 3;

if (reaction.emoji.name === "📖") {
field_delta = 4;
}

if (changedEmbed.fields[field_delta].value === blank_char) {
changedEmbed.fields[field_delta].value = username;
if (fields[field_delta].value === blank_char) {
fields[field_delta].value = username;
}
else {
changedEmbed.fields[field_delta].value += username;
fields[field_delta].value += username;
}
embedMessage.edit({ embeds: [changedEmbed] });

embed = changedEmbed;
embed.setFields(fields);

embedMessage.edit({ embeds: [embed] });
})
.on('remove', (reaction, user) => {
let changedEmbed = new Discord.MessageEmbed(embed);
let { fields } = embed.toJSON();
let username = `<@${user.id}>\n${blank_char}`;
let field_delta = 3;

if (reaction.emoji.name === "📖") {
field_delta = 4;
}

changedEmbed.fields[field_delta].value = changedEmbed.fields[field_delta].value.replace(username, '');
fields[field_delta].value = fields[field_delta].value.replace(username, '');

if (changedEmbed.fields[field_delta].value === '') {
changedEmbed.fields[field_delta].value = blank_char;
if (fields[field_delta].value === '') {
fields[field_delta].value = blank_char;
}

embedMessage.edit({ embeds: [changedEmbed] });
embed.setFields(fields);

embed = changedEmbed;
embedMessage.edit({ embeds: [embed] });
})
.on('end', collected => {
deleteCollector.stop();
embedMessage.reactions.removeAll();
let changedEmbed = new Discord.MessageEmbed(embed);
embed.setFooter({ text: 'Reactions have been closed off for this suggestion.' });
embedMessage.edit({ embeds: [embed] });
});
Expand Down
Loading

0 comments on commit af117ba

Please sign in to comment.