freifunk-bot

Modular parser for the hackerspace door status with handlers for multiple services
git clone git://archive.git.mtrnord.blog/MTRNord/freifunk-bot.git
Log | Files | Refs | README | LICENSE

commit 02fd5586937cf9875e3218c4878f151f2072fa95
parent f5fe0280e6368a65ccd297a7a9d75726cd2e1505
Author: MTRNord <mtrnord1@gmail.com>
Date:   Sat, 10 Sep 2016 22:58:40 +0200

remove any for loops that can already be replaced

Diffstat:
Mhandlers/getNodes.js | 102+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mhandlers/irc.js | 597++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mhandlers/slack.js | 41++++++++++++++++++-----------------------
Mhandlers/telegram.js | 19++++++++-----------
Mmain.js | 5+++--
Mpackage.json | 1+
6 files changed, 379 insertions(+), 386 deletions(-)

diff --git a/handlers/getNodes.js b/handlers/getNodes.js @@ -12,6 +12,7 @@ var request = require('request') var fs = require('fs'); var jsonfile = require('jsonfile') var slack = require('./slack.js'); +var _ = require("underscore"); /** * Get Community Config at start * @@ -58,66 +59,63 @@ module.exports = { return console.log(err); } var communities = obj - for (var key in communities.communities) { - if (communities.communities.hasOwnProperty(key)) { - var ccode = communities.communities[key]["ccode"]; - if (ccode.toLowerCase() === ccode_func.toLowerCase()) { - var nodesFile_link = communities.communities[key]["nodesURL"]; - var name = communities.communities[key]["name"]; - request.get(nodesFile_link, function (err, res, body) { - if (!err && res.statusCode == 200) { - /** - * Content of communities - * - * @property communities - * @type String - */ - // console.log(body); - // onlineNodes = body.nodes.length - // onlineNodes = Object.keys(body.nodes).length; - var count = 0; - for(var key in JSON.parse(body).nodes) { - if(JSON.parse(body).nodes.hasOwnProperty(key)) { - if (JSON.parse(body).nodes[key].hasOwnProperty('flags')) { - if (JSON.parse(body).nodes[key]["flags"]["online"] == true) { - count++; - } + _.find(communities.communities, function (key) { + var ccode = key["ccode"]; + if (ccode.toLowerCase() === ccode_func.toLowerCase()) { + var nodesFile_link = key["nodesURL"]; + var name = key["name"]; + request.get(nodesFile_link, function (err, res, body) { + if (!err && res.statusCode == 200) { + /** + * Content of communities + * + * @property communities + * @type String + */ + // console.log(body); + // onlineNodes = body.nodes.length + // onlineNodes = Object.keys(body.nodes).length; + var count = 0; + nodes = JSON.parse(body) + _.find(nodes.nodes, function (key) { + if (key.hasOwnProperty('flags')) { + if (key["flags"]["online"] == true) { + count++; + } + if (key.hasOwnProperty('status')) { + if (key["status"]["online"] == true) { + count++; } - if (JSON.parse(body).nodes[key].hasOwnProperty('status')) { - if (JSON.parse(body).nodes[key]["status"]["online"] == true) { - count++; - } - } } } - var output = "Current nodes in " + name + ": " + count - if(handler === "telegram"){ - bot.sendMessage(TfromId, output); - botan.track(Tmsg, 'nodes ' + ccode_func) + }); + var output = "Current nodes in " + name + ": " + count + if(handler === "telegram"){ + bot.sendMessage(TfromId, output); + botan.track(Tmsg, 'nodes ' + ccode_func) + }else { + if(handler === "irc"){ + bot.say(IRCto, output); }else { - if(handler === "irc"){ - bot.say(IRCto, output); - }else { - if(handler === "slack"){ - slack.slackSend(Schannel, output); - } + if(handler === "slack"){ + slack.slackSend(Schannel, output); } } - }else{ - /** - * Fired when an error occurs... - * - * @property error - * @type String - */ - //TODO Add real Error Handler - console.log(err); - return err } - }) - } + }else{ + /** + * Fired when an error occurs... + * + * @property error + * @type String + */ + //TODO Add real Error Handler + console.log(err); + return err + } + }) } - } + }); }); } } diff --git a/handlers/irc.js b/handlers/irc.js @@ -11,8 +11,9 @@ var irc = require('irc'); var request = require('request'); var S = require('string'); var jsonfile = require('jsonfile') -var ent = require('ent'); -var decode = require('ent/decode'); +var async = require("async"); +var _ = require("underscore"); + var command_config = require("../configs/commands.json"); var params_config = require("../configs/ircServer.json"); @@ -61,35 +62,33 @@ for (var key in params_config["servers"]) { */ var clients = []; var bot = []; -for (var key in params_config["servers"]) { - if (params_config["servers"].hasOwnProperty(key)) { - var serveraddress = params_config["servers"][key]["serveraddress"]; - var main_channel = params_config["servers"][key]["main_channel"]; - var active = params_config["servers"][key]["active"]; - var debug = params_config["servers"][key]["debug"]; - if (debug == 1) { - var debug = true; - }else{ - var debug = false; - } - if (debug == false) { - console = console || {}; - console.log = function(){}; - } - if (active == 1) { - bot[key] = new irc.Client(serveraddress, botname, { - debug: debug, - channels: [main_channel], - autoRejoin: true, - autoConnect: false, - messageSplit: 1000000, - floodProtection: true, - floodProtectionDelay: 1000, - }); - clients.push(bot[key]); - } +_.find(params_config["servers"], function (key) { + serveraddress = key["serveraddress"]; + main_channel = key["main_channel"]; + active = key["active"]; + debug = key["debug"]; + if (debug == 1) { + debug = true; + }else{ + debug = false; } -} + if (debug == false) { + console = console || {}; + console.log = function(){}; + } + if (active == 1) { + bot[key] = new irc.Client(serveraddress, botname, { + debug: debug, + channels: [main_channel], + autoRejoin: true, + autoConnect: false, + messageSplit: 1000000, + floodProtection: true, + floodProtectionDelay: 1000, + }); + clients.push(bot[key]); + } +}); function addListener(event, callback) { clients.forEach(function(client) { @@ -151,299 +150,301 @@ module.exports = { }, 7000); send('nick', botname); - for (var key in params_config["servers"]) { - if (params_config["servers"].hasOwnProperty(key)) { - /** - * Password for the NickServ - * - * @property nickserv_pass - * @type String - */ - var nickserv_pass = params_config["servers"][key]["nickserv_pass"]; - say('NickServ', 'identify ' + nickserv_pass); - } - } + _.find(params_config["servers"], function (key) { + /** + * Password for the NickServ + * + * @property nickserv_pass + * @type String + */ + var nickserv_pass = key["nickserv_pass"]; + say('NickServ', 'identify ' + nickserv_pass); + }); }); setTimeout(function() { console.log("wait 7sek"); }, 7000); connect(10, function() { send('nick', botname); - for (var key in params_config["servers"]) { - if (params_config["servers"].hasOwnProperty(key)) { - /** - * Password for the NickServ - * - * @property nickserv_pass - * @type String - */ - var nickserv_pass = params_config["servers"][key]["nickserv_pass"]; - /** - * Main Channel of the Bot - * - * @property main_channel - * @type String - */ - var main_channel = params_config["servers"][key]["main_channel"]; - say('NickServ', 'identify ' + nickserv_pass); - join(main_channel); - } - } + _.find(params_config["servers"], function (key) { + /** + * Password for the NickServ + * + * @property nickserv_pass + * @type String + */ + var nickserv_pass = key["nickserv_pass"]; + /** + * Main Channel of the Bot + * + * @property main_channel + * @type String + */ + var main_channel = key["main_channel"]; + say('NickServ', 'identify ' + nickserv_pass); + join(main_channel); + }); //say(main_channel, 'Door Bot is starting to watch on the Door Status'); }) }, /** - * Send DoorStatus to selected Channels - * - * @method ircSend - * @constructor - */ + * Send DoorStatus to selected Channels + * + * @method ircSend + * @constructor + */ ircSend: function (door_status) { - for (var key in params_config["servers"]) { - if (params_config["servers"].hasOwnProperty(key)) { - /** - * Main Channel of the Bot - * - * @property main_channel - * @type String - */ - var main_channel = params_config["servers"][key]["main_channel"]; - say(main_channel, 'Door Status changed to: ' + door_status); - say("#freifunk-flensburg", 'Door Status changed to: ' + door_status); - } - } - send('topic','#hackerspace "Hackerspace Flensburg - Treffen jeden Montag 18:00 Uhr im Offenen Kanal Flensburg! - Tür Status"' + door_status); - console.log("IRC Door Status Chnaged"); - }, + _.find(params_config["servers"], function (key) { + /** + * Main Channel of the Bot + * + * @property main_channel + * @type String + */ + var main_channel = key["main_channel"]; + say(main_channel, 'Door Status changed to: ' + door_status); + say("#freifunk-flensburg", 'Door Status changed to: ' + door_status); + }); + //send('topic','#hackerspace "Hackerspace Flensburg - Treffen jeden Montag 18:00 Uhr im Offenen Kanal Flensburg! - Tür Status"' + door_status); + //console.log("IRC Door Status Chnaged"); + }, /** - * Stops Bot with Stop measseagew freom config file - * - * @method ircStopp - */ - ircStopp: function() { - disconnect(disconnect_meassage); - }, + * Stops Bot with Stop measseagew freom config file + * + * @method ircStopp + */ + ircStopp: function() { + disconnect(disconnect_meassage); + }, /** - * Handels Commands from the Bot - * - * @method ircBotCommands - */ - ircBotCommands: function() { - // Will remove all false values: undefined, null, 0, false, NaN and "" (empty string) - function cleanArray(actual) { - var newArray = new Array(); - for (var i = 0; i < actual.length; i++) { - if (actual[i]) { - newArray.push(actual[i]); - } + * Handels Commands from the Bot + * + * @method ircBotCommands + */ + ircBotCommands: function() { + // Will remove all false values: undefined, null, 0, false, NaN and "" (empty string) + function cleanArray(actual) { + var newArray = new Array(); + for (var i = 0; i < actual.length; i++) { + if (actual[i]) { + newArray.push(actual[i]); } - return newArray; } + return newArray; + } - addListener('message', function (from, to, message) { - /** - * Recived meassage - * - * @property message - * @type String - */ - message = message.toLowerCase(); - for (var key in command_config["commands"]) { - if (command_config["commands"].hasOwnProperty(key)) { - if (S(message).contains("!" + command_config["commands"][key]["keyword"])) { - if (command_config["commands"][key]["before"] == "from") { - if (command_config["commands"][key]["target"] == "from") { - say(from, from + command_config["commands"][key]["message"]); - } else { - say(to, from + command_config["commands"][key]["message"]); - } - } else { - if (!command_config["commands"][key]["before"]) { - if (command_config["commands"][key]["target"] == "from") { - say(from, command_config["commands"][key]["message"]); - } else { - say(to, command_config["commands"][key]["message"]); - } - } else { - if (command_config["commands"][key]["target"] == "from") { - say(from, to + command_config["commands"][key]["message"]); - } else { - say(to, to + command_config["commands"][key]["message"]); - } - } - } - } - } - } - /** - * List of Channels on Server - * - * @property channel - * @type Array - * - * @beta - */ - var channel = message.split(" "); - channel = cleanArray(channel); - if (S(channel[0] + " " + channel[1]).contains("!source this")) { - console.log("!source " + channel[1]); - if (channel[1] == "this") { - join(to); - say(to, "You can find the Source of this bot at https://github.com/MTRNord/nordlab-hackerspace-door"); - } - } - // TODO ADD !nodes [Community code] - /*getNodes.countNodes("FFFL") - */ - - if (S(message).contains("!nodes")) { - jsonfile.readFile('handlers/tmp/communities.json', 'utf8', function (err,obj) { - var communities = obj - for (var key in communities.communities) { - if (communities.communities.hasOwnProperty(key)) { - var ccode = communities.communities[key].ccode; + addListener('message', function (from, to, message) { + /** + * Recived meassage + * + * @property message + * @type String + */ + message = message.toLowerCase(); + async.auto({ + commandFile: function (callback) { + _.find(command_config["commands"], function (key) { + if (S(message).contains("!" + key["keyword"])) { + if (key["before"] == "from") { + if (key["target"] == "from") { + say(from, from + key["message"]); + } else { + say(to, from + key["message"]); + } + } else { + if (!key["before"]) { + if (key["target"] == "from") { + say(from, key["message"]); + } else { + say(to, key["message"]); + } + } else { + if (key["target"] == "from") { + say(from, to + key["message"]); + } else { + say(to, to + key["message"]); + } + } + } + } + }); + }, + channelList: function (callback) { + /** + * List of Channels on Server + * + * @property channel + * @type Array + * + * @beta + */ + channel = message.split(" "); + channel = cleanArray(channel); + if (S(channel[0] + " " + channel[1]).contains("!source this")) { + console.log("!source " + channel[1]); + if (channel[1] == "this") { + join(to); + say(to, "You can find the Source of this bot at https://github.com/MTRNord/nordlab-hackerspace-door"); + } + } + }, + nodes: function (callback) { + if (S(message).contains("!nodes")) { + jsonfile.readFile('handlers/tmp/communities.json', 'utf8', function (err,obj) { + var communities = obj + _.find(communities.communities, function (key) { + var ccode = key["ccode"]; if (ccode.toLowerCase() === channel[1]) { clients.forEach(function(client) { getNodes.countNodes(channel[1], "irc", "", "", "", client, "", to) }); } + }); + }); + } + }, + communities: function (callback) { + if (S(message).contains("!communities")) { + jsonfile.readFile('handlers/tmp/communities.json', 'utf8', function (err,obj) { + var communities = obj + var communities_list = "" + _.find(communities.communities, function (key) { + var ccode = key["ccode"] + var name = key["name"] + say(from, name + ": " + ccode + " ") + }); + }) + } + }, + doorstatus: function (callback) { + if (S(message).contains("!doorstatus")) { + request.get('http://www.nordlab-ev.de/doorstate/status.txt', function (error, response, body) { + if (!error && response.statusCode == 200) { + /** + * Content of status_page + * + * @property body + * @type String + */ + door_status = body; + console.log(body); + } else { + /** + * Fired when an error occurs... + * + * @property error + * @type String + */ + door_status = error; + console.log(error); + } + if (!error && response.statusCode == 200) { + if (door_status == "geschlossen") { + door_status = "closed"; + } else { + door_status = "open"; + } + console.log(from + ' => ' + to + ': ' + message); + say(from, "DoorStatus is: " + door_status); + }else{ + say(from, "DoorStatus is not availible at this time"); } - } - }); - } - - if (S(message).contains("!communities")) { - jsonfile.readFile('handlers/tmp/communities.json', 'utf8', function (err,obj) { - var communities = obj - var communities_list = "" - for (var key in communities.communities) { - if (communities.communities.hasOwnProperty(key)) { - var ccode = decode(communities.communities[key].ccode) - var name = decode(communities.communities[key].name) - communities_list = communities_list + name + ": " + ccode + " " - } - } - say(to, communities_list) - }) - } - - - if (S(message).contains("!doorstatus")) { - request.get('http://www.nordlab-ev.de/doorstate/status.txt', function (error, response, body) { - if (!error && response.statusCode == 200) { - /** - * Content of status_page - * - * @property body - * @type String - */ - door_status = body; - console.log(body); - } else { - /** - * Fired when an error occurs... - * - * @property error - * @type String - */ - door_status = error; - console.log(error); - } - if (!error && response.statusCode == 200) { - if (door_status == "geschlossen") { - door_status = "closed"; - } else { - door_status = "open"; - } - console.log(from + ' => ' + to + ': ' + message); - say(from, "DoorStatus is: " + door_status); - }else{ - say(from, "DoorStatus is not availible at this time"); - } - }).setMaxListeners(0); - } - if (S(channel[0] + " " + channel[1]).contains("!doorstatus this")) { - request.get('http://www.nordlab-ev.de/doorstate/status.txt', function (error, response, body) { - if (!error && response.statusCode == 200) { - /** - * Content of status_page - * - * @property body - * @type String - */ - door_status = body; - console.log(body); - } else { - /** - * Fired when an error occurs... - * - * @property error - * @type String - */ - door_status = error; - console.log(error); - } - if (!error && response.statusCode == 200) { - if (door_status == "geschlossen") { - door_status = "closed"; - } else { - door_status = "open"; - } - console.log(message); - list(); - console.log(channel[(channel.length-(channel.length-1))+1]); - console.log(channel.length); - if (channel[1] !== "this") { - if (channel[1] !== " ") { - addListener('channellist', function (channel_list) { - for (var key in channel_list) { - if (channel_list.hasOwnProperty(key)) { - if (channel_list[key]["name"] == channel[1]) { - join(channel[1]); - say(channel[1], "DoorStatus is: " + door_status); - } - } - } - }); - } else { - say(from, "DoorStatus is: " + door_status); - } - } else { - join(to); - say(to, "DoorStatus is: " + door_status); - } - }else{ - say(from, "DoorStatus is not availible at this time"); - } - }).setMaxListeners(0); + }).setMaxListeners(0); } - if (S(message).contains("!kill")) { - if ((from == "DasNordlicht") || (from == "MTRNord")) { - console.log(from + ' => ' + to + ': ' + message); - if (process.platform === "win32") { - var rl = require("readline").createInterface({ - input: process.stdin, - output: process.stdout - }); - disconnect(disconnect_meassage); - process.exit(); - } - } - } - if (S(message).contains("!join")) { - if ((from == "DasNordlicht") || (from == "MTRNord")) { + }, + doorstatusThis: function (callback) { + if (S(channel[0] + " " + channel[1]).contains("!doorstatus this")) { + request.get('http://www.nordlab-ev.de/doorstate/status.txt', function (error, response, body) { + if (!error && response.statusCode == 200) { + /** + * Content of status_page + * + * @property body + * @type String + */ + door_status = body; + console.log(body); + } else { + /** + * Fired when an error occurs... + * + * @property error + * @type String + */ + door_status = error; + console.log(error); + } + if (!error && response.statusCode == 200) { + if (door_status == "geschlossen") { + door_status = "closed"; + } else { + door_status = "open"; + } + console.log(message); + list(); + console.log(channel[(channel.length-(channel.length-1))+1]); + console.log(channel.length); + if (channel[1] !== "this") { + if (channel[1] !== " ") { + addListener('channellist', function (channel_list) { + _.find(channel_list, function (key) { + if (key["name"] == channel[1]) { + join(channel[1]); + say(channel[1], "DoorStatus is: " + door_status); + } + }); + }); + } else { + say(from, "DoorStatus is: " + door_status); + } + } else { + join(to); + say(to, "DoorStatus is: " + door_status); + } + }else{ + say(from, "DoorStatus is not availible at this time"); + } + }).setMaxListeners(0); + } + }, + kill: function (callback) { + if (S(message).contains("!kill")) { + if ((from == "DasNordlicht") || (from == "MTRNord")) { + console.log(from + ' => ' + to + ': ' + message); + if (process.platform === "win32") { + var rl = require("readline").createInterface({ + input: process.stdin, + output: process.stdout + }); + disconnect(disconnect_meassage); + process.exit(); + } + } + } + }, + join: function (callback) { + if (S(message).contains("!join")) { + if ((from == "DasNordlicht") || (from == "MTRNord")) { console.log(from + ' => ' + to + ': ' + message); join(channel[1]); + } + } + } + }, + function(err, result) { + if (err) { + console.log(err) } } - }) - }, - /** - * Updates the NickName - * - * @method ircNick - */ - ircNick: function() { - send('nick', botname); - } + ); + }) +}, +/** + * Updates the NickName + * + * @method ircNick + */ +ircNick: function() { + send('nick', botname); +} }; diff --git a/handlers/slack.js b/handlers/slack.js @@ -11,6 +11,7 @@ var command_config = require("../configs/commands.json"); var params_config = require("../configs/slackServer.json"); var SlackBot = require('slackbots'); var S = require('string'); +var _ = require("underscore"); //Set Params /** @@ -28,19 +29,18 @@ var botname = params_config["botname"]; */ var disconnect_meassage = params_config["disconnect_meassage"]; var session; -for (var key in params_config["servers"]) { - if (params_config["servers"].hasOwnProperty(key)) { - var serveraddress = params_config["servers"][key]["serveraddress"]; - var devChannel = params_config["servers"][key]["devChannel"]; - var token = params_config["servers"][key]["token"]; - var active = params_config["servers"][key]["active"]; - var debug = params_config["servers"][key]["debug"];// create a bot - var bot = new SlackBot({ - token: token, - name: 'FreifunkBot' - }); - } -} +_.find(params_config["servers"], function (key) { + serveraddress = key["serveraddress"]; + devChannel = key["devChannel"]; + token = key["token"]; + active = key["active"]; + debug = key["debug"]; + bot = new SlackBot({ + token: token, + name: 'FreifunkBot' + }); +}); + function getDateTime() { var date = new Date(); var hour = date.getHours(); @@ -56,6 +56,7 @@ function getDateTime() { day = (day < 10 ? "0" : "") + day; return day + "." + month + "." + year + " " + hour + ":" + min + ":" + sec; } + module.exports = { /** * Connects to Server @@ -87,19 +88,13 @@ bot.on('message', function(data) { if (textmessage != null){ textmessage = textmessage.toLowerCase(); } - // if (S(textmessage).contains('!help')) { - // console.log(channel); - // bot.postMessage(channel, 'help!', params); - // } - for (var key in command_config["commands"]) { - if (command_config["commands"].hasOwnProperty(key)) { + _.find(command_config["commands"], function (key) { if (subtype != "bot_message"){ - if (S(textmessage).contains("!" + command_config["commands"][key]["keyword"])) { - bot.postMessage(channel, command_config["commands"][key]["message"], params); + if (S(textmessage).contains("!" + key["keyword"])) { + bot.postMessage(channel, key["message"], params); }else { console.log(""); } } - } - } + }); }); diff --git a/handlers/telegram.js b/handlers/telegram.js @@ -9,6 +9,7 @@ var botan = require('botanio')("H4dyFijDsUeCfwvMe-_nDuzdOYFyo_SR"); var ent = require('ent'); var decode = require('ent/decode'); var util = require('util'); +var _ = require("underscore"); // Setup polling way var bot = new TelegramBot(token, {polling: true}); module.exports = { @@ -19,14 +20,12 @@ module.exports = { bot.sendChatAction(fromId, "typing") jsonfile.readFile('handlers/tmp/communities.json', 'utf8', function (err,obj) { var communities = obj - for (var key in communities.communities) { - if (communities.communities.hasOwnProperty(key)) { - var ccode = communities.communities[key].ccode; + _.find(communities.communities, function (key) { + var ccode = key["ccode"]; if (ccode.toLowerCase() === resp.toLowerCase()) { getNodes.countNodes(resp.toLowerCase(), "telegram", fromId, msg, "", bot, botan) } - } - } + }); }); }); bot.onText(/\/communities/, function (msg, match) { @@ -36,13 +35,11 @@ module.exports = { jsonfile.readFile('handlers/tmp/communities.json', 'utf8', function (err,obj) { var communities = obj var communities_list = "" - for (var key in communities.communities) { - if (communities.communities.hasOwnProperty(key)) { - var ccode = decode(communities.communities[key].ccode) - var name = decode(communities.communities[key].name) + _.find(communities.communities, function (key) { + var ccode = decode(key["ccode"]) + var name = decode(key["name"]) communities_list = communities_list + name + ": " + ccode + "\n" - } - } + }); botan.track(msg, 'communities', function (err, res, body) { if (err) { console.log("[BOTAN] ERR: " + err); diff --git a/main.js b/main.js @@ -13,6 +13,7 @@ var argv = require('yargs').argv; var params_config = require("./configs/ircServer.json"); var autoupdate = params_config["autoupdate"]; var async = require("async"); +var _ = require("underscore"); //LOAD MODULES DOWN HERE require('./helper/heroku.js'); @@ -170,8 +171,8 @@ async.auto({ // if next is called with a value in its first parameter, it will appear // in here as 'err', and execution will stop. callback(err) - } - ); + } + ); } }, function(err, result) { diff --git a/package.json b/package.json @@ -35,6 +35,7 @@ "simple-git": "^1.21.0", "slackbots": "^0.5.1", "string": "^3.3.1", + "underscore": "^1.8.3", "yargs": "^4.1.0" }, "preferGlobal": false,