-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdicebot.js
77 lines (61 loc) · 1.79 KB
/
dicebot.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
var request = require('request');
module.exports = function (req, res, next) {
// default roll is 2d6
var matches;
var times = 2;
var die = 6;
var rolls = [];
var total = 0;
var botPayload = {};
if (req.body.text) {
// parse roll type if specified
matches = req.body.text.match(/^(\d{1,2})d(\d{1,2})$/);
if (matches && matches[1] && matches[2]) {
times = matches[1];
die = matches[2];
} else {
// send error message back to user if input is bad
return res.status(200).send('<number>d<sides>');
}
}
// roll dice and sum
for (var i = 0; i < times; i++) {
var currentRoll = roll(1, die);
rolls.push(currentRoll);
total += currentRoll;
}
// write response message and add to payload
botPayload.text = req.body.user_name + ' rolled ' + times + 'd' + die + ':\n' +
rolls.join(' + ') + ' = *' + total + '*';
botPayload.username = 'dicebot';
botPayload.channel = req.body.channel_id;
botPayload.icon_emoji = ':game_die:';
// send dice roll
send(botPayload, function (error, status, body) {
if (error) {
return next(error);
} else if (status !== 200) {
// inform user that our Incoming WebHook failed
return next(new Error('Incoming WebHook: ' + status + ' ' + body));
} else {
return res.status(200).end();
}
});
}
function roll (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
function send (payload, callback) {
var path = process.env.INCOMING_WEBHOOK_PATH;
var uri = 'https://hooks.slack.com/services' + path;
request({
uri: uri,
method: 'POST',
body: JSON.stringify(payload)
}, function (error, response, body) {
if (error) {
return callback(error);
}
callback(null, response.statusCode, body);
});
}