Skip to content

Instantly share code, notes, and snippets.

@k3n
Created June 9, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k3n/6c8b8a7cbf8df6ceb4c4 to your computer and use it in GitHub Desktop.
Save k3n/6c8b8a7cbf8df6ceb4c4 to your computer and use it in GitHub Desktop.
var request = require("request");
var util = require('util');
//var WebSocket = require('ws');
var WebSocketClient = require('websocket').client;
var ws;
var message = "";
var i = 0;
var latex = {};
/**
* Dictionary of URL's (template strings) that we'll use to construct our URL's.
*
* This is handy so that we can easily update these in the future, and/or swap them out for ConDel testing.
*
* @type {{START: string, DELETE: string, CHAT: string, LATEX: string}}
*/
var URL = {
START: 'https://slack.com/api/rtm.start?token=%s&pretty=1',
DELETE: 'https://slack.com/api/chat.delete?token=%s&ts=%s&channel=%s&pretty=1',
CHAT: 'https://slack.com/api/chat.postMessage?token=%s&channel=%s&text=%20&attachments=%5B%7B%22fallback%22%3A%22.%22%2C%22color%22%3A%20%22%2336a64f%22%2C%22image_url%22%3A%22%s%22%7D%5D&pretty=1',
LATEX: 'http://latex.codecogs.com/png.latex?%5Cdpi%7B300%7D%20%s'
};
/*
* Here begings the action!
*/
var fs = require('fs');
fs.readFile('secret.txt', 'utf8', function(err, data) {
global.token = data;
getWebSocket();
});
/**
* Get the websocket URL.
*
* Query the Slack API for the URL, then create a `WebSocketClient` with the result.
*/
function getWebSocket() {
request(util.format(URL.START, global.token)), function(error, response, body) {
//console.log(response.url);
if (!error && response.statusCode === 200) {
url = JSON.parse(body).url;
console.log("Creating url:" + url);
createWS(url);
}
});
}
/**
* Create a `WebSocketClient`, attach relevant event handlers, and then connect to `url`.
*
* @param url string The URL which you'll be connecting to.
* @returns {WebSocketClient}
*/
function createWS(url) {
var client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error: ' + error.toString());
});
client.on('connect', function(connection) {
console.log('WebSocket Client Connected');
connection.on('error', function(error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
});
connection.on('message', processMessageClosure(connection));
});
client.connect(url);
console.log("hey?");
return client;
}
/**
* Generate a function with a closure to process incoming messages.
*
* Using a closure so that we can access `connection` (would be better to refactor this requirement out).
*
* @param {WebSocketConnection} connection
* @returns {Function}
*/
function processMessageClosure(connection) {
/**
* Process a message...
*
* @param {Object} message
*/
return function processMessage(message) {
if (message.type === 'utf8') {
var mObj = JSON.parse(message.utf8Data);
console.log("Received: '" + message.utf8Data + "'");
console.log(mObj.type + "\n");
if (mObj.type === 'message') {
console.log("\t" + mObj.channel + "\n");
console.log("\t" + mObj.user + "\n");
console.log("\t" + mObj.text + "\n");
console.log("\t" + escape(mObj.text) + "\n");
if (mObj.text === '..ping' && connection.connected) {
pong(mObj.channel, "pong");
i++;
}
if (latex[mObj.user + mObj.channel] && mObj.text[0] === '$' && mObj.text[mObj.text.length - 1] === '$' && mObj.text.length > 1) {
deleteMessage(mObj.ts, mObj.channel);
postLatex(mObj.channel, mObj.text.substring(1, mObj.text.length - 1).replace('&', '&'));
console.log('Converting to latex: ' + mObj.text);
}
if (mObj.text === '..startLatex') {
latex[mObj.user + mObj.channel] = true;
console.log('Enable latex for ' + mObj.user + mObj.channel);
} else if (mObj.text === '..stopLatex') {
latex[mObj.user + mObj.channel] = false;
console.log('disable latex for ' + mObj.user + mObj.channel);
}
}
}
};
}
/**
* Respond to a server ping.
*
* @param {string} channel The channel for the pong.
* @param {string} text The text for the pong.
* @param {number} i The index for the message.
*/
function pong(channel, text, i) {
connection.sendUTF(JSON.stringify({
text: text,
channel: channel,
id: i,
type: 'message'
}));
}
/**
* Delete a message via Slack API.
*
* @param {string} timestamp
* @param {string} channel
*/
function deleteMessage(timestamp, channel) {
var url = util.format(URL.DELETE, global.token, timestamp, channel);
request(url, function(error, response, body) {
//console.log(response.url);
if (!error && response.statusCode === 200) {
console.log(body);
}
});
}
/**
* Post a Latex message to Slack API.
*
* @param {string} channel ...?
* @param {string} text ...?
*/
function postLatex(channel, text) {
var urlBase = util.format(URL.LATEX, encodeURIComponent(text));
var url = util.format(URL.CHAT, global.token, channel, encodeURIComponent(urlBase));
request(url, function(error, response, body) {
//console.log(response.url);
if (!error && response.statusCode === 200) {
console.log(body);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment