Skip to content

Instantly share code, notes, and snippets.

@kuroisuna
Created September 22, 2016 17:41
Show Gist options
  • Save kuroisuna/82b0867da00ebb99bb9cd2ba15e0b7ed to your computer and use it in GitHub Desktop.
Save kuroisuna/82b0867da00ebb99bb9cd2ba15e0b7ed to your computer and use it in GitHub Desktop.
NODE: Easily send Push Notifications through PushBullet
// Important to use dotenv (https://www.npmjs.com/package/dotenv) for security reasons
// every saved env variable is available inside "process.env"
require("dotenv").config();
var redis = require("redis");
var pushBullet = require("pushbullet");
require("moment");
var exec = require('child_process').exec;
var promise = require('promise');
// Localized Date
var moment = require('moment-timezone');
var momentTimezone = "America/Caracas";
var todayDate = moment().tz(momentTimezone).format("YYYY-MM-DD");
// Config Redis
var redisClient = redis.createClient({
host: process.env.REDIS_HOST,
});
// Config PushBullet
var pusher = new pushBullet(process.env.PUSHBULLET_KEY);
var deviceParams = {"channel_tag" : process.env.PUSHBULLET_CHANNEL_TAG};
// Message components
var activeUsers = "";
var serverStatus = "";
// Wrap a redis query in a promise
var getActiveUsers = function() {
return new promise(function (resolve, reject) {
// The redis query is async
redisClient.smembers("active:users", function (err, replies) {
if (err) {
activeUsers = 0;
resolve();
return;
}
activeUsers = replies.length
redisClient.quit();
resolve();
});
});
}
// Wrap a command call in a promise
var getServerStatus = function () {
return new promise(function (resolve, reject) {
serverStatus = "Status unknown!";
// With "exec" the command call return either "stdout" or "stderr"
exec("/sbin/status --system user-", function (stdout, stderr) {
// In any case we store the response
serverStatus = (stdout || '') + (stderr || '')
// Some message formatting
.trim()
.replace("driver-socket ", "")
.replace("start/running, ", "OK")
.replace("process ", "@");
resolve();
});
})
};
var sendNotification = function () {
var pushMoment = moment()
.tz(momentTimezone)
.format("D/MMM hh:mma");
noteBody.push("[" + serverStatus + "]");
noteBody.push(activeUsers + " active users");
var noteContent = noteBody.join("\n");
pusher.note(deviceParams, pushMoment, noteContent);
};
// Promises party <3
getActiveUsers()
.then(getServerStatus)
.done(sendNotification);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment