forked from STRML/js-slack-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (80 loc) · 2.57 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
'use strict';
const Botkit = require('botkit');
const {VM} = require('vm2');
const fs = require('fs');
const path = require('path');
const babel = require('babel-core');
const entities = new (require('html-entities').AllHtmlEntities)();
const BABEL_PRESETS = ['es2015-loose', 'react', 'stage-0'];
const BABEL_PRESETS_NODE6 = ['node6'].concat(BABEL_PRESETS.slice(1));
const BABEL_PLUGINS = ['transform-decorators-legacy'];
const token = fs.readFileSync(path.join(__dirname, '.token')).toString('utf8').trim();
var controller = Botkit.slackbot({
debug: false,
});
controller.spawn({
token: token,
// retry: Infinity // broken, see https://github.com/howdyai/botkit/issues/261
}).startRTM(function(err) {
if (err) throw new Error(err);
console.log('Slack connection opened.');
});
controller.on('rtm_close', function() {
console.error('Slack connection closed! Exiting.');
process.exit(1);
});
const VM_OPTIONS = {
timeout: 1000,
sandbox: {}
};
const vm = new VM(VM_OPTIONS);
//--- Built-ins
vm.run(
'help = function(object) {' +
' return Object.getOwnPropertyNames(object);' +
'};'
);
//--- End Built-ins
const codeRegex = /(^`+|`+$)/g;
const crappySingleQuoteRegex = /([‘’])/g;
const crappyDoubleQuoteRegex = /([“”])/g;
const babelRegex = /^babel(-node6)?:?\s*([\s\S]*)/i;
controller.hears(['[\s\S]*'],['direct_message','direct_mention','mention'], function(bot, message) {
let {text} = message;
// Ping
if (text === 'ping') return bot.reply('pong');
// Shortcut for `help(this)`
if (text === 'help') text += '(this);';
try {
// Babel transpile
const match = text.match(babelRegex);
if (match && match.length) {
// Get raw code
let code = match[match.length - 1];
// Comes in escaped
code = cleanupCode(code);
// Get presets
const isNode6 = match[1] === '-node6';
const presets = isNode6 ? BABEL_PRESETS_NODE6 : BABEL_PRESETS;
// Transform
let transformed = babel.transform(code, {presets, plugins: BABEL_PLUGINS, highlightCode: false}).code;
transformed = transformed.replace('"use strict";\n\n', '');
return bot.reply(message, '```' + transformed + '```');
} else {
// Regular eval
text = cleanupCode(text);
const result = vm.run(text);
bot.reply(message, `\`${result && result.toString()}\``);
}
} catch (e) {
bot.reply(message, '```' + e.message + '```');
}
});
function cleanupCode(text) {
return entities.decode(
text
.replace(codeRegex, '')
.replace(crappySingleQuoteRegex, "'")
.replace(crappyDoubleQuoteRegex, '"')
);
}