Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bot improvements #23

Merged
merged 3 commits into from
Nov 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
name: Node.js CI

on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master", "dev" ]

Expand Down
65 changes: 65 additions & 0 deletions src/commands/elitedangerous/findLootAnarchyMiningSettlements.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const { ApplicationCommandOptionType, PermissionFlagsBits } = require("discord.js");

const apiGetInaraMiningAnarchyLootSettlements = require('../../utils/apiGetInaraMiningAnarchyLootSettlements');

const cooldowns = new Set();
const COOLDOWN_TIME_MINUTES = 5;
const COOL_DOWN_NAME = 'findLootAnarchyMiningSettlements';

module.exports = {
name: "find-loot-settlements",
description: "Will find systems that have Anarchy Extraction settlements in big numbers near your system.",
isDeleted: false,
options: [
{
name: 'system-name',
description: 'system-name',
type: ApplicationCommandOptionType.String,
required: true,
},
],

permissionsRequired: [PermissionFlagsBits.ViewChannel],

callback: async(discordBot, interaction) => {
try {
if(cooldowns.has(COOL_DOWN_NAME)) {
interaction.reply({
content: `Whoa, This function was recently used, there is a cooldown of (${COOLDOWN_TIME_MINUTES}) minute(s).`,
ephemeral: true
});
return;
}

// have to use deferred reply, because the processing time is long...
await interaction.deferReply();

cooldowns.add(COOL_DOWN_NAME);
setTimeout(() => {
cooldowns.delete(COOL_DOWN_NAME);
}, COOLDOWN_TIME_MINUTES * 60 * 1000);

const systemName = interaction.options.get('system-name').value;

const overview = await apiGetInaraMiningAnarchyLootSettlements(systemName);

const groupedSettlements = overview.filter(x => x.Dist === '0');

let outputMessage = '';
if(groupedSettlements.length) {
outputMessage = `System: ${systemName} Last updated: ${groupedSettlements[0].Updated}\n`;
}

for(const settlement of groupedSettlements) {
outputMessage += `${settlement.Station} (${settlement.StationDistance})\n`;
}

interaction.editReply({
content: '```' + outputMessage + '```',
});

} catch(error) {
discordBot.getLogger().error(`Unhandled exception (find AX Reactivation Missions) while calling API: ${error}\n${error.stack}`);
}
},
};
67 changes: 67 additions & 0 deletions src/commands/elitedangerous/findLootAnarchyMiningSystems.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const { ApplicationCommandOptionType, PermissionFlagsBits } = require("discord.js");

const apiGetInaraMiningAnarchyLootSettlements = require('../../utils/apiGetInaraMiningAnarchyLootSettlements');
const groupAnarchyLootSettlements = require('../../utils/groupAnarchyLootSettlements');
const compareObjectArrayValues = require('../../utils/compareObjectArrayValues');

const TOP_SYSTEMS_DISPLAY_LIMIT = 10;

const cooldowns = new Set();
const COOLDOWN_TIME_MINUTES = 5;
const COOL_DOWN_NAME = 'findLootAnarchyMiningSystems';

module.exports = {
name: "find-loot-systems",
description: "Will find systems that have Anarchy Extraction settlements in big numbers near your system.",
isDeleted: false,
options: [
{
name: 'system-name',
description: 'system-name',
type: ApplicationCommandOptionType.String,
required: true,
},
],

permissionsRequired: [PermissionFlagsBits.ViewChannel],

callback: async(discordBot, interaction) => {
try {
if(cooldowns.has(COOL_DOWN_NAME)) {
interaction.reply({
content: `Whoa, This function was recently used, there is a cooldown of (${COOLDOWN_TIME_MINUTES}) minute(s).`,
ephemeral: true
});
return;
}

// have to use deferred reply, because the processing time is long...
await interaction.deferReply();

cooldowns.add(COOL_DOWN_NAME);
setTimeout(() => {
cooldowns.delete(COOL_DOWN_NAME);
}, COOLDOWN_TIME_MINUTES * 60 * 1000);

const systemName = interaction.options.get('system-name').value;

const overview = await apiGetInaraMiningAnarchyLootSettlements(systemName);

const groupedSystemsByNbSettlements = groupAnarchyLootSettlements(overview);

const sortedSystemsByNbSettlements = groupedSystemsByNbSettlements.sort(compareObjectArrayValues('nbSettlements', 'desc'));

let outputMessage = '';
for(const system of sortedSystemsByNbSettlements.slice([0], [TOP_SYSTEMS_DISPLAY_LIMIT])) {
outputMessage += `${system.system} (${system.nbSettlements}) (${system.lastUpdated})\n`;
}

interaction.editReply({
content: '```' + outputMessage + '```',
});

} catch(error) {
discordBot.getLogger().error(`Unhandled exception (find AX Reactivation Missions) while calling API: ${error}\n${error.stack}`);
}
},
};
45 changes: 45 additions & 0 deletions src/utils/apiGetInaraMiningAnarchyLootSettlements.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const axios = require('axios');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;


module.exports = async(systemName) => {

const URL = `https://inara.cz/elite/nearest-stations/?formbrief=1&ps1=${systemName.replace(/\s+/g, '+')}&pi13=&pi14=1&pi15=3&pi16=60&pi1=0&pi18=0&pi19=5000&pi17=0&ps2=&pi25=0&pi8=&pi9=1&pa2%5B%5D=0&pa2%5B%5D=5&pa2%5B%5D=13&pa2%5B%5D=1&pa2%5B%5D=11&pi26=1&pi3=&pi4=0&pi5=0&pi7=0&pi23=0&pi6=0&pa3%5B%5D=0&ps3=&pi24=0`;

const response = await axios.get(URL);

const dom = new JSDOM(response.data);

return getJSON(dom.window.document.querySelector('table.tablesortercollapsed'));
};


function getJSON(table) {
// thead (Header adjustment so that fields of JSON objects would appear uniformily)
const thead = Array.from(table.tHead.rows[0].children).map((el) =>
el.textContent
.replace("St dist", "StationDistance")
.replace("Star system", "StarSystem"));

let rows = [];

// creating an array of JSON objects based on HTML rows
for(const tRow of table.tBodies[0].rows) {
let row = {};
for(let j = 0; j < thead.length; j++) {
const key = `${thead[j].toString()}`;
row[key] = tRow.cells[j].textContent
.replaceAll("︎︎", "")
.replaceAll("︎", "")
.replaceAll(" Ly︎", "")
.replaceAll("0 Ly", "0")
.replaceAll(" Ly", "");
// TODO: Probably should think of a more elegant way of filtering weird Emojiis and html icons

}
rows.push(row);
}

return rows;
}
25 changes: 25 additions & 0 deletions src/utils/compareObjectArrayValues.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Example of usage of this function : groupedSystemsByNbSettlements.sort(compareObjectArrayValues('nbSettlements', 'desc'));

module.exports = (key, order = 'asc') => {
return function innerSort(a, b) {
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}

const varA = (typeof a[key] === 'string') ?
a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string') ?
b[key].toUpperCase() : b[key];

let comparison = 0;
if(varA > varB) {
comparison = 1;
} else if(varA < varB) {
comparison = -1;
}
return(
(order === 'desc') ? (comparison * -1) : comparison
);
};
};
20 changes: 20 additions & 0 deletions src/utils/groupAnarchyLootSettlements.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module.exports = (miningAnarchyLootSettlements = []) => {

// create categories object to count category items
let groupedAnarchySettlements = {};
let lastUpdatedSettlements = {};
miningAnarchyLootSettlements.forEach((miningAnarchyLootSettlementObject) => {
if(groupedAnarchySettlements.hasOwnProperty(miningAnarchyLootSettlementObject.StarSystem)) {
groupedAnarchySettlements[miningAnarchyLootSettlementObject.StarSystem]++;
} else {
groupedAnarchySettlements[miningAnarchyLootSettlementObject.StarSystem] = 1;
lastUpdatedSettlements[miningAnarchyLootSettlementObject.StarSystem] = miningAnarchyLootSettlementObject.Updated;
}
});

// convert object to array of objects (if this is really needed)
return Object.keys(groupedAnarchySettlements).map((key) => {
return { 'system': key, 'nbSettlements': groupedAnarchySettlements[key], 'lastUpdated': lastUpdatedSettlements[key] }
});

};
Loading