Skip to content

Commit

Permalink
Merge pull request #32 from alexdor/master
Browse files Browse the repository at this point in the history
Add mattremost support
  • Loading branch information
AEtherC0r3 authored Mar 4, 2017
2 parents 277779c + 273a459 commit 9223465
Show file tree
Hide file tree
Showing 5 changed files with 1,200 additions and 84 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
language: node_js
node_js:
- 0.12
- 0.10
- 6.10
- 7.7
156 changes: 92 additions & 64 deletions MinisterIN.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,17 @@ var program = require('commander');
var mqtt = require('mqtt');
var fs = require('fs');
var cron = require('node-schedule');
var mattermost = require('node-mattermost');
require('datejs');

var numOfHackers = -1;
var spaceOpen = false;

program
.version('1.2.1')
.usage('space=[open/closed]')
.option('-s, --space <state>', 'Whether the space is open or closed (default = closed)', /^(closed|open)$/i, 'closed')
.parse(process.argv);
.version('1.3.1')
.usage('space=[open/closed]')
.option('-s, --space <state>', 'Whether the space is open or closed (default = closed)', /^(closed|open)$/i, 'closed')
.parse(process.argv);

// Check if "space=open" was given as argument
spaceOpen = program.space.toLowerCase() === 'open';
Expand All @@ -32,9 +33,9 @@ try {
} catch (e) {
console.log('Could not parse MQTT configuration file: ' + e.message);
mqttConfig = {
caFile : "ca.crt",
port : "8883",
host : "mqtt.lambdaspace.gr"
caFile: "ca.crt",
port: "8883",
host: "mqtt.lambdaspace.gr"
};
}

Expand Down Expand Up @@ -77,6 +78,32 @@ var twitterClient = new Twitter({
access_token_secret: APIKeys.twitter.access_token_secret
});

// Read Mattermost config
try {
var mattermostConfig = require('./mattermost_config.json');
} catch (e) {
console.log('Could not parse mattermost configuration file: ' + e.message);
}


// Create Mattermost client
if (mattermostConfig.hook_url) var mattermostClient = new mattermost(mattermostConfig.hook_url);
var mattermostBroadcast = function(msg, channel = '#town-square') {
if (!msg) return;
try {
mattermostClient.send({
text: msg,
channel: channel,
icon_url: mattermostConfig.icon,
username: mattermostConfig.username
});
return true;
} catch (e) {
console.log('Could not post to mattermost' + e);
return false;
}
};

// Read IRC configuration file
var ircConfig;
try {
Expand All @@ -96,7 +123,7 @@ var mqttOptions = {
port: mqttConfig.port,
host: mqttConfig.host,
protocol: 'mqtts',
rejectUnauthorized : true,
rejectUnauthorized: true,
//The CA list will be used to determine if server is authorized
ca: CA
};
Expand All @@ -107,7 +134,7 @@ try {
console.log(e);
}

client.on('connect', function(){
client.on('connect', function() {
console.log('Connected to MQTT broker ' + mqttConfig.host);
});

Expand All @@ -125,66 +152,64 @@ ircClient.sayAllChannels = function(message) {
};

/**
* Tweet the status of the space
*
* @param newStatus true if the space is open,
* false if the space is closed.
*/
var tweetSpaceOpened = function(newStatus) {
var tweetMsg;
* Tweet the status of the space
*
* @param newStatus true if the space is open,
* false if the space is closed.
*/
var broadcastStatusChange = function(newStatus) {
var msg;
var rand;
if (newStatus) {
rand = Math.floor(Math.random() * tweetMsgs.statusOpen.length);
try {
tweetMsg = tweetMsgs.statusOpen[rand] + ' - Space: OPEN';
msg = tweetMsgs.statusOpen[rand] + ' - Space: OPEN';
} catch (e) {
console.log(e);
}
} else {
rand = Math.floor(Math.random() * tweetMsgs.statusClosed.length);
try {
tweetMsg = tweetMsgs.statusClosed[rand] + ' - Space: CLOSED';
msg = tweetMsgs.statusClosed[rand] + ' - Space: CLOSED';
} catch (e) {
console.log(e);
}
}

twitterClient.post('statuses/update', {status: tweetMsg}, function(error, tweet, response){
twitterClient.post('statuses/update', { status: msg }, function(error, tweet, response) {
if (error) {
console.log('Could not tweet: ' + tweet); // Tweet body.
console.log(response); // Raw response object.
console.log('Could not tweet: ' + tweet); // Tweet body.
console.log(response); // Raw response object.
} else {
// IRC bot says the random message in the channel
ircClient.sayAllChannels(tweetMsg);
console.log('Successfully tweeted: ' + tweet);

ircClient.sayAllChannels(msg);
// Update the status of the spaceOpen variable only after the status
// got successfully tweeted
spaceOpen = newStatus;
}
});

if (mattermostBroadcast(msg)) spaceOpen = newStatus;
};


/**
* Updates the status of the space, given the number
* of the hackers there.
*
* @param numOfHackers the number of hackers in space. or NaN
* in case there was an error while parsing the hackers.txt file.
*/
* Updates the status of the space, given the number
* of the hackers there.
*
* @param numOfHackers the number of hackers in space. or NaN
* in case there was an error while parsing the hackers.txt file.
*/
var updateStatus = function(numOfHackers) {
if (spaceOpen) {
if (numOfHackers === 0) {
// If space status was open and there are no hackers anymore
console.log('Space is empty.');
tweetSpaceOpened(false);
broadcastStatusChange(false);
}
} else {
if (numOfHackers > 0) {
// If space was closed and there are hackers now
console.log('Space is open!');
tweetSpaceOpened(true);
broadcastStatusChange(true);
}
}
};
Expand All @@ -208,27 +233,29 @@ ircClient.addListener('message#LambdaSpace', function(from, message) {
// });

// Github organization Webhooks
var gh_webhook_handler = gh_webhook({'path': '/lambdaspace', 'secret': APIKeys.github.webhook});
var gh_webhook_handler = gh_webhook({ 'path': '/lambdaspace', 'secret': APIKeys.github.webhook });
try {
http.createServer(function (req, res) {
gh_webhook_handler(req, res, function (err) {
res.statusCode = 404;
res.end('No such location');
});
}).listen(7777);
http.createServer(function(req, res) {
gh_webhook_handler(req, res, function(err) {
res.statusCode = 404;
res.end('No such location');
});
}).listen(7777);
} catch (e) {
console.log(e);

}

gh_webhook_handler.on('push', function (event) {
gh_webhook_handler.on('push', function(event) {
ircClient.sayAllChannels(event.payload.pusher.name + ' pushed to repository ' + event.payload.repository.name + ':');
event.payload.commits.forEach(function(commit) {
ircClient.sayAllChannels('* ' + commit.author.name + ' - ' + commit.message);
var msg = '* ' + commit.author.name + ' - ' + commit.message;
ircClient.sayAllChannels(msg);
mattermostBroadcast(msg, '#off-topic');
});
});

gh_webhook_handler.on('error', function (err) {
gh_webhook_handler.on('error', function(err) {
console.error('Github Webhook error:', err.message);
});

Expand Down Expand Up @@ -261,7 +288,7 @@ var eventParser = function(topic) {
var tokens = topic.split(' ');
event.day = tokens[0];
if (!event.day.match(/^\d\d\/\d\d\/\d\d\d\d+$/)) {
throw 'Not in expected format';
console.log('Not in expected format');
}
var dateTokens = tokens[0].split('/');
event.date = new Date(dateTokens[2], dateTokens[1] - 1, dateTokens[0], 0, 0);
Expand All @@ -283,7 +310,7 @@ var parseEvents = function(data) {
var event;
try {
event = eventParser(topic.title);
} catch(e) {
} catch (e) {
return;
}
var pubEvent = null;
Expand All @@ -295,31 +322,32 @@ var parseEvents = function(data) {
if (!!pubEvent) {
pubEvent = pubEvent + event.time + ' - ' + event.title;
ircClient.sayAllChannels(pubEvent);
pubEvent = pubEvent.substring(0,139);
twitterClient.post('statuses/update', {status: pubEvent}, function(error, tweet, response){
pubEvent = pubEvent.substring(0, 139);
twitterClient.post('statuses/update', { status: pubEvent }, function(error, tweet, response) {
if (error) {
console.log('Could not tweet event: ' + pubEvent); // Tweet body.
console.log('Could not tweet event: ' + pubEvent); // Tweet body.
}
});
mattermostBroadcast(pubEvent);
}
});
};

// Check for events every day at 11:00
cron.scheduleJob('0 0 11 * * * *', function() {
try {
request('https://community.lambdaspace.gr/c/5/l/latest.json', function(error, response, body) {
if (!error && response.statusCode == 200) {
try {
parseEvents(JSON.parse(body));
} catch (e) {
console.log('Response from Discourse could not be parsed to JSON');
}
} else {
console.log('Error while retrieving events.json');
}
});
} catch (e) {
console.log(e);
}
try {
request('https://community.lambdaspace.gr/c/5/l/latest.json', function(error, response, body) {
if (!error && response.statusCode == 200) {
try {
parseEvents(JSON.parse(body));
} catch (e) {
console.log('Response from Discourse could not be parsed to JSON');
}
} else {
console.log('Error while retrieving events.json');
}
});
} catch (e) {
console.log(e);
}
});
5 changes: 5 additions & 0 deletions mattermost_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"username": "Consuela",
"hook_url": "your_secret_hook_url",
"icon": "https://lambdaspace.gr/dist/favicons/android-chrome-512x512.png"
}
32 changes: 14 additions & 18 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,44 +1,40 @@
{
"name": "MinisterIN",
"description": "Notification service for the lambdaspace.gr hackerspace.",
"version": "1.2.1",
"version": "1.3.1",
"license": "GPL-3.0",
"author": {
"name": "Marios Isaakidis",
"email": "[email protected]",
"web": "https://github.com/misaakidis"
},
"contributors:": [
{
"name": "Alexandros Dorodoulis",
"email": "[email protected]"
},
{
"name": "Zack Mullaly",
"email": "[email protected]",
"web": "http://redwire.co"
}
],
"contributors:": [{
"name": "Alexandros Dorodoulis",
"email": "[email protected]"
}, {
"name": "Zack Mullaly",
"email": "[email protected]",
"web": "http://redwire.co"
}],
"bugs": {
"url": "https://github.com/techministry/MinisterIN/issues"
},
"scripts": {
"test": "./node_modules/jshint/bin/jshint *.js",
"start": "node MinisterIN.js"
},
"repository": [
{
"type": "git",
"url": "https://github.com/techministry/MinisterIN.git"
}
],
"repository": [{
"type": "git",
"url": "https://github.com/techministry/MinisterIN.git"
}],
"dependencies": {
"commander": "2.9.0",
"datejs": "^1.0.0-rc3",
"fs": "0.0.2",
"github-webhook-handler": "0.5.0",
"irc": "0.4.0",
"mqtt": "^1.11.0",
"node-mattermost": "^0.0.1",
"node-schedule": "^1.1.0",
"request": "^2.72.0",
"twitter": "1.2.5"
Expand Down
Loading

0 comments on commit 9223465

Please sign in to comment.