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
const irc = require('irc');
const fs = require('fs');
const winston = require('winston');
require('winston-daily-rotate-file');
const path = require('path');
const irc = require('irc')
const path = require('path')
// Load config
const config = require('./config');
const cron = require('node-cron');
const config = require('./config')
const cron = require('node-cron')
// Load new plugins
const PluginManager = require('./plugins/pluginManager.js');
const pluginManager = new PluginManager(config);
pluginManager.loadAllPlugins();
const PluginManager = require('./plugins/pluginManager.js')
const pluginManager = new PluginManager(config)
pluginManager.loadAllPlugins()
// Configure logger
// create a write stream (in append mode)
const logDirectory = __dirname + '/log';
// ensure log directory exists
if(!fs.existsSync(logDirectory)) {
fs.mkdirSync(logDirectory);
const logger = require('./logger')
if (!config.irc.connect) {
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
var client = new irc.Client(config.irc.server, config.irc.nick, {
debug: false,
channels: config.irc.channels,
//floodProtection: true,
//sasl: true,
millisecondsOfSilenceBeforePingSent: 60000,
});
// floodProtection: true,
// sasl: true,
millisecondsOfSilenceBeforePingSent: 60000
})
var handleMessage = function (from, to, message) {
logger.info(from + ' => ' + to + ': ' + message)
var handleMessage = function(from, to, message) {
logger.info(from + ' => ' + to + ': ' + message);
pluginManager.testPlugins(message).then(function(results) {
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) {
logger.error('Plugin error: ', error);
});
var res = null;
}, function (error) {
logger.error('Plugin error: ', error)
})
// Op
if (message.match(/^\.op$/i)) {
client.send('NAMES', to);
client.send('NAMES', to)
}
// reload config
if (message.match(/^\.paivita$/i)) {
// Using require for config files is dangerous
// Rewrite this in the future
var filename = path.resolve('./config.js');
delete require.cache[filename];
config = require('./config');
client.say(to, 'Ladattiin asetustiedosto. ' + Object.keys(config.members).length + ' käyttäjäasetusta. Päivitetään operaattorioikeuksia...');
client.send('NAMES', to);
var filename = path.resolve('./config.js')
delete require.cache[filename]
var config = require('./config')
client.say(to, 'Ladattiin asetustiedosto. ' + Object.keys(config.members).length + ' käyttäjäasetusta. Päivitetään operaattorioikeuksia...')
client.send('NAMES', to)
}
};
}
client.addListener('message', function (from, to, message) {
if(String(from) !== String(config.irc.nick)) {
handleMessage(from, to, message);
if (String(from) !== String(config.irc.nick)) {
handleMessage(from, to, message)
}
});
})
client.addListener('pm', function (from, message) {
if(String(from) !== String(config.irc.nick)) {
handleMessage(from, from, message);
if (String(from) !== String(config.irc.nick)) {
handleMessage(from, from, message)
}
});
})
client.addListener('join', function(channel, who) {
client.whois(who, function(result) {
console.log(result);
client.addListener('join', function (channel, who) {
client.whois(who, function (result) {
console.log(result)
var members = config.members;
for(var memberNick in members) {
var member = members[memberNick];
var members = config.members
for (var memberNick in members) {
var member = members[memberNick]
if(typeof result.host !== 'undefined' && typeof result.user !== 'undefined') {
if(result.host.match(member.host) && result.user.match(member.user)) {
client.send('MODE', channel, '+o', result.nick);
}
if (typeof result.host !== 'undefined' && typeof result.user !== 'undefined') {
if (result.host.match(member.host) && result.user.match(member.user)) {
client.send('MODE', channel, '+o', result.nick)
}
}
}
})
})
});
});
client.addListener('error', function (message) {
console.log('error: ', message)
})
client.addListener('error', function(message) {
console.log('error: ', message);
});
client.addListener('names', function(channel, nicks) {
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
for(var nick in nicks) {
if(nicks[nick] !== '@') {
client.whois(nick, function(result) {
var members = config.members;
for(var memberNick in members) {
var member = members[memberNick];
for (var nick in nicks) {
if (nicks[nick] !== '@') {
client.whois(nick, function (result) {
var members = config.members
for (var memberNick in members) {
var member = members[memberNick]
if(result.host.match(member.host) && result.user.match(member.user)) {
client.send('MODE', channel, '+o', result.nick);
if (result.host.match(member.host) && result.user.match(member.user)) {
client.send('MODE', channel, '+o', result.nick)
}
}
});
})
}
}
}
});
})
for (let i = 0; i < config.cron.length; i++) {
let row = config.cron[i]
let that = this;
cron.schedule(row.cron, () => {
if (client.conn !== null) {
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
function prompt(question, callback) {
var stdin = process.stdin,
stdout = process.stdout;
function prompt (question, callback) {
var stdin = process.stdin
var stdout = process.stdout
stdin.resume();
stdout.write(question);
stdin.resume()
stdout.write(question)
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
const config = require('./config');
const config = require('./config')
// Load new plugins
const PluginManager = require('./plugins/pluginManager.js');
const pluginManager = new PluginManager(config);
pluginManager.loadAllPlugins();
const PluginManager = require('./plugins/pluginManager.js')
const pluginManager = new PluginManager(config)
pluginManager.loadAllPlugins()
// Configure logger
// create a write stream (in append mode)
const logDirectory = __dirname + '/log';
// ensure log directory exists
if(!fs.existsSync(logDirectory)) {
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 logger = require('./logger')
const isPm = false
function query() {
function query () {
prompt('> ', function (message) {
if(!isPm) {
pluginManager.testPlugins(message).then(function(results) {
for(var i = 0; i < results.length; i++) {
console.log(results[i]);
if (!isPm) {
pluginManager.testPlugins(message).then(function (results) {
for (var i = 0; i < results.length; i++) {
console.log(results[i])
}
query()
}, function(error) {
logger.error('Plugin error: ', error);
});
}, function (error) {
logger.error('Plugin error: ', error)
query()
})
} else {
// PM
pluginManager.testPlugins(message, false).then(function(results) {
for(var i = 0; i < results.length; i++) {
console.log(results[i]);
pluginManager.testPlugins(message, false).then(function (results) {
for (var i = 0; i < results.length; i++) {
console.log(results[i])
}
query()
}, function(error) {
logger.error('Plugin error: ', error);
});
}, function (error) {
logger.error('Plugin error: ', error)
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"
},
"dependencies": {
"chance": "=1.0.13",
"chance": "=1.0.18",
"cheerio": "^1.0.0-rc.2",
"cron": "=1.3.0",
"file-stream-rotator": "=0.2.1",
"finalhandler": "=1.1.1",
"googleapis": "=34.0.0",
"html-to-text": "=4.0.0",
"cron": "=1.7.1",
"file-stream-rotator": "=0.4.1",
"finalhandler": "=1.1.2",
"googleapis": "=42.0.0",
"html-to-text": "=5.1.1",
"irc": "=0.5.2",
"lokijs": "=1.5.3",
"lokijs": "=1.5.7",
"mkdirp": "=0.5.1",
"morgan": "=1.9.0",
"morgan": "=1.9.1",
"node-cron": "^2.0.3",
"node-dev": "=3.1.3",
"node-dev": "=4.0.0",
"node-uuid": "=1.4.8",
"promise": "=8.0.1",
"request": "=2.85.0",
"request-promise": "=4.2.2",
"promise": "=8.0.3",
"request": "=2.88.0",
"request-promise": "=4.2.4",
"twitter": "=1.7.1",
"winston": "=2.4.2",
"winston-daily-rotate-file": "=3.1.2"
"winston": "=3.2.1",
"winston-daily-rotate-file": "^3.10.0"
},
"devDependencies": {
"nodemon": "^1.18.5"

View File

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

View File

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

View File

@ -1,33 +1,29 @@
var Promise = require('promise');
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var BasePlugin = require('./base.js')
var Chance = require('chance');
var chance = new Chance();
var Chance = require('chance')
var chance = new Chance()
class Character {
constructor() {
this.gender = null;
this.name = null;
this.class = null;
this.alignment = null;
this.stats = [];
this.statSum = -1;
constructor () {
this.gender = null
this.name = null
this.class = null
this.alignment = null
this.stats = []
this.statSum = -1
}
create() {
this.gender = chance.gender();
this.name = chance.first({gender: this.gender});
create () {
this.gender = chance.gender()
this.name = chance.first({gender: this.gender})
// Throw stats
for(var i = 0; i < 6; i++) {
var throws = [chance.d6(), chance.d6(), chance.d6(), chance.d6()].sort();
throws.splice(0, 1);
var stat = throws.reduce(function(a, b) { return a + b; }, 0);
this.stats.push(stat);
for (var i = 0; i < 6; i++) {
var throws = [chance.d6(), chance.d6(), chance.d6(), chance.d6()].sort()
throws.splice(0, 1)
var stat = throws.reduce(function (a, b) { return a + b }, 0)
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
var races = {
@ -37,20 +33,20 @@ class Character {
'Gnome': 'Bard',
'Half-Elf': '',
'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
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 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)
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
var classes = {
'Barbarian' : '',
'Barbarian': '',
'Bard': '',
'Cleric': '',
'Druid': '',
@ -59,72 +55,74 @@ class Character {
'Paladin': '',
'Ranger': '',
'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
var roll = function(times, func) {
var sum = 0;
for(var i = 0; i < times; i++) {
sum += chance[func]();
var roll = function (times, func) {
var sum = 0
for (var i = 0; i < times; i++) {
sum += chance[func]()
}
return sum;
return sum
}
var ages = {
'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')] },
'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')] },
'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')] },
'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 = {
'Barbarian': 0, 'Rogue': 0, 'Sorcerer': 0,
'Bard': 1, 'Fighter': 1, '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]];
'Barbarian': 0,
'Rogue': 0,
'Sorcerer': 0,
'Bard': 1,
'Fighter': 1,
'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() {
var str = this.age + " years old " + this.alignment + " " + this.gender + " " + this.race + " " + this.class + " named " + this.name;
str += " with stats ";
this.stats.forEach(function(val) {
str += val + " ";
});
str += " ("+this.statSum+")";
return str;
toString () {
var str = this.age + ' years old ' + this.alignment + ' ' + this.gender + ' ' + this.race + ' ' + this.class + ' named ' + this.name
str += ' with stats '
this.stats.forEach(function (val) {
str += val + ' '
})
str += ' (' + this.statSum + ')'
return str
}
}
class Character2 extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Character2';
constructor (config) {
super(config)
this.name = 'Character2'
}
test(input) {
var res = null;
if (res = input.match(/^\.luohahmo2$/i)) {
return true;
test (input) {
if (input.match(/^\.luohahmo2$/i)) {
return true
}
return false;
return false
}
result(input) {
result (input) {
// Different cases
let newChar = new Character();
newChar.create();
let result = newChar.toString();
return result;
let newChar = new Character()
newChar.create()
let result = newChar.toString()
return result
}
}
module.exports = Character2;
module.exports = Character2

View File

@ -1,68 +1,63 @@
var Promise = require('promise');
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var BasePlugin = require('./base.js')
class Dice extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Dice';
constructor (config) {
super(config)
this.name = 'Dice'
}
test(input) {
var res = null;
if (res = input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)) {
return true;
}
if (res = input.match(/^\.heit(a|ä) voltti homo$/i)) {
test (input) {
if (input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)) {
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;
var totalThrows = [];
numThrows = Number(numThrows)
sides = Number(sides)
numThrows = Number(numThrows);
sides = Number(sides);
if(numThrows === 0 || sides === 0) {
return 'Tyhjää ei voi heittää';
if (numThrows === 0 || sides === 0) {
return 'Tyhjää ei voi heittää'
}
if(numThrows > 100) {
return 'Ei jaksa...';
if (numThrows > 100) {
return 'Ei jaksa...'
}
for(var a = 0; a < numThrows; a++) {
var t = Math.floor(Math.random()*sides)+1;
totalThrows.push(t);
total += t;
for (var a = 0; a < numThrows; a++) {
var t = Math.floor(Math.random() * sides) + 1
totalThrows.push(t)
total += t
}
var resultString = '';
totalThrows.forEach(function(value) {
resultString += value + ', ';
});
var resultString = ''
totalThrows.forEach(function (value) {
resultString += value + ', '
})
resultString = resultString.substring(0, resultString.length - 2);
resultString += ' (yhteensä: ' + total + '. '+ (total/numThrows).toFixed(2) + ' per heitto)';
resultString = resultString.substring(0, resultString.length - 2)
resultString += ' (yhteensä: ' + total + '. ' + (total / numThrows).toFixed(2) + ' per heitto)'
return resultString;
return resultString
}
result(input) {
result (input) {
// Different cases
let res = null
if (res = input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)) {
var th = this.getDiceString(res[2], res[3]);
return 'Heitettiin: '+th;
res = input.match(/^\.heit(a|ä) ([0-9]+)d([0-9]+)( ([ \w])*)*$/i)
if (res !== null) {
var th = this.getDiceString(res[2], res[3])
return 'Heitettiin: ' + th
}
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 DDG = require('node-ddg-api').DDG;
var Promise = require('promise')
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) {
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;
}
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL
resolve(str)
} else if (response.RelatedTopics.length > 0) {
str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL
resolve(str)
} else {
reject(new Error(''))
}
} else {
reject(new Error(''))
}
})
})
return promise
}
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL;
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;
};
return getAnswer
}

View File

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

View File

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

View File

@ -1,34 +1,34 @@
var request = require('request');
var Promise = require('promise');
var request = require('request')
var Promise = require('promise')
function RequestPromise(url, urlArgs, headers, json) {
if(typeof headers === 'undefined') {
headers = {};
function RequestPromise (url, urlArgs, headers, json) {
if (typeof headers === 'undefined') {
headers = {}
}
if(typeof json === 'undefined') {
json = false;
if (typeof json === 'undefined') {
json = false
}
var promise = new Promise(function(resolve, reject) {
var promise = new Promise(function (resolve, reject) {
request({
url: url,
qs: urlArgs,
headers: headers,
json: json
}, function(error, response, body) {
if(!error && response.statusCode == 200) {
if (json === false) {
resolve(JSON.parse(body)); /// wtf
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
if (json === false) {
resolve(JSON.parse(body)) /// wtf
} else {
resolve(body)
}
} 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 requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
class InstantAswer extends BasePlugin {
constructor(config) {
super(config);
this.name = 'InstantAswer';
constructor (config) {
super(config)
this.name = 'InstantAswer'
}
test(input) {
var res = null;
if (res = input.match(/^\.wtf (.+)$/i)) {
return true;
test (input) {
if (input.match(/^\.wtf (.+)$/i)) {
return true
}
return false;
return false
}
getDDG(query) {
getDDG (query) {
var urlArgs = {
q: query,
kp: -1,
skip_disambig: '0',
format: 'json'
};
}
let url = 'https://api.duckduckgo.com/';
var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json',
});
let url = 'https://api.duckduckgo.com/'
var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json'
})
return promise;
return promise
}
getAnswer(query) {
let that = this;
var promise = new Promise(function(resolve, reject) {
getAnswer (query) {
let that = this
var promise = new Promise(function (resolve, reject) {
that.getDDG(query).then((response) => {
var str = '';
if(response.AbstractText !== '') {
var text = '';
if(response.AbstractText.length > 350) {
text = response.AbstractText.substring(0, 350-response.AbstractURL.length) + '...';
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;
text = response.AbstractText
}
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL;
resolve(str);
}
else if(response.RelatedTopics.length > 0) {
str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL;
resolve(str);
str = 'Vastaus: ' + text + '" | ' + response.AbstractURL
resolve(str)
} else if (response.RelatedTopics.length > 0) {
str = 'Vastaus: "' + response.RelatedTopics[0].Text + '" | ' + response.RelatedTopics[0].FirstURL
resolve(str)
} else {
reject();
reject(new Error())
}
}, reject);
});
return promise;
}, reject)
})
return promise
}
result(input) {
let that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
var res = null;
if (res = input.match(/^\.wtf (.+)$/i)) {
result (input) {
let that = this
var resultPromise = new Promise(function (resolve, reject) {
var res = input.match(/^\.wtf (.+)$/i)
if (res !== null) {
let query = res[1]
that.getAnswer(query).then(str => {
resultResolve(str);
resolve(str)
})
} 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 requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
class Joke extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Joke';
constructor (config) {
super(config)
this.name = 'Joke'
}
test(input) {
var res = null;
if (res = input.match(/^\.vitsi$/i)) {
return true;
test (input) {
if (input.match(/^\.vitsi$/i)) {
return true
}
return false;
return false
}
getJoke () {
var urlArgs = {}
var url = 'https://icanhazdadjoke.com/'
getJoke() {
var urlArgs = {};
var url = 'https://icanhazdadjoke.com/';
var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json'
})
var promise = requestPromise(url, urlArgs, {
'Accept': 'application/json',
});
return promise;
return promise
}
result(input) {
var that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
var res = null;
if (res = input.match(/^\.vitsi$/i)) {
that.getJoke().then(function(data) {
var text = 'Vitsi: ';
result (input) {
var that = this
var resultPromise = new Promise(function (resolve, reject) {
if (input.match(/^\.vitsi$/i)) {
that.getJoke().then(function (data) {
var text = 'Vitsi: '
var joke = data.joke;
if(typeof joke === 'undefined' || joke === null) {
resultReject('No joke!');
var joke = data.joke
if (typeof joke === 'undefined' || joke === null) {
reject(new Error('No joke!'))
}
text += "\"" + joke + "\"";
text += '"' + joke + '"'
resultResolve(text);
}, function(error) {
resultReject(error);
});
resolve(text)
}, function (error) {
reject(error)
})
}
});
})
return resultPromise;
return resultPromise
}
}
module.exports = Joke;
module.exports = Joke

View File

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

View File

@ -1,85 +1,83 @@
var Promise = require('promise');
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var htmlToText = require('html-to-text');
var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
var htmlToText = require('html-to-text')
class Mastodon extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Mastodon';
constructor (config) {
super(config)
this.name = 'Mastodon'
}
test(input) {
var res = null;
if (res = input.match(/http(s)?:\/\/(www\.)?((.*\..*\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) {
return true;
test (input) {
if (input.match(/http(s)?:\/\/(www\.)?((.*\..*\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) {
return true
}
if (res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) {
return true;
if (input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) {
return true
}
return false;
return false
}
getToot(host, statusId) {
var promise = new Promise(function(resolve, reject) {
var url = 'https://' + host + '/api/v1/statuses/' + statusId;
getToot (host, statusId) {
var promise = new Promise(function (resolve, reject) {
var url = 'https://' + host + '/api/v1/statuses/' + statusId
requestPromise(url, {}, {
'Accept': 'application/json',
}).then(function(toot) {
if(!toot.error) {
var user = toot.account.username;
var time = toot.created_at;
var dateTime = new Date(time);
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes();
'Accept': 'application/json'
}).then(function (toot) {
if (!toot.error) {
var user = toot.account.username
var time = toot.created_at
var dateTime = new Date(time)
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes()
var tootContent = toot.content;
var tootContent = htmlToText.fromString(tootContent, {
var tootContent = toot.content
tootContent = htmlToText.fromString(tootContent, {
wordwrap: false,
ignoreHref: true,
preserveNewlines: false,
});
preserveNewlines: false
})
var str = '@' + user + ': "' + tootContent + '" ('+ dateTimeLocale +')';
str = str.replace(/(?:\r\n|\r|\n)/g, ' ');
var str = '@' + user + ': "' + tootContent + '" (' + dateTimeLocale + ')'
str = str.replace(/(?:\r\n|\r|\n)/g, ' ')
resolve(str);
resolve(str)
} else {
reject();
reject(new Error(''))
}
});
});
return promise;
})
})
return promise
}
result(input) {
var that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
var host = null;
var tootId = null;
result (input) {
var that = this
var resultPromise = new Promise(function (resolve, reject) {
var host = null
var tootId = null
var res = null;
if (res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) {
host = res[5];
tootId = res[7];
var res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)
if (res !== null) {
host = res[5]
tootId = res[7]
}
if (res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) {
host = res[5];
tootId = res[7];
res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)
if (res !== null) {
host = res[5]
tootId = res[7]
}
if (host !== null && tootId !== null) {
that.getToot(host, tootId).then(function(toot) {
resultResolve('Tuuttaus: ' + toot);
}, function(error) {
resultReject('Tuuttaus: Jokin virhe tapahtui');
});
that.getToot(host, tootId).then(function (toot) {
resolve('Tuuttaus: ' + toot)
}, function () {
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 Promise = require('promise');
var fs = require('fs')
var Promise = require('promise')
const logger = require('../logger')
class PluginManager {
constructor(config) {
this.enabledPlugins = [];
this.enabledPmPlugins = [];
this.plugins = [];
this.pmPlugins = [];
this.config = config;
constructor (config) {
this.enabledPlugins = []
this.enabledPmPlugins = []
this.plugins = []
this.pmPlugins = []
this.config = config
var that = this;
var that = this
config.plugins.forEach(function(pluginName) {
logger.info('checking ' + pluginName + '...');
config.plugins.forEach(function (pluginName) {
logger.info('checking ' + pluginName + '...')
if(fs.existsSync('./plugins/'+pluginName.toLowerCase()+'.js')) {
logger.info('* Exists. Enabling...');
that.enabledPlugins.push(pluginName.toLowerCase());
if (fs.existsSync('./plugins/' + pluginName.toLowerCase() + '.js')) {
logger.info('* Exists. Enabling...')
that.enabledPlugins.push(pluginName.toLowerCase())
}
if(fs.existsSync('./plugins/pm'+pluginName.toLowerCase()+'.js')) {
logger.info('* Exists as PM plugin. Enabling...');
that.enabledPmPlugins.push(pluginName.toLowerCase());
if (fs.existsSync('./plugins/pm' + pluginName.toLowerCase() + '.js')) {
logger.info('* Exists as PM plugin. Enabling...')
that.enabledPmPlugins.push(pluginName.toLowerCase())
}
});
})
}
loadAllPlugins() {
var that = this;
this.enabledPlugins.forEach(function(pluginName) {
var Plugin = require('./' + pluginName + '.js');
loadAllPlugins () {
var that = this
this.enabledPlugins.forEach(function (pluginName) {
var Plugin = require('./' + pluginName + '.js')
var plugin = new Plugin(that.config);
that.plugins.push(plugin);
});
var plugin = new Plugin(that.config)
that.plugins.push(plugin)
})
this.enabledPmPlugins.forEach(function(pluginName) {
var Plugin = require('./pm' + pluginName + '.js');
this.enabledPmPlugins.forEach(function (pluginName) {
var Plugin = require('./pm' + pluginName + '.js')
var plugin = new Plugin(that.config);
that.pmPlugins.push(plugin);
});
var plugin = new Plugin(that.config)
that.pmPlugins.push(plugin)
})
}
testPlugins(input, publicChat) {
testPlugins (input, publicChat) {
if (typeof publicChat === 'undefined') {
publicChat = true
}
var promises = [];
var promises = []
if (publicChat) {
for(let i = 0; i < this.plugins.length; i++) {
var plugin = this.plugins[i];
if(plugin.test(input)) {
logger.info('* Plugin ' + plugin.name + ' reported hit');
promises.push(plugin.result(input));
for (let i = 0; i < this.plugins.length; i++) {
let plugin = this.plugins[i]
if (plugin.test(input)) {
logger.info('* Plugin ' + plugin.name + ' reported hit')
promises.push(plugin.result(input))
}
}
} else {
for(let i = 0; i < this.pmPlugins.length; i++) {
var plugin = this.pmPlugins[i];
for (let i = 0; i < this.pmPlugins.length; i++) {
let plugin = this.pmPlugins[i]
if(plugin.test(input)) {
logger.info('* Plugin ' + plugin.name + ' reported hit');
promises.push(plugin.result(input));
if (plugin.test(input)) {
logger.info('* Plugin ' + plugin.name + ' reported hit')
promises.push(plugin.result(input))
}
}
}
return Promise.all(promises);
return Promise.all(promises)
}
}
// export default BasePlugin;
module.exports = PluginManager;
module.exports = PluginManager

View File

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

View File

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

View File

@ -1,69 +1,65 @@
var Promise = require('promise');
var BasePlugin = require('./base.js');
var logger = require('winston');
var Promise = require('promise')
var BasePlugin = require('./base.js')
class Twitter extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Twitter';
this.config = config;
constructor (config) {
super(config)
this.name = 'Twitter'
this.config = config
}
test(input) {
test (input) {
// Kernel version
var res = null;
if (res = input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) {
return true;
if (input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) {
return true
}
return false;
return false
}
getTweet(statusId) {
var Twitter = require('twitter');
getTweet (statusId) {
var Twitter = require('twitter')
var client = new Twitter({
consumer_key: this.config.keys.twitter.consumerKey,
consumer_secret: this.config.keys.twitter.consumerSecret,
access_token_key: '',
access_token_secret: ''
});
var promise = new Promise(function(resolve, reject) {
client.get('statuses/show/' + statusId, function(error, tweet, response) {
if(!error) {
var user = tweet.user.screen_name;
var time = tweet.created_at;
var dateTime = new Date(time);
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes();
var str = '@' + user + ': "' + tweet.text + '" ('+ dateTimeLocale +')';
str = str.replace(/(?:\r\n|\r|\n)/g, ' ');
})
var promise = new Promise(function (resolve, reject) {
client.get('statuses/show/' + statusId, function (error, tweet, response) {
if (!error) {
var user = tweet.user.screen_name
var time = tweet.created_at
var dateTime = new Date(time)
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes()
var str = '@' + user + ': "' + tweet.text + '" (' + dateTimeLocale + ')'
str = str.replace(/(?:\r\n|\r|\n)/g, ' ')
resolve(str);
resolve(str)
} else {
reject();
reject(new Error())
}
});
});
return promise;
})
})
return promise
}
result(input) {
var that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
var res = null;
if (res = input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) {
var status = res[6];
that.getTweet(status).then(function(tweet) {
resultResolve('Twiitti: ' + tweet);
}, function(error) {
resultReject('Twiitti: Jokin virhe tapahtui');
});
result (input) {
var that = this
var resultPromise = new Promise(function (resolve, reject) {
var res = input.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)
if (res !== null) {
var status = res[6]
that.getTweet(status).then(function (tweet) {
resolve('Twiitti: ' + tweet)
}, function () {
reject(new Error('Twiitti: Jokin virhe tapahtui'))
})
} 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 requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
const logger = require('../logger')
class Weather extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Weather';
constructor (config) {
super(config)
this.name = 'Weather'
this.apikey = config.keys.owm.apiKey;
this.apikey = config.keys.owm.apiKey
this.iconCodeToText = {
'01d': 'selkeää',
'02d': 'puolipilvistä',
@ -28,158 +28,153 @@ class Weather extends BasePlugin {
'11n': 'ukkostaa',
'13n': 'lumisadetta',
'50n': 'sumua'
};
}
test(input) {
var res = null;
if (res = input.match(/^\.saa(.*)/i)) {
return true;
}
return false;
}
getTemperature(city, code) {
var language = 'fi';
test (input) {
if (input.match(/^\.saa(.*)/i)) {
return true
}
return false
}
getTemperature (city, code) {
var language = 'fi'
var urlArgs = {
'q': city,
'lang': language,
'APPID': this.apikey
};
var url = 'http://api.openweathermap.org/data/2.5/weather';
var promise = requestPromise(url, urlArgs);
}
var url = 'http://api.openweathermap.org/data/2.5/weather'
var promise = requestPromise(url, urlArgs)
return promise;
return promise
}
getTemperatures(cities, code) {
logger.info('getting temperatures ', cities, code);
if(typeof code === 'undefined') {
code = 'fi';
getTemperatures (cities, code) {
logger.info('getting temperatures ', cities, code)
if (typeof code === 'undefined') {
code = 'fi'
}
var language = 'fi';
var language = 'fi'
var idList = '';
for(var city in cities) {
idList += cities[city] + ',';
var idList = ''
for (var city in cities) {
idList += cities[city] + ','
}
idList = idList.substring(0,idList.length - 1);
idList = idList.substring(0, idList.length - 1)
var urlArgs = {
'id': idList,
'lang': language,
'APPID': this.apikey
};
var url = 'http://api.openweathermap.org/data/2.5/group';
var promise = requestPromise(url, urlArgs);
}
var url = 'http://api.openweathermap.org/data/2.5/group'
var promise = requestPromise(url, urlArgs)
return promise;
return promise
}
getPenaTemperatures(start, stop, limit) {
logger.info('getting pena', start, stop, limit);
var d = new Date();
var urlArgs = {};
getPenaTemperatures (start, stop, limit) {
logger.info('getting pena', start, stop, limit)
var urlArgs = {}
if(typeof limit === 'undefined') {
limit = 20;
if (typeof limit === 'undefined') {
limit = 1
}
urlArgs.limit = limit;
urlArgs.limit = limit
if(typeof start !== 'undefined' && typeof stop !== 'undefined') {
urlArgs.limit = limit;
urlArgs.start = start;
urlArgs.stop = stop;
if (typeof start !== 'undefined' && typeof stop !== 'undefined') {
urlArgs.limit = limit
urlArgs.start = start
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) {
let that = this;
var promise = new Promise(function(resolve, reject) {
getTemperatureString (owmCityIds) {
let that = this
var promise = new Promise(function (resolve, reject) {
Promise.all([
that.getTemperatures(owmCityIds),
that.getPenaTemperatures()
]).then(function(results) {
var resultString = '';
]).then(function (results) {
var resultString = ''
// OWM
results[0].list.forEach(function(data) {
var city = data.name;
var temp = (data.main.temp-273.15).toFixed(1);
var code = data.weather[0].icon;
results[0].list.forEach(function (data) {
var city = data.name
var temp = (data.main.temp - 273.15).toFixed(1)
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) {
var temp = Number(results[1][0].temp).toFixed(1);
resultString += 'Aura (' + temp + ' °C)';
if (results[1].length > 0) {
var temp = Number(results[1][0].temp).toFixed(1)
resultString += 'Aura (' + temp + ' °C)'
}
resolve(resultString);
}, (str) => reject(str));
});
return promise;
resolve(resultString)
}, (str) => reject(str))
})
return promise
}
result(input) {
result (input) {
// Different cases
let that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
let that = this
var resultPromise = new Promise(function (resolve, reject) {
if (input.match(/^\.sää$/i) || input.match(/^\.saa$/i)) {
that.getTemperatureString(that.config.owmCityIds).then(function(str) {
resultResolve('Sää: ' + str);
}, function(str) {
resultReject(str)
});
that.getTemperatureString(that.config.owmCityIds).then(function (str) {
resolve('Sää: ' + str)
}, function (str) {
reject(new Error(str))
})
}
var res = null;
// Weather
if (res = input.match(/^\.s(ää|aa) ([^0-9]+)$/i)) {
//console.log('kaupunki', res[1]);
that.getTemperature(res[2]).then(function(result) {
//console.log(result);
if(result.cod === '404') {
//console.log('Eioo: ' + res[1]);
client.say(to, 'Eioo: ' + res[2]);
var res = input.match(/^\.s(ää|aa) ([^0-9]+)$/i)
if (res !== null) {
// console.log('kaupunki', res[1]);
that.getTemperature(res[2]).then(function (result) {
// console.log(result);
if (result.code === '404') {
// console.log('Eioo: ' + res[1]);
// client.say(to, 'Eioo: ' + res[2])
resolve('Eioo: ' + res[2])
} else {
var city = result.name;
var country = result.sys.country;
var temp = (result.main.temp-273.15).toFixed(1);
var code = result.weather[0].icon;
var sunriseDate = new Date(result.sys.sunrise*1000);
var sunsetDate = new Date(result.sys.sunset*1000);
var city = result.name
var country = result.sys.country
var temp = (result.main.temp - 273.15).toFixed(1)
var code = result.weather[0].icon
var sunrise = sunriseDate.getHours() + '.' + sunriseDate.getMinutes();
var sunset = sunsetDate.getHours() + '.' + sunsetDate.getMinutes();
// var sunriseDate = new Date(result.sys.sunrise * 1000)
// 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 pressure = result.main.pressure;
var humidity = result.main.humidity
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)';
resultResolve('Sää: ' + str);
let str = 'Sää: ' + city + ', ' + country + ' (' + temp + ' °C, ' + that.iconCodeToText[code] + ', ilmankosteus: ' + humidity + ' %, ilmanpaine: ' + pressure + ' hPa, tuulen nopeus: ' + windspeed + ' m/s)'
resolve('Sää: ' + str)
}
}, function(error) {
logger.error('ERROR ',error);
resultResolve('Oho! Tapahtui virhe. Yritä myöhemmin uudelleen...');
});
}, function (error) {
logger.error('ERROR ', error)
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 requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
var Promise = require('promise')
var BasePlugin = require('./base.js')
const logger = require('../logger')
class Youtube extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Youtube';
this.config = config;
constructor (config) {
super(config)
this.name = 'Youtube'
this.config = config
}
test(input) {
// Kernel version
var res = null;
if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+))|(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+)))/i)) {
return true;
}
return false;
test (input) {
// Kernel version
if (input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+))|(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+)))/i)) {
return true
}
return false
}
getYoutubeResult(id, resolve, reject) {
if(typeof id !== 'undefined') {
var googleapi = require('./helpers/googleapi.js')(this.config);
googleapi.getYoutubeVideoById(id).then(function(result) {
var resultString = 'Youtube: ';
resultString += result.title;
resultString += ', esittäjänä ' + result.channelTitle;
if(typeof result.statistics !== 'undefined') {
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+' )';
getYoutubeResult (id, resolve, reject) {
if (typeof id !== 'undefined') {
var googleapi = require('./helpers/googleapi.js')(this.config)
googleapi.getYoutubeVideoById(id).then(function (result) {
var resultString = 'Youtube: '
resultString += result.title
resultString += ', esittäjänä ' + result.channelTitle
if (typeof result.statistics !== 'undefined') {
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 + ' )'
}
resolve(resultString);
}, function(err) {
logger.info('Error', err);
reject('Youtube: jokin meni pieleen...');
});
} else {
reject('Youtube: jokin meni pahasti pieleen...');
}
resolve(resultString)
}, function (err) {
logger.info('Error', err)
reject('Youtube: jokin meni pieleen...')
})
} else {
reject('Youtube: jokin meni pahasti pieleen...')
}
}
result(input) {
var that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
var res = null;
result (input) {
var that = this
var resultPromise = new Promise(function (resolve, reject) {
var res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+)))/i)
if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+)))/i)) {
var id = res[1];
if (res !== null) {
var id = res[1]
that.getYoutubeResult(id, resultResolve, resultReject);
} else if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+))/i)) {
var id = res[1];
that.getYoutubeResult(id, resolve, reject)
} else {
res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtube\.com\/watch\?(?:[\w=#-]+&)*v=)([\w-]+))/i)
that.getYoutubeResult(id, resultResolve, resultReject);
} else {
resultReject('Youtube: jokin meni pieleen (ei osunut)...');
}
});
if (res !== null) {
that.getYoutubeResult(res[1], resolve, reject)
} else {
reject(new Error('Youtube: jokin meni pieleen (ei osunut)...'))
}
}
})
return resultPromise;
return resultPromise
}
}
module.exports = Youtube;
module.exports = Youtube