feat(*): Add urban dictionary command

This commit is contained in:
Olly Nicholass
2021-01-15 11:42:02 +00:00
parent 245903b620
commit 2e70031183
+60 -2
View File
@@ -1,4 +1,5 @@
const { sendEmbedMessage } = require('./helpers.js');
const { sendEmbedMessage, trim } = require('./helpers.js');
const axios = require('axios');
module.exports = {
matchCommand: function (Discord, config, logger, message, command, args) {
@@ -6,6 +7,9 @@ module.exports = {
case 'help':
commandHelp(Discord, config, logger, message, command, args);
break;
case 'ud':
commandUrbanDictionary(Discord, config, logger, message, command, args);
break;
default:
message.channel.send(`That command is not one I know yet - but you could add it! To find out more visit ${config.github_url}`);
}
@@ -15,8 +19,62 @@ module.exports = {
function commandHelp (Discord, config, logger, message, command, args) {
const msg = `
The commands available to you are:
- ${config.prefix}commandgoeshere - Do something
- \`${config.prefix}ud <query>\` - Search Urban Dictionary
`;
message.channel.send(msg);
}
function commandUrbanDictionary(Discord, config, logger, message, command, args) {
if (!args.length) {
//If the command is used incorrectly without arguments
return message.channel.send(`You didn't provide any arguments, ${message.author}!`);
}
else if (args[0] != "") {
var searchQuery = args[0];
// Send a POST request to urban dictionary including the search query
axios({
method: 'get',
url: 'http://api.urbandictionary.com/v0/define',
headers: {"Content-Type": "application/json"},
params: {"term": searchQuery}
})
.then(function(response) {
const answers = response.data.list;
if (answers.length > 0) {
try {
// Set up rich embed for the command to return the API response, add the first responses URL with an example of the usage and rating
const embed = sendEmbedMessage(Discord, logger, message, answers[0].word, trim(Discord, logger, answers[0].definition, 1024));
embed.setURL(answers[0].permalink)
.addFields(
{ name: 'Example', value: trim(Discord, logger, answers[0].example, 1024) },
{ name: 'Rating', value: `:thumbsup: ${answers[0].thumbs_up} :thumbsdown: ${answers[0].thumbs_down}` }
);
if (answers.length > 1) {
// If more than 1 definition is found, add additional fields to show the definitions of up to another 3 results
embed.addField('Other Definitions', 'Below are some that didn\t quite cut the mustard.')
for (let i = 1; i < answers.length && i < 4; i++) {
const ele = answers[i];
embed.addField(`${i}. `, `[${ele.word}](${ele.permalink})\r\n${trim(Discord, logger, ele.definition, 1024)}`)
}
}
message.channel.send(embed);
}
catch (error) {
logger.error('Failed to send embed message', error);
message.channel.send('There was a problem, sorry!');
}
}
else {
// If the API returns no results for the specified query
message.channel.send(`There are no results for *${args[0]}*`)
}
})
.catch(function (error) {
logger.error('Something went wrong', error);
});
}
}