Skip to content

Commit

Permalink
Add initial support for Discord
Browse files Browse the repository at this point in the history
  • Loading branch information
robdy committed Nov 29, 2018
1 parent 2635dba commit 55c1534
Show file tree
Hide file tree
Showing 8 changed files with 144 additions and 8 deletions.
41 changes: 38 additions & 3 deletions bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ var commands = require('./commands');
const tasks = require('./tasks');
const warn = _.memoize(console.warn);
const bot = require('./services/irc').setUp(config.irc);
const client = require('./services/discord').client;

if (!config.db) {
// Old config. Maybe we should give the user an option to rewrite the config
Expand All @@ -20,12 +21,17 @@ if (config.db.enabled) {
console.log("The following modules, which require database connectivity, have been disabled: ["+db.listModules().join(", ")+"]");
}

function outputResponse(target, messages) {
// Connect to Discord
if (config.discord.enabled && config.discord.token) {
client.login(config.discord.token);
}

function outputResponse(target, messages, richMessages) {
if (!messages) {
return;
}
if (typeof messages === 'string') {
bot.say(target, messages);
sendMessage(target, messages, richMessages);
} else if (Array.isArray(messages)) {
for (let i = 0; i < messages.length; i++) {
outputResponse(target, messages[i]);
Expand All @@ -42,19 +48,42 @@ function outputResponse(target, messages) {
}
switch (messages['response_type']) {
case 'text':
bot.say(target, messages['message']);
sendMessage(target, messages['message']);
break;
case 'action':
bot.action(target, messages['message']);
break;
default:
console.log("Message containing invalid `response_type` passed to outputResponse()");
}
} else if (typeof messages === 'object' && messages.hasOwnProperty('text') && messages.hasOwnProperty('richText')) {
sendMessage(target, messages.text, messages.richText);
} else {
throw 'Invalid `messages` argument passed to outputResponse()';
}
}

function sendMessage (target, messages, richMessages) {
let discordTarget = '';
if (config.discord.enabled) {
if (target.match(/\d+/)) {
discordTarget = target;
}
else if (config.discord.channels[target].match(/\d+/)) {
discordTarget = config.discord.channels[target]
}
if (!(richMessages)) {
richMessages = messages;
}
}
if (target.match(/#\w*/)) {
bot.say(target, messages);
}
if (discordTarget) {
client.channels.get(discordTarget).send(richMessages);
}
}

function defaultAllow ({isPM, isMod, isAuthenticated}) { // The default allow() function that gets used for a command if allow() is not provided
return !isPM || isMod && isAuthenticated;
}
Expand All @@ -69,7 +98,13 @@ function executeCommands (event, author, channel, text) {
if (message_match && author_match && author !== bot.nick && (isPM || checkEnabled(channel, i, config.irc.channels[channel]))) {
Promise.join(checkIfUserIsMod(author), checkAuthenticated(author), (isMod, isAuthenticated) => {
if ((commands[event][i].allow || defaultAllow)({isPM, isMod, isAuthenticated})) {
if (commands[event][i].richResponse) {
outputResponse(target, commands[event][i].response({bot, message_match, author_match, channel, isMod, isAuthenticated, eventType: event, isPM}),
commands[event][i].richResponse({bot, message_match, author_match, channel, isMod, isAuthenticated, eventType: event, isPM}));
}
else {
outputResponse(target, commands[event][i].response({bot, message_match, author_match, channel, isMod, isAuthenticated, eventType: event, isPM}));
}
} else if (config.debug) {
outputResponse(target, "You are not authorised to run that command");
}
Expand Down
13 changes: 12 additions & 1 deletion commands/fhq.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
'use strict';
const Discord = require('discord.js');
const config = require('../config.js');

module.exports = {
message_regex: /^\.fhq(?: (?:\/u\/)?([\w-]+))?/,
response: ({ message_match: [, username] }) => `https://hq.porygon.co${username ? `/u/${username}` : ''}`
response: ({ message_match: [, username] }) => `https://hq.porygon.co${username ? `/u/${username}` : ''}`,
richResponse: ({ message_match: [, username] }) => {
const embedColor = config.discord.embedColor[Math.floor(Math.random()*config.discord.embedColor.length)];
const embed = new Discord.RichEmbed()
.setTitle(`/u/${username} Flair HQ`, 'https://hq.porygon.co/images/fhq-500.png')
.setURL(`https://hq.porygon.co/u/${username}`)
.setColor(embedColor)

return embed;
}
};
5 changes: 4 additions & 1 deletion commands/lenny.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@ module.exports = {
message_regex: /^\.lenny/,
response: function () {
return "( ͡° ͜ʖ ͡°)‎";
}
},
richResponse: function () {
return "( ͡° ͜ʖ ͡°)!";
},
};
9 changes: 9 additions & 0 deletions config.default.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ module.exports = {
// etc.
}
},
discord: {
enabled: true,
token: 'DISCORD TOKEN',
channels: { // Discord channel IDs for respective IRC ones
'#ircroom1': '111111111111',
},
embedColor: ['#25C1C6', '#F388B2'],

},
db: {
enabled: true,
host: "http://localhost",
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
],
"dependencies": {
"bluebird": "^3.3.4",
"discord.js": "^11.4.2",
"irc": "~0.3.0",
"lodash": "^4.6.1",
"minimist": "^1.2.0",
Expand Down
13 changes: 12 additions & 1 deletion tasks/example.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
// States the current time and the uptime each minute. This is very irritating in practice and enabling it is not recommended.
'use strict';
const Discord = require('discord.js');
const config = require('../config.js');

let counter = 0;
module.exports = {
period: 60,
onStart: true,
task () {
return `The time is now ${new Date().toTimeString()}. This bot was last restarted ${counter++} minutes ago.`;
counter++;
const embedColor = config.discord.embedColor[Math.floor(Math.random()*config.discord.embedColor.length)];
const embed = new Discord.RichEmbed()
.setColor(embedColor)
.setDescription(`The time is now ${new Date().toTimeString()}. This bot was last restarted ${counter} minutes ago.`)
return {
text: `The time is now ${new Date().toTimeString()}. This bot was last restarted ${counter} minutes ago.`,
richText: embed
}
}
};
26 changes: 24 additions & 2 deletions tasks/reports.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ const r = require('../services/reddit');
if (!r) {
return;
}
const Discord = require('discord.js');
const config = require('../config.js');
let reportedItemNames = new Set();
let hasFinishedFirstRun = false;

const SUBREDDITS = ['pokemontrades', 'SVExchange'];
const SUBREDDITS = ['pokemontrades', 'notpokemontrades'];

module.exports = {
period: 60,
Expand All @@ -16,9 +18,16 @@ module.exports = {
// Don't output the new reports on the first fetch, as that would cause old reports to be listed.
// Unfortunately, there is no way to tell whether reports on an item have been ignored using the OAuth API.
const newItemsToReport = hasFinishedFirstRun ? items.filter(item => !reportedItemNames.has(item.name)) : [];
// For testing
// const newItemsToReport = items.filter(item => !reportedItemNames.has(item.name));
items.forEach(item => reportedItemNames.add(item.name));
hasFinishedFirstRun = true;
return newItemsToReport.map(formatItem);
return newItemsToReport.map(item => {
return {
text: formatItem(item),
richText: formatRichItem(item)
}
});
}).catch((e) => console.log(`Error fetching subreddit reports. Error code: ${e.statusCode}`));
}
};
Expand All @@ -28,3 +37,16 @@ function formatItem (item) {
const reportReason = (item.user_reports.length ? item.user_reports[0][0] : item.mod_reports.length ? item.mod_reports[0][0] : '') || '<no reason>';
return `[New report]: "${reportReason}" (on ${item.constructor.name.toLowerCase()} by /u/${item.author.name}, ${permalink} )`;
}

function formatRichItem (item) {
const permalink = item.constructor.name === 'Comment' ? item.link_url + item.id : item.url;
const reportReason = (item.user_reports.length ? item.user_reports[0][0] : item.mod_reports.length ? item.mod_reports[0][0] : '') || '<no reason>';
const embedColor = config.discord.embedColor[Math.floor(Math.random()*config.discord.embedColor.length)];
const embed = new Discord.RichEmbed()
.setAuthor("New Report", "https://i.imgur.com/lm8s41J.png")
.setTitle(`${reportReason}`)
.setURL(permalink)
.setColor(embedColor)
.setDescription(`on ${item.constructor.name.toLowerCase()} by [/u/${item.author.name}](https://reddit.com/user/${item.author.name})`)
return embed;
}
44 changes: 44 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ assertion-error@^1.0.1:
version "1.1.0"
resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b"

async-limiter@~1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8"
integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==

asynckit@^0.4.0:
version "0.4.0"
resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"
Expand Down Expand Up @@ -276,6 +281,17 @@ [email protected]:
version "1.4.0"
resolved "https://registry.yarnpkg.com/diff/-/diff-1.4.0.tgz#7f28d2eb9ee7b15a97efd89ce63dcfdaa3ccbabf"

discord.js@^11.4.2:
version "11.4.2"
resolved "https://registry.yarnpkg.com/discord.js/-/discord.js-11.4.2.tgz#54586981926521572051f2a30b984aad2b49786e"
integrity sha512-MDwpu0lMFTjqomijDl1Ed9miMQe6kB4ifKdP28QZllmLv/HVOJXhatRgjS8urp/wBlOfx+qAYSXcdI5cKGYsfg==
dependencies:
long "^4.0.0"
prism-media "^0.0.3"
snekfetch "^3.6.4"
tweetnacl "^1.0.0"
ws "^4.0.0"

doctrine@^1.2.2:
version "1.5.0"
resolved "https://registry.yarnpkg.com/doctrine/-/doctrine-1.5.0.tgz#379dce730f6166f76cefa4e6707a159b02c5a6fa"
Expand Down Expand Up @@ -763,6 +779,11 @@ [email protected], lodash@^4.0.0, lodash@^4.3.0, lodash@^4.5.1, lodash@^4.6.1:
version "4.17.10"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.10.tgz#1b7793cf7259ea38fb3661d4d38b3260af8ae4e7"

long@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/long/-/long-4.0.0.tgz#9a7b71cfb7d361a194ea555241c92f7468d5bf28"
integrity sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==

lru-cache@2:
version "2.7.3"
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-2.7.3.tgz#6d4524e8b955f95d4f5b58851ce21dd72fb4e952"
Expand Down Expand Up @@ -948,6 +969,11 @@ prelude-ls@~1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.1.2.tgz#21932a549f5e52ffd9a827f570e04be62a97da54"

prism-media@^0.0.3:
version "0.0.3"
resolved "https://registry.yarnpkg.com/prism-media/-/prism-media-0.0.3.tgz#8842d4fae804f099d3b48a9a38e3c2bab6f4855b"
integrity sha512-c9KkNifSMU/iXT8FFTaBwBMr+rdVcN+H/uNv1o+CuFeTThNZNTOrQ+RgXA1yL/DeLk098duAeRPP3QNPNbhxYQ==

process-nextick-args@~1.0.6:
version "1.0.7"
resolved "https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3"
Expand Down Expand Up @@ -1104,6 +1130,11 @@ [email protected]:
version "0.0.4"
resolved "https://registry.yarnpkg.com/slice-ansi/-/slice-ansi-0.0.4.tgz#edbf8903f66f7ce2f8eafd6ceed65e264c831b35"

snekfetch@^3.6.4:
version "3.6.4"
resolved "https://registry.yarnpkg.com/snekfetch/-/snekfetch-3.6.4.tgz#d13e80a616d892f3d38daae4289f4d258a645120"
integrity sha512-NjxjITIj04Ffqid5lqr7XdgwM7X61c/Dns073Ly170bPQHLm6jkmelye/eglS++1nfTWktpP6Y2bFXjdPlQqdw==

snoowrap@^1.8.1:
version "1.15.2"
resolved "https://registry.yarnpkg.com/snoowrap/-/snoowrap-1.15.2.tgz#2086fcb911c64356c04a6e601e2eed23079acaa4"
Expand Down Expand Up @@ -1227,6 +1258,11 @@ tweetnacl@^0.14.3, tweetnacl@~0.14.0:
version "0.14.5"
resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64"

tweetnacl@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-1.0.0.tgz#713d8b818da42068740bf68386d0479e66fc8a7b"
integrity sha1-cT2LgY2kIGh0C/aDhtBHnmb8ins=

type-check@~0.3.2:
version "0.3.2"
resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.3.2.tgz#5884cab512cf1d355e3fb784f30804b2b520db72"
Expand Down Expand Up @@ -1292,6 +1328,14 @@ ws@^1.1.1:
options ">=0.0.5"
ultron "1.0.x"

ws@^4.0.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/ws/-/ws-4.1.0.tgz#a979b5d7d4da68bf54efe0408967c324869a7289"
integrity sha512-ZGh/8kF9rrRNffkLFV4AzhvooEclrOH0xaugmqGsIfFgOE/pIz4fMc4Ef+5HSQqTEug2S9JZIWDR47duDSLfaA==
dependencies:
async-limiter "~1.0.0"
safe-buffer "~5.1.0"

xtend@^4.0.0:
version "4.0.1"
resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"

0 comments on commit 55c1534

Please sign in to comment.