Converted twitter and youtube to the new plugin arch

This commit is contained in:
lanxu 2017-03-17 21:09:39 +02:00
parent be504d8dd4
commit 57c8220044
5 changed files with 140 additions and 117 deletions

65
app.js
View File

@ -34,16 +34,13 @@ var PluginManager = require('./plugins/pluginManager.js');
var pluginManager = new PluginManager(config);
pluginManager.loadAllPlugins();
// Load plugins
var googletin = require('./googleapi.js')(config);
var owmapi = require('./owmapi')(config);
var getTemperatureString = require('./plugins/getWeather')(config);
var getDnDCharacter = require('./plugins/getCharacter')();
var getDnDCharacter2 = require('./plugins/getCharacter2')();
var getDiceString = require('./plugins/getDice')();
var getUrlString = require('./plugins/getUrl')();
var getTweet = require('./plugins/getTweet')(config);
var getInstantAnswer = require('./plugins/getInstantAnswer')(config);
// Configure logger
@ -67,7 +64,6 @@ var logger = new (winston.Logger)({
if(!config.irc.connect) {
logger.info('Not connecting to IRC. Exit');
return;
}
@ -75,6 +71,9 @@ if(!config.irc.connect) {
var client = new irc.Client(config.irc.server, config.irc.nick, {
debug: true,
channels: config.irc.channels,
//floodProtection: true,
//sasl: true,
millisecondsOfSilenceBeforePingSent: 60000,
});
@ -85,6 +84,8 @@ var handleMessage = function(from, to, message) {
for(var i = 0; i < results.length; i++) {
client.say(to, results[i]);
}
}, function(error) {
logger.error('Plugin error: ', error);
});
//if (to.match(/^[#&]/)) {
@ -171,62 +172,6 @@ var handleMessage = function(from, to, message) {
client.say(to, 'Ladattiin asetustiedosto. ' + Object.keys(config.members).length + ' käyttäjäasetusta. Päivitetään operaattorioikeuksia...');
client.send('NAMES', to);
}
// Url specific handling
if(res = message.match(/http(s)?:\/\/(www\.)?((youtu\.be\/([a-zA-Z0-9_-]*))|(youtube\.com\/watch\?([a-zA-Z0-9_=#-]+&)*v=([a-zA-Z0-9_-]+)))/)) {
console.log(res);
var id = res[7];
if(typeof id === 'undefined') {
id = res[5];
}
if(typeof id !== 'undefined') {
googletin.getYoutubeVideoById(id).then(function(result) {
var resultString = 'Youtube: ';
resultString += result.title;
resultString += ', esittäjänä ' + result.channelTitle;
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+' )';
client.say(to, ''+resultString);
}, function(err) {
console.log('error', err);
client.say(to, 'Youtube: jokin meni pieleen...');
});
}
} else if (res = message.match(/^\.youtube (.+)$/i)) {
console.log(res);
googletin.getYoutubeVideo(res[1]).then(function(result) {
var resultString = 'Youtube: ';
resultString += result.title;
resultString += ', esittäjänä ' + result.channelTitle;
var rotten = (Number(result.statistics.likeCount)/(Number(result.statistics.likeCount)+Number(result.statistics.dislikeCount))).toFixed(2);
//resultString += ' ('+result.duration+')';
resultString += ' ('+result.duration+', '+ result.statistics.viewCount +' katselukertaa, '+rotten*100+'% tykätty, '+result.url+' )';
//console.log(resultString);
client.say(to, ''+resultString);
}, function(err) {
console.log('error');
client.say(to, 'Youtube: jokin meni pieleen...');
});
} else if (res = message.match(/http(s)?:\/\/(www\.)?((twitter\.com\/([a-zA-Z0-9_-]*)\/status\/([a-zA-Z0-9_-]*)))/)) {
var status = res[6];
getTweet(status).then(function(tweet) {
client.say(to, 'Twiitti: ' + tweet);
});
} else if (res = message.match(/http(s)?:\/\/([^ ]*)/i)) {
// Not liked. Disabled for now
/*var url = res[0];
console.log('Get url: ' + url);
getUrlString(url).then(function(str) {
client.say(to, 'Otsikko: ' + str);
});*/
} else {
// Do nothing? :D
}
};

View File

@ -1,33 +0,0 @@
var Promise = require('promise');
var Twitter = require('twitter');
module.exports = function(config) {
var client = new Twitter({
consumer_key: config.keys.twitter.consumerKey,
consumer_secret: config.keys.twitter.consumerSecret,
access_token_key: '',
access_token_secret: ''
});
var getTweet = function(statusId) {
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 +')';
resolve(str);
} else {
reject();
}
});
});
return promise;
};
return getTweet;
};

View File

@ -1,26 +1,8 @@
var request = require('request');
var Promise = require('promise');
var requestPromise = require('./requestPromise.js');
var google = require('googleapis');
var youtube = google.youtube('v3');
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(JSON.parse(body));
} else {
reject(error);
}
});
});
return promise;
};
module.exports = function(config) {
'use strict';
var apikey = config.keys.google.apiKey;
@ -72,10 +54,6 @@ module.exports = function(config) {
reject(err);
}
//console.log(resp.items[0].snippet.title);
//console.log(resp.items[0].snippet.channelTitle);
//console.log(resp, videoId);
if(resp === null || resp.items === null) {
reject('No results (null)');
return;

69
plugins/twitter.js Normal file
View File

@ -0,0 +1,69 @@
var Promise = require('promise');
var BasePlugin = require('./base.js');
var logger = require('winston');
class Twitter extends BasePlugin {
constructor(config) {
super(config);
this.name = 'Twitter';
this.config = config;
}
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;
}
return false;
}
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, ' ');
resolve(str);
} else {
reject();
}
});
});
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');
});
} else {
resultReject('Twiitti: Jokin virhe tapahtui');
}
});
return resultPromise;
}
}
module.exports = Twitter;

64
plugins/youtube.js Normal file
View File

@ -0,0 +1,64 @@
var Promise = require('promise');
var requestPromise = require('./helpers/requestPromise.js');
var BasePlugin = require('./base.js');
var logger = require('winston');
class Youtube extends BasePlugin {
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;
}
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;
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...');
}
}
result(input) {
var that = this;
var resultPromise = new Promise(function(resultResolve, resultReject) {
var res = null;
if (res = input.match(/https?:\/\/(?:www\.)?(?:(?:youtu\.be\/([\w-]+)))/i)) {
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, resultResolve, resultReject);
} else {
resultReject('Youtube: jokin meni pieleen (ei osunut)...');
}
});
return resultPromise;
}
}
module.exports = Youtube;