forked from petemcgrath/cool-guy-bot
-
Notifications
You must be signed in to change notification settings - Fork 5
/
bot.js
111 lines (99 loc) · 2.68 KB
/
bot.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
99
100
101
102
103
104
105
106
107
108
109
110
111
var HTTPS = require('https');
var botID = process.env.BOT_ID,
botCommand = /^\/roll/;
//roll
//d4, d6, d8, d10, d20
//min max
// @User rolled: val
function respond() {
var request = JSON.parse(this.req.chunks[0]);
if(request.text && botCommand.test(request.text)){
commandHandler(this, request);
} else {
console.log("don't care");
this.res.writeHead(200);
this.res.end();
}
}
function commandHandler(relThis, command){
var rollCount = 0, //command.text.split(' ')[1] ? command.text.split(' ')[1] : 1,
rollMin = 0,
rollMax = 0;
/*
Default vals
rollCount = 1; //command.text.split(' ')[1] ? command.text.split(' ')[1] : 1,
rollMin = 1;
rollMax = 100;
*/
if(!command.text.split(' ')[1]){
//Pure Roll
rollCount = 1;
rollMin = 1;
rollMax = 100;
} else if(command.text.split(' ')[1] && command.text.split(' ')[1].split('d')[1]){
//dice setup
rollCount = parseInt(command.text.split(' ')[1].split('d')[0]);
rollMin = 1;
rollMax = parseInt(command.text.split(' ')[1].split('d')[1]);
} else if(command.text.split(' ')[1] && command.text.split(' ')[2]){
//min max
rollCount = 1;
rollMin = parseInt(command.text.split(' ')[1]);
rollMax = parseInt(command.text.split(' ')[2]);
} else {
rollCount = 1;
rollMin = 0;
rollMax = 0;
}
console.log('Count: ' + rollCount + ", Min: " + rollMin + ", Max: " + rollMax);
relThis.res.writeHead(200);
postMessage(("@" + command.name + " rolled: " + roll(rollCount, rollMin, rollMax) + " [" + rollMin + "-" + rollMax + "]"), command.name, command.user_id);
relThis.res.end();
}
function roll(count, min, max){
var result = 0;
if(count === 1){
result = min + Math.floor(Math.random()*(max-min+1));
} else {
for(i = 0; i < count; i++){
result = result + (min + Math.floor(Math.random()*(max-min+1)));
}
}
return result;
}
function postMessage(message, name, id) {
var botResponse, options, body, botReq;
options = {
hostname: 'api.groupme.com',
path: '/v3/bots/post',
method: 'POST'
};
body = {
"bot_id" : botID,
"text" : message,
"attachments": [
{
"type": "mentions",
"user_ids": [id],
"loci": [
[0,name.length + 1]
]
}
]
};
botReq = HTTPS.request(options, function(res) {
if(res.statusCode == 202) {
//neat
} else {
console.log('rejecting bad status code ' + res.statusCode);
}
});
botReq.on('error', function(err) {
console.log('error posting message ' + JSON.stringify(err));
});
botReq.on('timeout', function(err) {
console.log('timeout posting message ' + JSON.stringify(err));
});
botReq.end(JSON.stringify(body));
}
exports.respond = respond;