-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
98 lines (81 loc) · 2.62 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';
var http = require('http');
var https = require('https');
var url = require('url');
var minimist = require('minimist');
var argv;
var port = 3000;
var host = '127.0.0.1';
var slackToken;
var groupRestrict;
var slackHost;
function rollDie(max){
return Math.floor(Math.random() * (max - 1 + 1)) + 1;
}
function startRollServer(port, ip, slackToken, slackHost, groupRestrict){
var server = http.createServer(function(req, res){
var parsed = url.parse(req.url, true);
if(typeof groupRestrict !== 'undefined' && parsed.query.team_id !== groupRestrict){
return res.end('');
}
if(parsed.pathname === '/roll'){
var diceData = parsed.query.text.split('d');
var echoChannel = parsed.query.channel_id;
var numDice = parseInt(diceData[0] || 1, 10);
var diceType = parseInt(diceData[1], 10);
var results = [];
var roll = 0;
console.log('request', req.url);
if(!isNaN(numDice) && !isNaN(diceType)){
console.log('valid request, rolling dice');
numDice = numDice > 10 ? 10 : numDice;
diceType = diceType > 20 ? 20 : diceType;
for(var i = 0; i < numDice; i++){
roll = rollDie(diceType);
results.push(roll);
}
}
var total = results.reduce(function(a,r){ return a += r}, 0);
var output = JSON.stringify({
text: diceData.join('d')+': '+total+'; '+results.join(' '),
username: 'dungeonmaster',
icon_emoji: ':dm:',
channel: echoChannel
});
console.log('sending to webhook', output);
var post = https.request({
host: slackHost,
path: '/services/hooks/incoming-webhook?token='+slackToken,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': output.length
}
}, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log('response', chunk);
});
});
post.write(output);
post.end();
res.end('');
} else {
res.end('nope');
}
});
server.listen(port, ip);
console.log('listening on', ip+':'+port)
}
if(!module.parent){
argv = minimist(process.argv.slice(2));
host = argv.host || host;
port = argv.port || port;
groupRestrict = argv.group || groupRestrict;
slackHost = argv.slack || slackHost;
slackToken = argv.token || slackToken;
if(typeof slackToken === 'undefined' || typeof slackHost === 'undefined'){
console.log('You need a slack token and a slack hostname to continue');
}
startRollServer(port, host, slackToken, slackHost, groupRestrict);
}