Updated libraries and linted everything

This commit is contained in:
lanxu 2019-08-13 19:37:22 +03:00
parent 68d9d39b00
commit 436fb393ac
22 changed files with 1701 additions and 1937 deletions

157
app.js
View File

@ -1,147 +1,122 @@
// General includes // General includes
const irc = require('irc'); const irc = require('irc')
const fs = require('fs'); const path = require('path')
const winston = require('winston');
require('winston-daily-rotate-file');
const path = require('path');
// Load config // Load config
const config = require('./config'); const config = require('./config')
const cron = require('node-cron'); const cron = require('node-cron')
// Load new plugins // Load new plugins
const PluginManager = require('./plugins/pluginManager.js'); const PluginManager = require('./plugins/pluginManager.js')
const pluginManager = new PluginManager(config); const pluginManager = new PluginManager(config)
pluginManager.loadAllPlugins(); pluginManager.loadAllPlugins()
// Configure logger // Configure logger
// create a write stream (in append mode) // create a write stream (in append mode)
const logDirectory = __dirname + '/log'; const logger = require('./logger')
// ensure log directory exists
if(!fs.existsSync(logDirectory)) { if (!config.irc.connect) {
fs.mkdirSync(logDirectory); logger.info('Not connecting to IRC. Exit')
process.exit()
} }
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.DailyRotateFile)({
filename: logDirectory + '/ircbot.log',
datePattern: 'YYYY-MM-DD',
maxsize: 20000
})
]
});
if(!config.irc.connect) {
logger.info('Not connecting to IRC. Exit');
return;
}
var isConnected = false
// Start client // Start client
var client = new irc.Client(config.irc.server, config.irc.nick, { var client = new irc.Client(config.irc.server, config.irc.nick, {
debug: false, debug: false,
channels: config.irc.channels, channels: config.irc.channels,
//floodProtection: true, // floodProtection: true,
//sasl: true, // sasl: true,
millisecondsOfSilenceBeforePingSent: 60000, millisecondsOfSilenceBeforePingSent: 60000
}); })
var handleMessage = function (from, to, message) {
logger.info(from + ' => ' + to + ': ' + message)
var handleMessage = function(from, to, message) { pluginManager.testPlugins(message).then(function (results) {
logger.info(from + ' => ' + to + ': ' + message); for (var i = 0; i < results.length; i++) {
client.say(to, results[i])
pluginManager.testPlugins(message).then(function(results) {
for(var i = 0; i < results.length; i++) {
client.say(to, results[i]);
} }
}, function(error) { }, function (error) {
logger.error('Plugin error: ', error); logger.error('Plugin error: ', error)
}); })
var res = null;
// Op // Op
if (message.match(/^\.op$/i)) { if (message.match(/^\.op$/i)) {
client.send('NAMES', to); client.send('NAMES', to)
} }
// reload config // reload config
if (message.match(/^\.paivita$/i)) { if (message.match(/^\.paivita$/i)) {
// Using require for config files is dangerous // Using require for config files is dangerous
// Rewrite this in the future // Rewrite this in the future
var filename = path.resolve('./config.js'); var filename = path.resolve('./config.js')
delete require.cache[filename]; delete require.cache[filename]
config = require('./config'); var config = require('./config')
client.say(to, 'Ladattiin asetustiedosto. ' + Object.keys(config.members).length + ' käyttäjäasetusta. Päivitetään operaattorioikeuksia...'); client.say(to, 'Ladattiin asetustiedosto. ' + Object.keys(config.members).length + ' käyttäjäasetusta. Päivitetään operaattorioikeuksia...')
client.send('NAMES', to); client.send('NAMES', to)
} }
}; }
client.addListener('message', function (from, to, message) { client.addListener('message', function (from, to, message) {
if(String(from) !== String(config.irc.nick)) { if (String(from) !== String(config.irc.nick)) {
handleMessage(from, to, message); handleMessage(from, to, message)
} }
}); })
client.addListener('pm', function (from, message) { client.addListener('pm', function (from, message) {
if(String(from) !== String(config.irc.nick)) { if (String(from) !== String(config.irc.nick)) {
handleMessage(from, from, message); handleMessage(from, from, message)
} }
}); })
client.addListener('join', function(channel, who) { client.addListener('join', function (channel, who) {
client.whois(who, function(result) { client.whois(who, function (result) {
console.log(result); console.log(result)
var members = config.members; var members = config.members
for(var memberNick in members) { for (var memberNick in members) {
var member = members[memberNick]; var member = members[memberNick]
if(typeof result.host !== 'undefined' && typeof result.user !== 'undefined') { if (typeof result.host !== 'undefined' && typeof result.user !== 'undefined') {
if(result.host.match(member.host) && result.user.match(member.user)) { if (result.host.match(member.host) && result.user.match(member.user)) {
client.send('MODE', channel, '+o', result.nick); client.send('MODE', channel, '+o', result.nick)
} }
} }
} }
})
})
}); client.addListener('error', function (message) {
}); console.log('error: ', message)
})
client.addListener('error', function(message) { client.addListener('names', function (channel, nicks) {
console.log('error: ', message); if (typeof nicks[config.irc.nick] !== 'undefined' && nicks[config.irc.nick] === '@') {
});
client.addListener('names', function(channel, nicks) {
if(typeof nicks[config.irc.nick] !== 'undefined' && nicks[config.irc.nick] === '@') {
// go through nicks // go through nicks
for(var nick in nicks) { for (var nick in nicks) {
if(nicks[nick] !== '@') { if (nicks[nick] !== '@') {
client.whois(nick, function(result) { client.whois(nick, function (result) {
var members = config.members; var members = config.members
for(var memberNick in members) { for (var memberNick in members) {
var member = members[memberNick]; var member = members[memberNick]
if(result.host.match(member.host) && result.user.match(member.user)) { if (result.host.match(member.host) && result.user.match(member.user)) {
client.send('MODE', channel, '+o', result.nick); client.send('MODE', channel, '+o', result.nick)
} }
} }
}); })
} }
} }
} }
}); })
for (let i = 0; i < config.cron.length; i++) { for (let i = 0; i < config.cron.length; i++) {
let row = config.cron[i] let row = config.cron[i]
let that = this;
cron.schedule(row.cron, () => { cron.schedule(row.cron, () => {
if (client.conn !== null) { if (client.conn !== null) {
for (let c = 0; c < config.irc.channels.length; c++) { for (let c = 0; c < config.irc.channels.length; c++) {
handleMessage('BOT', config.irc.channels[c] , row.command); handleMessage('BOT', config.irc.channels[c], row.command)
} }
} }
}); })
} }

View File

@ -1,76 +1,56 @@
// Start without app // Start without app
function prompt(question, callback) { function prompt (question, callback) {
var stdin = process.stdin, var stdin = process.stdin
stdout = process.stdout; var stdout = process.stdout
stdin.resume(); stdin.resume()
stdout.write(question); stdout.write(question)
stdin.once('data', function (data) { stdin.once('data', function (data) {
callback(data.toString().trim()); callback(data.toString().trim())
}); })
} }
const fs = require('fs');
const winston = require('winston');
require('winston-daily-rotate-file');
const path = require('path');
// Load config // Load config
const config = require('./config'); const config = require('./config')
// Load new plugins // Load new plugins
const PluginManager = require('./plugins/pluginManager.js'); const PluginManager = require('./plugins/pluginManager.js')
const pluginManager = new PluginManager(config); const pluginManager = new PluginManager(config)
pluginManager.loadAllPlugins(); pluginManager.loadAllPlugins()
// Configure logger // Configure logger
// create a write stream (in append mode) // create a write stream (in append mode)
const logDirectory = __dirname + '/log';
// ensure log directory exists // ensure log directory exists
if(!fs.existsSync(logDirectory)) { const logger = require('./logger')
fs.mkdirSync(logDirectory);
}
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.DailyRotateFile)({
filename: logDirectory + '/ircbot-test.log',
datePattern: '.yyyy-MM-dd',
maxsize: 20000
})
]
});
const isPm = false const isPm = false
function query() { function query () {
prompt('> ', function (message) { prompt('> ', function (message) {
if(!isPm) { if (!isPm) {
pluginManager.testPlugins(message).then(function(results) { pluginManager.testPlugins(message).then(function (results) {
for(var i = 0; i < results.length; i++) { for (var i = 0; i < results.length; i++) {
console.log(results[i]); console.log(results[i])
} }
query() query()
}, function(error) { }, function (error) {
logger.error('Plugin error: ', error); logger.error('Plugin error: ', error)
}); query()
})
} else { } else {
// PM // PM
pluginManager.testPlugins(message, false).then(function(results) { pluginManager.testPlugins(message, false).then(function (results) {
for(var i = 0; i < results.length; i++) { for (var i = 0; i < results.length; i++) {
console.log(results[i]); console.log(results[i])
} }
query() query()
}, function(error) { }, function (error) {
logger.error('Plugin error: ', error); logger.error('Plugin error: ', error)
}); query()
})
} }
}); })
} }
query() query()

1817
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -14,26 +14,26 @@
"url": "https://lanxu@bitbucket.org/lanxu/kulmapaikka-ircbot" "url": "https://lanxu@bitbucket.org/lanxu/kulmapaikka-ircbot"
}, },
"dependencies": { "dependencies": {
"chance": "=1.0.13", "chance": "=1.0.18",
"cheerio": "^1.0.0-rc.2", "cheerio": "^1.0.0-rc.2",
"cron": "=1.3.0", "cron": "=1.7.1",
"file-stream-rotator": "=0.2.1", "file-stream-rotator": "=0.4.1",
"finalhandler": "=1.1.1", "finalhandler": "=1.1.2",
"googleapis": "=34.0.0", "googleapis": "=42.0.0",
"html-to-text": "=4.0.0", "html-to-text": "=5.1.1",
"irc": "=0.5.2", "irc": "=0.5.2",
"lokijs": "=1.5.3", "lokijs": "=1.5.7",
"mkdirp": "=0.5.1", "mkdirp": "=0.5.1",
"morgan": "=1.9.0", "morgan": "=1.9.1",
"node-cron": "^2.0.3", "node-cron": "^2.0.3",
"node-dev": "=3.1.3", "node-dev": "=4.0.0",
"node-uuid": "=1.4.8", "node-uuid": "=1.4.8",
"promise": "=8.0.1", "promise": "=8.0.3",
"request": "=2.85.0", "request": "=2.88.0",
"request-promise": "=4.2.2", "request-promise": "=4.2.4",
"twitter": "=1.7.1", "twitter": "=1.7.1",
"winston": "=2.4.2", "winston": "=3.2.1",
"winston-daily-rotate-file": "=3.1.2" "winston-daily-rotate-file": "^3.10.0"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "^1.18.5" "nodemon": "^1.18.5"

View File

@ -1,18 +1,18 @@
class BasePlugin { class BasePlugin {
constructor(config) { constructor (config) {
this.name = 'BasePlugin'; this.name = 'BasePlugin'
this.config = config; this.config = config
} }
test(input) { test (input) {
} }
result(input) { result (input) {
} }
} }
// export default BasePlugin; // export default BasePlugin;
module.exports = BasePlugin; module.exports = BasePlugin

View File

@ -1,62 +1,57 @@
var Promise = require('promise'); var BasePlugin = require('./base.js')
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
class Character1 extends BasePlugin { class Character1 extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Character1'; this.name = 'Character1'
} }
test(input) { test (input) {
var res = null; if (input.match(/^\.luohahmo$/i)) {
if (res = input.match(/^\.luohahmo$/i)) { return true
return true;
} }
return false; return false
} }
throwStat() { throwStat () {
// Heittää 4 kertaa d6:n, tiputtaa heikoimman tuloksen ja laskee // Heittää 4 kertaa d6:n, tiputtaa heikoimman tuloksen ja laskee
// loput yhteen // loput yhteen
var throws = []; var throws = []
var sum = 0; var sum = 0
for( var i = 0; i < 4; i++ ) { for (var i = 0; i < 4; i++) {
var t = Math.floor(Math.random()*6)+1; var t = Math.floor(Math.random() * 6) + 1
throws.push(t); throws.push(t)
} }
throws.sort(); throws.sort()
throws.reverse(); throws.reverse()
var sum = 0; sum = 0
for(var i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
sum += throws[i]; sum += throws[i]
} }
return sum; return sum
} }
getDnDCharacter() { getDnDCharacter () {
var statPoints = 'DnD-statsit:'; var statPoints = 'DnD-statsit:'
var total = 0; var total = 0
for( var i = 0; i < 6; i++) { for (var i = 0; i < 6; i++) {
var newStat = this.throwStat(); var newStat = this.throwStat()
statPoints += ' '; // erotetaan sanat toisistaan statPoints += ' ' // erotetaan sanat toisistaan
statPoints += newStat; statPoints += newStat
total += Number(newStat); total += Number(newStat)
} }
statPoints += ' ('+total+')'; statPoints += ' (' + total + ')'
return statPoints; return statPoints
}; };
result(input) { result (input) {
// Different cases // Different cases
let info = this.getDnDCharacter(); let info = this.getDnDCharacter()
return info; return info
} }
} }
module.exports = Character1; module.exports = Character1

View File

@ -1,33 +1,29 @@
var Promise = require('promise'); var BasePlugin = require('./base.js')
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var Chance = require('chance'); var Chance = require('chance')
var chance = new Chance(); var chance = new Chance()
class Character { class Character {
constructor() { constructor () {
this.gender = null
this.gender = null; this.name = null
this.name = null; this.class = null
this.class = null; this.alignment = null
this.alignment = null; this.stats = []
this.stats = []; this.statSum = -1
this.statSum = -1;
} }
create() { create () {
this.gender = chance.gender(); this.gender = chance.gender()
this.name = chance.first({gender: this.gender}); this.name = chance.first({gender: this.gender})
// Throw stats // Throw stats
for(var i = 0; i < 6; i++) { for (var i = 0; i < 6; i++) {
var throws = [chance.d6(), chance.d6(), chance.d6(), chance.d6()].sort(); var throws = [chance.d6(), chance.d6(), chance.d6(), chance.d6()].sort()
throws.splice(0, 1); throws.splice(0, 1)
var stat = throws.reduce(function(a, b) { return a + b; }, 0); var stat = throws.reduce(function (a, b) { return a + b }, 0)
this.stats.push(stat); this.stats.push(stat)
} }
this.statSum = this.stats.reduce(function(a, b) { return a + b; }, 0); this.statSum = this.stats.reduce(function (a, b) { return a + b }, 0)
// Select race // Select race
var races = { var races = {
@ -37,20 +33,20 @@ class Character {
'Gnome': 'Bard', 'Gnome': 'Bard',
'Half-Elf': '', 'Half-Elf': '',
'Half-Orc': 'Barbarian', 'Half-Orc': 'Barbarian',
'Halfling': 'Rogue', 'Halfling': 'Rogue'
}; }
this.race = Object.keys(races)[chance.natural({min: 0, max: Object.keys(races).length-1})]; this.race = Object.keys(races)[chance.natural({min: 0, max: Object.keys(races).length - 1})]
// Select alignment // Select alignment
var alignmentY = ['Good', 'Neutral', 'Evil'].splice(chance.natural({min: 0, max: 2}), 1); var alignmentY = ['Good', 'Neutral', 'Evil'].splice(chance.natural({min: 0, max: 2}), 1)
var alignmentX = ['Lawful', 'Neutral', 'Chaotic'].splice(chance.natural({min: 0, max: 2}), 1); var alignmentX = ['Lawful', 'Neutral', 'Chaotic'].splice(chance.natural({min: 0, max: 2}), 1)
this.alignment = (alignmentY[0] === 'Neutral' && alignmentX[0] === 'Neutral') ? 'True Neutral' : alignmentX[0] + ' ' + alignmentY[0]; this.alignment = (alignmentY[0] === 'Neutral' && alignmentX[0] === 'Neutral') ? 'True Neutral' : alignmentX[0] + ' ' + alignmentY[0]
// Select class // Select class
var classes = { var classes = {
'Barbarian' : '', 'Barbarian': '',
'Bard': '', 'Bard': '',
'Cleric': '', 'Cleric': '',
'Druid': '', 'Druid': '',
@ -59,72 +55,74 @@ class Character {
'Paladin': '', 'Paladin': '',
'Ranger': '', 'Ranger': '',
'Rogue': '', 'Rogue': '',
'Sorcerer': '', 'Sorcerer': ''
} }
this.class = Object.keys(classes)[chance.natural({min: 0, max: Object.keys(classes).length-1})]; this.class = Object.keys(classes)[chance.natural({min: 0, max: Object.keys(classes).length - 1})]
// Select age // Select age
var roll = function(times, func) { var roll = function (times, func) {
var sum = 0; var sum = 0
for(var i = 0; i < times; i++) { for (var i = 0; i < times; i++) {
sum += chance[func](); sum += chance[func]()
} }
return sum; return sum
} }
var ages = { var ages = {
'Human': { start: 15, classes: [roll(1, 'd4'), roll(1, 'd6'), roll(2, 'd6')] }, 'Human': { start: 15, classes: [roll(1, 'd4'), roll(1, 'd6'), roll(2, 'd6')] },
'Dwarf': { start: 40, classes: [roll(3, 'd6'), roll(5, 'd6'), roll(6, 'd6')] }, 'Dwarf': { start: 40, classes: [roll(3, 'd6'), roll(5, 'd6'), roll(6, 'd6')] },
'Elf': { start: 110, classes: [roll(4, 'd6'), roll(6, 'd6'), roll(10, 'd6')] }, 'Elf': { start: 110, classes: [roll(4, 'd6'), roll(6, 'd6'), roll(10, 'd6')] },
'Gnome': { start: 40, classes: [roll(4, 'd6'), roll(6, 'd6'), roll(9, 'd6')] }, 'Gnome': { start: 40, classes: [roll(4, 'd6'), roll(6, 'd6'), roll(9, 'd6')] },
'Half-Elf': { start: 20, classes: [roll(1, 'd6'), roll(2, 'd6'), roll(3, 'd6')] }, 'Half-Elf': { start: 20, classes: [roll(1, 'd6'), roll(2, 'd6'), roll(3, 'd6')] },
'Half-Orc': { start: 14, classes: [roll(1, 'd4'), roll(1, 'd6'), roll(2, 'd6')] }, 'Half-Orc': { start: 14, classes: [roll(1, 'd4'), roll(1, 'd6'), roll(2, 'd6')] },
'Halfling': { start: 20, classes: [roll(2, 'd4'), roll(3, 'd6'), roll(4, 'd6')] }, 'Halfling': { start: 20, classes: [roll(2, 'd4'), roll(3, 'd6'), roll(4, 'd6')] }
}; }
var ageClasses = { var ageClasses = {
'Barbarian': 0, 'Rogue': 0, 'Sorcerer': 0, 'Barbarian': 0,
'Bard': 1, 'Fighter': 1, 'Paladin': 1, 'Ranger': 1, 'Rogue': 0,
'Cleric': 2, 'Druid': 2, 'Monk': 2, 'Wizard': 2, 'Sorcerer': 0,
}; 'Bard': 1,
'Fighter': 1,
this.age = ages[this.race].start + ages[this.race].classes[ageClasses[this.class]]; 'Paladin': 1,
'Ranger': 1,
'Cleric': 2,
'Druid': 2,
'Monk': 2,
'Wizard': 2
}
this.age = ages[this.race].start + ages[this.race].classes[ageClasses[this.class]]
} }
toString() { toString () {
var str = this.age + " years old " + this.alignment + " " + this.gender + " " + this.race + " " + this.class + " named " + this.name; var str = this.age + ' years old ' + this.alignment + ' ' + this.gender + ' ' + this.race + ' ' + this.class + ' named ' + this.name
str += " with stats "; str += ' with stats '
this.stats.forEach(function(val) { this.stats.forEach(function (val) {
str += val + " "; str += val + ' '
}); })
str += " ("+this.statSum+")"; str += ' (' + this.statSum + ')'
return str; return str
} }
} }
class Character2 extends BasePlugin { class Character2 extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Character2'; this.name = 'Character2'
} }
test(input) { test (input) {
var res = null; if (input.match(/^\.luohahmo2$/i)) {
if (res = input.match(/^\.luohahmo2$/i)) { return true
return true;
} }
return false; return false
} }
result(input) { result (input) {
// Different cases // Different cases
let newChar = new Character(); let newChar = new Character()
newChar.create(); newChar.create()
let result = newChar.toString(); let result = newChar.toString()
return result; return result
} }
} }
module.exports = Character2; module.exports = Character2

View File

@ -1,68 +1,63 @@
var Promise = require('promise'); var BasePlugin = require('./base.js')
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
class Dice extends BasePlugin { class Dice extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Dice'; this.name = 'Dice'
} }
test(input) { test (input) {
var res = null; if (input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)) {
if (res = input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)) {
return true;
}
if (res = input.match(/^\.heit(a|ä) voltti homo$/i)) {
return true return true
} }
return false; if (input.match(/^\.heit(a|ä) voltti homo$/i)) {
return true
}
return false
} }
getDiceString(numThrows, sides) { getDiceString (numThrows, sides) {
var total = 0
var totalThrows = []
var total = 0; numThrows = Number(numThrows)
var totalThrows = []; sides = Number(sides)
numThrows = Number(numThrows); if (numThrows === 0 || sides === 0) {
sides = Number(sides); return 'Tyhjää ei voi heittää'
if(numThrows === 0 || sides === 0) {
return 'Tyhjää ei voi heittää';
} }
if(numThrows > 100) { if (numThrows > 100) {
return 'Ei jaksa...'; return 'Ei jaksa...'
} }
for(var a = 0; a < numThrows; a++) { for (var a = 0; a < numThrows; a++) {
var t = Math.floor(Math.random()*sides)+1; var t = Math.floor(Math.random() * sides) + 1
totalThrows.push(t); totalThrows.push(t)
total += t; total += t
} }
var resultString = ''; var resultString = ''
totalThrows.forEach(function(value) { totalThrows.forEach(function (value) {
resultString += value + ', '; resultString += value + ', '
}); })
resultString = resultString.substring(0, resultString.length - 2); resultString = resultString.substring(0, resultString.length - 2)
resultString += ' (yhteensä: ' + total + '. '+ (total/numThrows).toFixed(2) + ' per heitto)'; resultString += ' (yhteensä: ' + total + '. ' + (total / numThrows).toFixed(2) + ' per heitto)'
return resultString; return resultString
} }
result(input) { result (input) {
// Different cases // Different cases
let res = null let res = null
if (res = input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)) { res = input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)
var th = this.getDiceString(res[2], res[3]); if (res !== null) {
return 'Heitettiin: '+th; var th = this.getDiceString(res[2], res[3])
return 'Heitettiin: ' + th
} }
if (input.match(/^\.heit(a|ä) voltti homo$/i)) { if (input.match(/^\.heit(a|ä) voltti homo$/i)) {
return 'steam://run/1250'; return 'steam://run/1250'
} }
} }
} }
module.exports = Dice; module.exports = Dice

View File

@ -1,40 +1,37 @@
var Promise = require('promise'); var Promise = require('promise')
var DDG = require('node-ddg-api').DDG; var DDG = require('node-ddg-api').DDG
module.exports = function(config) { module.exports = function (config) {
var ddg = new DDG('kulmapaikka-ircbot')
var ddg = new DDG('kulmapaikka-ircbot'); var getAnswer = function (queryText) {
var promise = new Promise(function (resolve, reject) {
ddg.instantAnswer(queryText, {skip_disambig: '0'}, function (error, response) {
if (!error) {
var str = ''
if (response.AbstractText !== '') {
var text = ''
if (response.AbstractText.length > 350) {
text = response.AbstractText.substring(0, 350 - response.AbstractURL.length) + '...'
} else {
text = response.AbstractText
}
var getAnswer = function(queryText) { str = 'Vastaus: ' + text + '" | ' + response.AbstractURL
var promise = new Promise(function(resolve, reject) { resolve(str)
ddg.instantAnswer(queryText, {skip_disambig: '0'}, function(error, response) { } else if (response.RelatedTopics.length > 0) {
if(!error) { str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL
var str = ''; resolve(str)
if(response.AbstractText !== '') { } else {
var text = ''; reject(new Error(''))
if(response.AbstractText.length > 350) { }
text = response.AbstractText.substring(0, 350-response.AbstractURL.length) + '...'; } else {
} else { reject(new Error(''))
text = response.AbstractText; }
} })
})
return promise
}
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL; return getAnswer
resolve(str); }
}
else if(response.RelatedTopics.length > 0) {
str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL;
resolve(str);
} else {
reject();
}
} else {
reject();
}
});
});
return promise;
};
return getAnswer;
};

View File

@ -1,49 +1,46 @@
var Promise = require('promise'); var Promise = require('promise')
var request = require('request'); var request = require('request')
var requestPromise = function (url, urlArgs) { var requestPromise = function (url, urlArgs) {
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
request({ request({
url: url, url: url,
qs: urlArgs, qs: urlArgs,
json: false json: false
}, function(error, response, body) { }, function (error, response, body) {
if(!error && response.statusCode == 200) { if (!error && response.statusCode === 200) {
resolve(body); resolve(body)
} else { } else {
reject(error); reject(error)
} }
}); })
}); })
return promise; return promise
}; }
module.exports = function(config) { module.exports = function (config) {
// http://stackoverflow.com/questions/13087888/getting-the-page-title-from-a-scraped-webpage // http://stackoverflow.com/questions/13087888/getting-the-page-title-from-a-scraped-webpage
var getTitle = function(url) { var getTitle = function (url) {
var urlOpts = {host: url, path: '/', port: '80'}; var re = /(<\s*title[^>]*>((.|\n)+?)<\s*\/\s*title)>/gi
var urlArgs = {}
var re = /(<\s*title[^>]*>((.|\n)+?)<\s*\/\s*title)>/gi; var promise = new Promise(function (resolve, reject) {
var urlArgs = {}; var urlPromise = requestPromise(url, urlArgs)
urlPromise.then(function (data) {
var match = re.exec(data)
var promise = new Promise(function(resolve, reject) { if (match && match[2]) {
var urlPromise = requestPromise(url, urlArgs); var title = match[2].trim() // remove whitespace
urlPromise.then(function(data) { title = title.replace(/\r?\n|\r/g, '') // remove newlines
var match = re.exec(data); resolve(title)
} else {
reject(new Error())
}
})
})
return promise
}
if (match && match[2]) { return getTitle
var title = match[2].trim(); // remove whitespace }
title = title.replace(/\r?\n|\r/g, ''); // remove newlines
resolve(title);
} else {
reject();
}
});
});
return promise;
};
return getTitle;
};

View File

@ -1,101 +1,103 @@
const Promise = require('promise'); const Promise = require('promise')
const requestPromise = require('./requestPromise.js'); const {google} = require('googleapis')
const {google} = require('googleapis'); const youtube = google.youtube('v3')
const youtube = google.youtube('v3'); const logger = require('../../logger')
const apis = google.getSupportedAPIs();
module.exports = function(config) { module.exports = function (config) {
'use strict'; 'use strict'
var apikey = config.keys.google.apiKey; var apikey = config.keys.google.apiKey
return { return {
getYoutubeVideoById: function(videoId) { getYoutubeVideoById: function (videoId) {
var promise = new Promise(function(resolve, reject) { return new Promise(function (resolve, reject) {
var videosParams = { var videosParams = {
part: 'snippet,contentDetails,statistics', part: 'snippet,contentDetails,statistics',
id: videoId, id: videoId,
key: apikey key: apikey
}; }
var thisResolve = resolve; var thisResolve = resolve
var thisReject = reject; var thisReject = reject
youtube.videos.list(videosParams, function(err, response) { youtube.videos.list(videosParams, function (err, response) {
let resp = response.data; if (err !== null) {
if(typeof resp === 'undefined' || resp === null || typeof resp.items === 'undefined' || resp.items === null || resp.items.length <= 0) { logger.error(err)
thisReject('No results'); thisReject(new Error('Google error'))
return; return
}
let resp = response.data
if (typeof resp === 'undefined' || resp === null || typeof resp.items === 'undefined' || resp.items === null || resp.items.length <= 0) {
thisReject('No results')
return
} }
var duration = resp.items[0].contentDetails.duration; var duration = resp.items[0].contentDetails.duration
var formattedTime = duration.replace("PT","").replace("H","t ").replace("M","m ").replace("S","s"); var formattedTime = duration.replace('PT', '').replace('H', 't ').replace('M', 'm ').replace('S', 's')
var data = { var data = {
videoId: videoId, videoId: videoId,
url: 'https://youtu.be/'+videoId, url: 'https://youtu.be/' + videoId,
title: resp.items[0].snippet.title, title: resp.items[0].snippet.title,
channelTitle: resp.items[0].snippet.channelTitle, channelTitle: resp.items[0].snippet.channelTitle,
statistics: resp.items[0].statistics, statistics: resp.items[0].statistics,
duration: formattedTime duration: formattedTime
}; }
thisResolve(data); thisResolve(data)
}); })
}); })
return promise;
}, },
getYoutubeVideo: function(query) { getYoutubeVideo: function (query) {
var params = { var params = {
part: 'snippet', part: 'snippet',
q: query, q: query,
type: 'video', type: 'video',
order: 'viewCount', order: 'viewCount',
key: apikey key: apikey
}; }
console.log(params); logger.debug(params)
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
youtube.search.list(params, function(err, resp) { youtube.search.list(params, function (err, resp) {
if (err) { if (err) {
console.log('An error occured', err); console.log('An error occured', err)
reject(err); reject(err)
} }
if(resp === null || resp.items === null) { if (resp === null || resp.items === null) {
reject('No results (null)'); reject(new Error('No results (null)'))
return; return
} }
if(resp.items.length <= 0) { if (resp.items.length <= 0) {
reject('No results'); reject(new Error('No results'))
return; return
} }
var videoId = resp.items[0].id.videoId; var videoId = resp.items[0].id.videoId
var data = { var data = {
videoId: videoId, videoId: videoId,
url: 'https://youtu.be/'+videoId, url: 'https://youtu.be/' + videoId,
title: resp.items[0].snippet.title, title: resp.items[0].snippet.title,
channelTitle: resp.items[0].snippet.channelTitle channelTitle: resp.items[0].snippet.channelTitle
}; }
var videosParams = { var videosParams = {
part: 'snippet,contentDetails,statistics', part: 'snippet,contentDetails,statistics',
id: videoId, id: videoId,
key: apikey key: apikey
}; }
youtube.videos.list(videosParams, function(err2, resp2) { youtube.videos.list(videosParams, function (err2, resp2) {
//console.log('respo', resp2); // console.log('respo', resp2);
if(resp2.items.length <= 0) { if (resp2.items.length <= 0) {
reject('No results'); reject(new Error('No results'))
return; return
} }
data.statistics = resp2.items[0].statistics; data.statistics = resp2.items[0].statistics
var duration = resp2.items[0].contentDetails.duration; var duration = resp2.items[0].contentDetails.duration
var formattedTime = duration.replace("PT","").replace("H","t ").replace("M","m ").replace("S","s"); var formattedTime = duration.replace('PT', '').replace('H', 't ').replace('M', 'm ').replace('S', 's')
data.duration = formattedTime; data.duration = formattedTime
resolve(data); resolve(data)
}); })
}); })
}); })
return promise; return promise
} }
}; }
}; }

View File

@ -1,34 +1,34 @@
var request = require('request'); var request = require('request')
var Promise = require('promise'); var Promise = require('promise')
function RequestPromise(url, urlArgs, headers, json) { function RequestPromise (url, urlArgs, headers, json) {
if(typeof headers === 'undefined') { if (typeof headers === 'undefined') {
headers = {}; headers = {}
} }
if(typeof json === 'undefined') { if (typeof json === 'undefined') {
json = false; json = false
} }
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
request({ request({
url: url, url: url,
qs: urlArgs, qs: urlArgs,
headers: headers, headers: headers,
json: json json: json
}, function(error, response, body) { }, function (error, response, body) {
if(!error && response.statusCode == 200) { if (!error && response.statusCode === 200) {
if (json === false) { if (json === false) {
resolve(JSON.parse(body)); /// wtf resolve(JSON.parse(body)) /// wtf
} else { } else {
resolve(body) resolve(body)
} }
} else { } else {
reject(error); reject(error)
} }
}); })
}); })
return promise; return promise
} }
module.exports = RequestPromise; module.exports = RequestPromise

View File

@ -1,80 +1,76 @@
var Promise = require('promise'); var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js'); var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js'); var BasePlugin = require('./base.js')
var logger = require('winston');
class InstantAswer extends BasePlugin { class InstantAswer extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'InstantAswer'; this.name = 'InstantAswer'
} }
test(input) { test (input) {
var res = null; if (input.match(/^\.wtf (.+)$/i)) {
if (res = input.match(/^\.wtf (.+)$/i)) { return true
return true;
} }
return false; return false
} }
getDDG(query) { getDDG (query) {
var urlArgs = { var urlArgs = {
q: query, q: query,
kp: -1, kp: -1,
skip_disambig: '0', skip_disambig: '0',
format: 'json' format: 'json'
}; }
let url = 'https://api.duckduckgo.com/'; let url = 'https://api.duckduckgo.com/'
var promise = requestPromise(url, urlArgs, { var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json', 'Accept': 'application/json'
}); })
return promise; return promise
} }
getAnswer(query) { getAnswer (query) {
let that = this; let that = this
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
that.getDDG(query).then((response) => { that.getDDG(query).then((response) => {
var str = ''; var str = ''
if(response.AbstractText !== '') { if (response.AbstractText !== '') {
var text = ''; var text = ''
if(response.AbstractText.length > 350) { if (response.AbstractText.length > 350) {
text = response.AbstractText.substring(0, 350-response.AbstractURL.length) + '...'; text = response.AbstractText.substring(0, 350 - response.AbstractURL.length) + '...'
} else { } else {
text = response.AbstractText; text = response.AbstractText
} }
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL; str = 'Vastaus: ' + text + '" | ' + response.AbstractURL
resolve(str); resolve(str)
} } else if (response.RelatedTopics.length > 0) {
else if(response.RelatedTopics.length > 0) { str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL
str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL; resolve(str)
resolve(str);
} else { } else {
reject(); reject(new Error())
} }
}, reject); }, reject)
}); })
return promise; return promise
} }
result(input) { result (input) {
let that = this; let that = this
var resultPromise = new Promise(function(resultResolve, resultReject) { var resultPromise = new Promise(function (resolve, reject) {
var res = null; var res = input.match(/^\.wtf (.+)$/i)
if (res = input.match(/^\.wtf (.+)$/i)) { if (res !== null) {
let query = res[1] let query = res[1]
that.getAnswer(query).then(str => { that.getAnswer(query).then(str => {
resultResolve(str); resolve(str)
}) })
} else { } else {
resultReject(); reject(new Error())
} }
}); })
return resultPromise; return resultPromise
} }
} }
module.exports = InstantAswer; module.exports = InstantAswer

View File

@ -1,59 +1,54 @@
var Promise = require('promise'); var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js'); var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js'); var BasePlugin = require('./base.js')
var logger = require('winston');
class Joke extends BasePlugin { class Joke extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Joke'; this.name = 'Joke'
} }
test(input) { test (input) {
var res = null; if (input.match(/^\.vitsi$/i)) {
if (res = input.match(/^\.vitsi$/i)) { return true
return true;
} }
return false; return false
} }
getJoke () {
var urlArgs = {}
var url = 'https://icanhazdadjoke.com/'
getJoke() { var promise = requestPromise(url, urlArgs, {
var urlArgs = {}; 'Accept': 'application/json'
var url = 'https://icanhazdadjoke.com/'; })
var promise = requestPromise(url, urlArgs, { return promise
'Accept': 'application/json',
});
return promise;
} }
result(input) { result (input) {
var that = this; var that = this
var resultPromise = new Promise(function(resultResolve, resultReject) { var resultPromise = new Promise(function (resolve, reject) {
var res = null; if (input.match(/^\.vitsi$/i)) {
if (res = input.match(/^\.vitsi$/i)) { that.getJoke().then(function (data) {
that.getJoke().then(function(data) { var text = 'Vitsi: '
var text = 'Vitsi: ';
var joke = data.joke; var joke = data.joke
if(typeof joke === 'undefined' || joke === null) { if (typeof joke === 'undefined' || joke === null) {
resultReject('No joke!'); reject(new Error('No joke!'))
} }
text += "\"" + joke + "\""; text += '"' + joke + '"'
resultResolve(text); resolve(text)
}, function (error) {
}, function(error) { reject(error)
resultReject(error); })
});
} }
}); })
return resultPromise; return resultPromise
} }
} }
module.exports = Joke; module.exports = Joke

View File

@ -1,88 +1,84 @@
var Promise = require('promise'); var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js'); var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js'); var BasePlugin = require('./base.js')
var logger = require('winston'); const logger = require('../logger')
class Kernel extends BasePlugin { class Kernel extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Kernel'; this.name = 'Kernel'
} }
getKernelData(queryText) { getKernelData (queryText) {
var urlArgs = {}; var urlArgs = {}
var url = 'https://www.kernel.org/releases.json'; var url = 'https://www.kernel.org/releases.json'
var promise = requestPromise(url, urlArgs); var promise = requestPromise(url, urlArgs)
return promise; return promise
} }
test(input) { test (input) {
// Kernel version // Kernel version
var res = null; if (input.match(/^\.kernel( (.+))?/i)) {
if (res = input.match(/^\.kernel( (.+))?/i)) { return true
return true;
} }
return false; return false
} }
result(input) { result (input) {
var that = this; var that = this
var resultPromise = new Promise(function(resultResolve, resultReject) { var resultPromise = new Promise(function (resolve, reject) {
var res = null; var res = input.match(/^\.kernel( (.+))?/i)
if (res = input.match(/^\.kernel( (.+))?/i)) { if (res !== null) {
var version = res[2]; var version = res[2]
logger.info('Search kernel version ' + res[2]); logger.info('Search kernel version ' + res[2])
that.getKernelData().then(function(data) { that.getKernelData().then(function (data) {
var text = 'kernel: '; var text = 'kernel: '
// Store current versions! // Store current versions!
var releaseToVersion = {}; var releaseToVersion = {}
data.releases.forEach(function(val) { data.releases.forEach(function (val) {
var regex = /([0-9]+?)(\.([0-9]+))?(\.([0-9]+))?/; var regex = /([0-9]+?)(\.([0-9]+))?(\.([0-9]+))?/
var result = val.version.match(regex); var result = val.version.match(regex)
var major = result[1]; var major = result[1]
var minor = result[3]; var minor = result[3]
if(typeof major !== 'undefined' && typeof minor !== 'undefined') { if (typeof major !== 'undefined' && typeof minor !== 'undefined') {
var releaseWithVersion = val.moniker + '-' + major + '-' + minor; var releaseWithVersion = val.moniker + '-' + major + '-' + minor
var release = val.moniker + ''; var release = val.moniker + ''
if(typeof releaseToVersion[releaseWithVersion] !== 'undefined') { if (typeof releaseToVersion[releaseWithVersion] !== 'undefined') {
if(releaseToVersion[releaseWithVersion] !== val.version) { if (releaseToVersion[releaseWithVersion] !== val.version) {
// new release // new release
} }
} }
if(typeof releaseToVersion[release] === 'undefined') { if (typeof releaseToVersion[release] === 'undefined') {
releaseToVersion[release] = val.version; releaseToVersion[release] = val.version
} }
releaseToVersion[releaseWithVersion] = val.version; releaseToVersion[releaseWithVersion] = val.version
} }
}, function(error) { }, function (error) {
resultReject(error); reject(error)
}); })
if(typeof releaseToVersion[version] !== 'undefined') { if (typeof releaseToVersion[version] !== 'undefined') {
text += 'Viimeisin versio on ' + releaseToVersion[version] + ' (' + version + ')'; text += 'Viimeisin versio on ' + releaseToVersion[version] + ' (' + version + ')'
} else { } else {
text += 'Viimeisin vakaa versio on ' + data.latest_stable.version
text += 'Viimeisin vakaa versio on ' + data.latest_stable.version;
} }
resultResolve(text); resolve(text)
}, function(error) { }, function (error) {
resultReject(error); reject(error)
}); })
} }
}); })
return resultPromise; return resultPromise
} }
} }
module.exports = Kernel
module.exports = Kernel;

View File

@ -1,85 +1,83 @@
var Promise = require('promise'); var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js'); var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js'); var BasePlugin = require('./base.js')
var logger = require('winston'); var htmlToText = require('html-to-text')
var htmlToText = require('html-to-text');
class Mastodon extends BasePlugin { class Mastodon extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Mastodon'; this.name = 'Mastodon'
} }
test(input) { test (input) {
var res = null; if (input.match(/http(s)?:\/\/(www\.)?((.*\..*\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) {
if (res = input.match(/http(s)?:\/\/(www\.)?((.*\..*\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) { return true
return true;
} }
if (res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) { if (input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) {
return true; return true
} }
return false; return false
} }
getToot(host, statusId) { getToot (host, statusId) {
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
var url = 'https://' + host + '/api/v1/statuses/' + statusId; var url = 'https://' + host + '/api/v1/statuses/' + statusId
requestPromise(url, {}, { requestPromise(url, {}, {
'Accept': 'application/json', 'Accept': 'application/json'
}).then(function(toot) { }).then(function (toot) {
if(!toot.error) { if (!toot.error) {
var user = toot.account.username; var user = toot.account.username
var time = toot.created_at; var time = toot.created_at
var dateTime = new Date(time); var dateTime = new Date(time)
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes(); var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes()
var tootContent = toot.content; var tootContent = toot.content
var tootContent = htmlToText.fromString(tootContent, { tootContent = htmlToText.fromString(tootContent, {
wordwrap: false, wordwrap: false,
ignoreHref: true, ignoreHref: true,
preserveNewlines: false, preserveNewlines: false
}); })
var str = '@' + user + ': "' + tootContent + '" ('+ dateTimeLocale +')'; var str = '@' + user + ': "' + tootContent + '" (' + dateTimeLocale + ')'
str = str.replace(/(?:\r\n|\r|\n)/g, ' '); str = str.replace(/(?:\r\n|\r|\n)/g, ' ')
resolve(str); resolve(str)
} else { } else {
reject(); reject(new Error(''))
} }
}); })
})
}); return promise
return promise;
} }
result(input) { result (input) {
var that = this; var that = this
var resultPromise = new Promise(function(resultResolve, resultReject) { var resultPromise = new Promise(function (resolve, reject) {
var host = null; var host = null
var tootId = null; var tootId = null
var res = null; var res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)
if (res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) { if (res !== null) {
host = res[5]; host = res[5]
tootId = res[7]; tootId = res[7]
} }
if (res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) { res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)
host = res[5]; if (res !== null) {
tootId = res[7]; host = res[5]
tootId = res[7]
} }
if (host !== null && tootId !== null) { if (host !== null && tootId !== null) {
that.getToot(host, tootId).then(function(toot) { that.getToot(host, tootId).then(function (toot) {
resultResolve('Tuuttaus: ' + toot); resolve('Tuuttaus: ' + toot)
}, function(error) { }, function () {
resultReject('Tuuttaus: Jokin virhe tapahtui'); reject(new Error('Tuuttaus: Jokin virhe tapahtui'))
}); })
} }
}); })
return resultPromise; return resultPromise
} }
} }
module.exports = Mastodon; module.exports = Mastodon

View File

@ -1,78 +1,76 @@
var logger = require('winston'); var fs = require('fs')
var fs = require('fs'); var Promise = require('promise')
var Promise = require('promise'); const logger = require('../logger')
class PluginManager { class PluginManager {
constructor(config) { constructor (config) {
this.enabledPlugins = []; this.enabledPlugins = []
this.enabledPmPlugins = []; this.enabledPmPlugins = []
this.plugins = []; this.plugins = []
this.pmPlugins = []; this.pmPlugins = []
this.config = config; this.config = config
var that = this; var that = this
config.plugins.forEach(function(pluginName) { config.plugins.forEach(function (pluginName) {
logger.info('checking ' + pluginName + '...'); logger.info('checking ' + pluginName + '...')
if(fs.existsSync('./plugins/'+pluginName.toLowerCase()+'.js')) { if (fs.existsSync('./plugins/' + pluginName.toLowerCase() + '.js')) {
logger.info('* Exists. Enabling...'); logger.info('* Exists. Enabling...')
that.enabledPlugins.push(pluginName.toLowerCase()); that.enabledPlugins.push(pluginName.toLowerCase())
} }
if(fs.existsSync('./plugins/pm'+pluginName.toLowerCase()+'.js')) { if (fs.existsSync('./plugins/pm' + pluginName.toLowerCase() + '.js')) {
logger.info('* Exists as PM plugin. Enabling...'); logger.info('* Exists as PM plugin. Enabling...')
that.enabledPmPlugins.push(pluginName.toLowerCase()); that.enabledPmPlugins.push(pluginName.toLowerCase())
} }
}); })
} }
loadAllPlugins() { loadAllPlugins () {
var that = this; var that = this
this.enabledPlugins.forEach(function(pluginName) { this.enabledPlugins.forEach(function (pluginName) {
var Plugin = require('./' + pluginName + '.js'); var Plugin = require('./' + pluginName + '.js')
var plugin = new Plugin(that.config); var plugin = new Plugin(that.config)
that.plugins.push(plugin); that.plugins.push(plugin)
}); })
this.enabledPmPlugins.forEach(function(pluginName) { this.enabledPmPlugins.forEach(function (pluginName) {
var Plugin = require('./pm' + pluginName + '.js'); var Plugin = require('./pm' + pluginName + '.js')
var plugin = new Plugin(that.config); var plugin = new Plugin(that.config)
that.pmPlugins.push(plugin); that.pmPlugins.push(plugin)
}); })
} }
testPlugins(input, publicChat) { testPlugins (input, publicChat) {
if (typeof publicChat === 'undefined') { if (typeof publicChat === 'undefined') {
publicChat = true publicChat = true
} }
var promises = []; var promises = []
if (publicChat) { if (publicChat) {
for(let i = 0; i < this.plugins.length; i++) { for (let i = 0; i < this.plugins.length; i++) {
var plugin = this.plugins[i]; let plugin = this.plugins[i]
if(plugin.test(input)) { if (plugin.test(input)) {
logger.info('* Plugin ' + plugin.name + ' reported hit'); logger.info('* Plugin ' + plugin.name + ' reported hit')
promises.push(plugin.result(input)); promises.push(plugin.result(input))
} }
} }
} else { } else {
for(let i = 0; i < this.pmPlugins.length; i++) { for (let i = 0; i < this.pmPlugins.length; i++) {
var plugin = this.pmPlugins[i]; let plugin = this.pmPlugins[i]
if(plugin.test(input)) { if (plugin.test(input)) {
logger.info('* Plugin ' + plugin.name + ' reported hit'); logger.info('* Plugin ' + plugin.name + ' reported hit')
promises.push(plugin.result(input)); promises.push(plugin.result(input))
} }
} }
} }
return Promise.all(promises); return Promise.all(promises)
} }
} }
// export default BasePlugin; // export default BasePlugin;
module.exports = PluginManager; module.exports = PluginManager

View File

@ -1,31 +1,26 @@
var Promise = require('promise'); var BasePlugin = require('./base.js')
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
class Users extends BasePlugin { class Users extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Users'; this.name = 'Users'
} }
test(input) { test (input) {
var res = null; if (input.match(/.*/i)) {
if (res = input.match(/.*/i)) { return true
return true;
} }
return false; return false
} }
result(input) { result (input) {
// Different cases // Different cases
let info = ''; let info = ''
info += 'Hei! Olen ' + this.config.irc.nick + '!' + '\n'; info += 'Hei! Olen ' + this.config.irc.nick + '!' + '\n'
info += 'Tarjoan yksityisviestien kautta ominaisuuksia!' + '\n'; info += 'Tarjoan yksityisviestien kautta ominaisuuksia!' + '\n'
info += 'Voidaksesi käyttää niitä, sinun on rekisteröidyttävä lähettämällä viesti \".rekisteröi\".'; info += 'Voidaksesi käyttää niitä, sinun on rekisteröidyttävä lähettämällä viesti ".rekisteröi".'
return info; return info
} }
} }
module.exports = Users; module.exports = Users

View File

@ -78,7 +78,7 @@ class Pwm extends BasePlugin {
const $ = cheerio.load(data[0]) const $ = cheerio.load(data[0])
let names = [] let names = []
let names_ = $('.text p').children('a').each(function (i, elem) { $('.text p').children('a').each(function (i, elem) {
names.push($(this).text()) names.push($(this).text())
}) })

View File

@ -1,69 +1,65 @@
var Promise = require('promise'); var Promise = require('promise')
var BasePlugin = require('./base.js'); var BasePlugin = require('./base.js')
var logger = require('winston');
class Twitter extends BasePlugin { class Twitter extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Twitter'; this.name = 'Twitter'
this.config = config; this.config = config
} }
test(input) { test (input) {
// Kernel version // Kernel version
var res = null; if (input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) {
if (res = input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) { return true
return true;
} }
return false; return false
} }
getTweet(statusId) { getTweet (statusId) {
var Twitter = require('twitter'); var Twitter = require('twitter')
var client = new Twitter({ var client = new Twitter({
consumer_key: this.config.keys.twitter.consumerKey, consumer_key: this.config.keys.twitter.consumerKey,
consumer_secret: this.config.keys.twitter.consumerSecret, consumer_secret: this.config.keys.twitter.consumerSecret,
access_token_key: '', access_token_key: '',
access_token_secret: '' access_token_secret: ''
}); })
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
client.get('statuses/show/' + statusId, function(error, tweet, response) { client.get('statuses/show/' + statusId, function (error, tweet, response) {
if(!error) { if (!error) {
var user = tweet.user.screen_name; var user = tweet.user.screen_name
var time = tweet.created_at; var time = tweet.created_at
var dateTime = new Date(time); var dateTime = new Date(time)
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes(); var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes()
var str = '@' + user + ': "' + tweet.text + '" ('+ dateTimeLocale +')'; var str = '@' + user + ': "' + tweet.text + '" (' + dateTimeLocale + ')'
str = str.replace(/(?:\r\n|\r|\n)/g, ' '); str = str.replace(/(?:\r\n|\r|\n)/g, ' ')
resolve(str); resolve(str)
} else { } else {
reject(); reject(new Error())
} }
}); })
})
}); return promise
return promise;
} }
result(input) { result (input) {
var that = this; var that = this
var resultPromise = new Promise(function(resultResolve, resultReject) { var resultPromise = new Promise(function (resolve, reject) {
var res = null; var res = input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)
if (res = input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) { if (res !== null) {
var status = res[6]; var status = res[6]
that.getTweet(status).then(function(tweet) { that.getTweet(status).then(function (tweet) {
resultResolve('Twiitti: ' + tweet); resolve('Twiitti: ' + tweet)
}, function(error) { }, function () {
resultReject('Twiitti: Jokin virhe tapahtui'); reject(new Error('Twiitti: Jokin virhe tapahtui'))
}); })
} else { } else {
resultReject('Twiitti: Jokin virhe tapahtui'); reject(new Error('Twiitti: Jokin virhe tapahtui'))
} }
}); })
return resultPromise; return resultPromise
} }
} }
module.exports = Twitter; module.exports = Twitter

View File

@ -1,14 +1,14 @@
var Promise = require('promise'); var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js'); var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js'); var BasePlugin = require('./base.js')
var logger = require('winston'); const logger = require('../logger')
class Weather extends BasePlugin { class Weather extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Weather'; this.name = 'Weather'
this.apikey = config.keys.owm.apiKey; this.apikey = config.keys.owm.apiKey
this.iconCodeToText = { this.iconCodeToText = {
'01d': 'selkeää', '01d': 'selkeää',
'02d': 'puolipilvistä', '02d': 'puolipilvistä',
@ -28,158 +28,153 @@ class Weather extends BasePlugin {
'11n': 'ukkostaa', '11n': 'ukkostaa',
'13n': 'lumisadetta', '13n': 'lumisadetta',
'50n': 'sumua' '50n': 'sumua'
};
}
test(input) {
var res = null;
if (res = input.match(/^\.saa(.*)/i)) {
return true;
} }
return false;
} }
getTemperature(city, code) { test (input) {
var language = 'fi'; if (input.match(/^\.saa(.*)/i)) {
return true
}
return false
}
getTemperature (city, code) {
var language = 'fi'
var urlArgs = { var urlArgs = {
'q': city, 'q': city,
'lang': language, 'lang': language,
'APPID': this.apikey 'APPID': this.apikey
}; }
var url = 'http://api.openweathermap.org/data/2.5/weather'; var url = 'http://api.openweathermap.org/data/2.5/weather'
var promise = requestPromise(url, urlArgs); var promise = requestPromise(url, urlArgs)
return promise; return promise
} }
getTemperatures(cities, code) { getTemperatures (cities, code) {
logger.info('getting temperatures ', cities, code); logger.info('getting temperatures ', cities, code)
if(typeof code === 'undefined') { if (typeof code === 'undefined') {
code = 'fi'; code = 'fi'
} }
var language = 'fi'; var language = 'fi'
var idList = ''; var idList = ''
for(var city in cities) { for (var city in cities) {
idList += cities[city] + ','; idList += cities[city] + ','
} }
idList = idList.substring(0,idList.length - 1); idList = idList.substring(0, idList.length - 1)
var urlArgs = { var urlArgs = {
'id': idList, 'id': idList,
'lang': language, 'lang': language,
'APPID': this.apikey 'APPID': this.apikey
}; }
var url = 'http://api.openweathermap.org/data/2.5/group'; var url = 'http://api.openweathermap.org/data/2.5/group'
var promise = requestPromise(url, urlArgs); var promise = requestPromise(url, urlArgs)
return promise; return promise
} }
getPenaTemperatures(start, stop, limit) { getPenaTemperatures (start, stop, limit) {
logger.info('getting pena', start, stop, limit); logger.info('getting pena', start, stop, limit)
var d = new Date(); var urlArgs = {}
var urlArgs = {};
if(typeof limit === 'undefined') { if (typeof limit === 'undefined') {
limit = 20; limit = 1
} }
urlArgs.limit = limit; urlArgs.limit = limit
if(typeof start !== 'undefined' && typeof stop !== 'undefined') { if (typeof start !== 'undefined' && typeof stop !== 'undefined') {
urlArgs.limit = limit; urlArgs.limit = limit
urlArgs.start = start; urlArgs.start = start
urlArgs.stop = stop; urlArgs.stop = stop
} }
var url = 'http://masa.dy.fi/api/temperature.php'; var url = 'http://masa.dy.fi/api/temperature.php'
var promise = requestPromise(url, urlArgs); var promise = requestPromise(url, urlArgs)
return promise; return promise
} }
getTemperatureString(owmCityIds) { getTemperatureString (owmCityIds) {
let that = this; let that = this
var promise = new Promise(function(resolve, reject) { var promise = new Promise(function (resolve, reject) {
Promise.all([ Promise.all([
that.getTemperatures(owmCityIds), that.getTemperatures(owmCityIds),
that.getPenaTemperatures() that.getPenaTemperatures()
]).then(function(results) { ]).then(function (results) {
var resultString = ''; var resultString = ''
// OWM // OWM
results[0].list.forEach(function(data) { results[0].list.forEach(function (data) {
var city = data.name; var city = data.name
var temp = (data.main.temp-273.15).toFixed(1); var temp = (data.main.temp - 273.15).toFixed(1)
var code = data.weather[0].icon; var code = data.weather[0].icon
resultString += '' + city + ' ('+temp+' °C, '+that.iconCodeToText[code]+'), '; resultString += '' + city + ' (' + temp + ' °C, ' + that.iconCodeToText[code] + '), '
}); })
if(results[1].length > 0) { if (results[1].length > 0) {
var temp = Number(results[1][0].temp).toFixed(1); var temp = Number(results[1][0].temp).toFixed(1)
resultString += 'Aura (' + temp + ' °C)'; resultString += 'Aura (' + temp + ' °C)'
} }
resolve(resultString); resolve(resultString)
}, (str) => reject(str))
}, (str) => reject(str)); })
}); return promise
return promise;
} }
result(input) { result (input) {
// Different cases // Different cases
let that = this; let that = this
var resultPromise = new Promise(function(resultResolve, resultReject) {
var resultPromise = new Promise(function (resolve, reject) {
if (input.match(/^\.sää$/i) || input.match(/^\.saa$/i)) { if (input.match(/^\.sää$/i) || input.match(/^\.saa$/i)) {
that.getTemperatureString(that.config.owmCityIds).then(function(str) { that.getTemperatureString(that.config.owmCityIds).then(function (str) {
resultResolve('Sää: ' + str); resolve('Sää: ' + str)
}, function(str) { }, function (str) {
resultReject(str) reject(new Error(str))
}); })
} }
var res = null;
// Weather // Weather
if (res = input.match(/^\.s(ää|aa) ([^0-9]+)$/i)) { var res = input.match(/^\.s(ää|aa) ([^0-9]+)$/i)
//console.log('kaupunki', res[1]); if (res !== null) {
that.getTemperature(res[2]).then(function(result) { // console.log('kaupunki', res[1]);
//console.log(result); that.getTemperature(res[2]).then(function (result) {
if(result.cod === '404') { // console.log(result);
//console.log('Eioo: ' + res[1]); if (result.code === '404') {
client.say(to, 'Eioo: ' + res[2]); // console.log('Eioo: ' + res[1]);
// client.say(to, 'Eioo: ' + res[2])
resolve('Eioo: ' + res[2])
} else { } else {
var city = result.name; var city = result.name
var country = result.sys.country; var country = result.sys.country
var temp = (result.main.temp-273.15).toFixed(1); var temp = (result.main.temp - 273.15).toFixed(1)
var code = result.weather[0].icon; var code = result.weather[0].icon
var sunriseDate = new Date(result.sys.sunrise*1000);
var sunsetDate = new Date(result.sys.sunset*1000);
var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes(); // var sunriseDate = new Date(result.sys.sunrise * 1000)
var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes(); // var sunsetDate = new Date(result.sys.sunset * 1000)
// var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes()
// var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes()
var humidity = result.main.humidity; var humidity = result.main.humidity
var pressure = result.main.pressure; var pressure = result.main.pressure
var windspeed = result.wind.speed; var windspeed = result.wind.speed
let str = 'Sää: '+city+', '+country+' ('+temp+' °C, '+ that.iconCodeToText[code] +', ilmankosteus: '+humidity+' %, ilmanpaine: '+pressure+' hPa, tuulen nopeus: '+windspeed+' m/s)'; let str = 'Sää: ' + city + ', ' + country + ' (' + temp + ' °C, ' + that.iconCodeToText[code] + ', ilmankosteus: ' + humidity + ' %, ilmanpaine: ' + pressure + ' hPa, tuulen nopeus: ' + windspeed + ' m/s)'
resultResolve('Sää: ' + str); resolve('Sää: ' + str)
} }
}, function(error) { }, function (error) {
logger.error('ERROR ',error); logger.error('ERROR ', error)
resultResolve('Oho! Tapahtui virhe. Yritä myöhemmin uudelleen...'); resolve('Oho! Tapahtui virhe. Yritä myöhemmin uudelleen...')
}); })
} }
}); })
return resultPromise; return resultPromise
} }
} }
module.exports = Weather; module.exports = Weather

View File

@ -1,66 +1,65 @@
var Promise = require('promise'); var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js'); var BasePlugin = require('./base.js')
var BasePlugin = require('./base.js'); const logger = require('../logger')
var logger = require('winston');
class Youtube extends BasePlugin { class Youtube extends BasePlugin {
constructor(config) { constructor (config) {
super(config); super(config)
this.name = 'Youtube'; this.name = 'Youtube'
this.config = config; this.config = config
} }
test(input) { test (input) {
// Kernel version // Kernel version
var res = null; if (input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+))|(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+)))/i)) {
if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+))|(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+)))/i)) { return true
return true; }
} return false
return false;
} }
getYoutubeResult(id, resolve, reject) { getYoutubeResult (id, resolve, reject) {
if(typeof id !== 'undefined') { if (typeof id !== 'undefined') {
var googleapi = require('./helpers/googleapi.js')(this.config); var googleapi = require('./helpers/googleapi.js')(this.config)
googleapi.getYoutubeVideoById(id).then(function(result) { googleapi.getYoutubeVideoById(id).then(function (result) {
var resultString = 'Youtube: '; var resultString = 'Youtube: '
resultString += result.title; resultString += result.title
resultString += ', esittäjänä ' + result.channelTitle; resultString += ', esittäjänä ' + result.channelTitle
if(typeof result.statistics !== 'undefined') { if (typeof result.statistics !== 'undefined') {
var rotten = (Number(result.statistics.likeCount)/(Number(result.statistics.likeCount)+Number(result.statistics.dislikeCount))).toFixed(2); var rotten = (Number(result.statistics.likeCount) / (Number(result.statistics.likeCount) + Number(result.statistics.dislikeCount))).toFixed(2)
resultString += ' ('+result.duration+', '+ result.statistics.viewCount +' katselukertaa, '+rotten*100+'% tykätty, '+result.url+' )'; resultString += ' (' + result.duration + ', ' + result.statistics.viewCount + ' katselukertaa, ' + rotten * 100 + '% tykätty, ' + result.url + ' )'
} }
resolve(resultString); resolve(resultString)
}, function(err) { }, function (err) {
logger.info('Error', err); logger.info('Error', err)
reject('Youtube: jokin meni pieleen...'); reject('Youtube: jokin meni pieleen...')
}); })
} else { } else {
reject('Youtube: jokin meni pahasti pieleen...'); reject('Youtube: jokin meni pahasti pieleen...')
} }
} }
result(input) { result (input) {
var that = this; var that = this
var resultPromise = new Promise(function(resultResolve, resultReject) { var resultPromise = new Promise(function (resolve, reject) {
var res = null; var res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+)))/i)
if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+)))/i)) { if (res !== null) {
var id = res[1]; var id = res[1]
that.getYoutubeResult(id, resultResolve, resultReject); that.getYoutubeResult(id, resolve, reject)
} else if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+))/i)) { } else {
var id = res[1]; res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+))/i)
that.getYoutubeResult(id, resultResolve, resultReject); if (res !== null) {
} else { that.getYoutubeResult(res[1], resolve, reject)
resultReject('Youtube: jokin meni pieleen (ei osunut)...'); } else {
} reject(new Error('Youtube: jokin meni pieleen (ei osunut)...'))
}); }
}
})
return resultPromise; return resultPromise
} }
} }
module.exports = Youtube; module.exports = Youtube