forked from julioolvr/count-to-1000
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.js
90 lines (83 loc) · 2.87 KB
/
run.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
var WebSocket = require('ws'),
apiToken = "", //Api Token from https://api.slack.com/web (Authentication section)
whoAmIUrl = "https://slack.com/api/auth.test?token=" + apiToken,
authUrl = "https://slack.com/api/rtm.start?token=" + apiToken,
request = require("request"),
userId = '', // Id for the user the bot is posting as''
channelId = false; //'G069T2UV9'; // Id of the channel the bot is posting to
var goal = 1000;
request(whoAmIUrl, function(err, response, body) {
if (!err && response.statusCode === 200) {
body = JSON.parse(body);
userId = body.user_id;
request(authUrl, function(err, response, body) {
if (!err && response.statusCode === 200) {
var res = JSON.parse(body);
if (res.ok) {
connectWebSocket(res.url);
}
}
});
}
});
function connectWebSocket(url) {
var ws = new WebSocket(url);
var channels = {};
function channelHandler(channelId) {
var cc = channels[channelId];
if (!cc) {
cc = {
lastNumber: 0,
lastUser: "",
channelId: channelId,
handleNumber: function (message) {
if (this.timeout) {
clearTimeout(this.timeout);
}
var number = Number(message.text);
if (number && number <= this.lastNumber) {
this.lastNumber = (number == 1) ? 1 : 0;
this.lastUser = message.user;
}
else if (number) {
this.lastNumber = number;
this.lastUser = message.user;
console.log('received number:', number);
var delay = Math.pow(Math.random(), 2) * 180000 + 5000;
console.log("delay: ", delay);
this.timeout = setTimeout(this.prepareSend.bind(this), delay);
}
},
prepareSend: function() {
ws.send(JSON.stringify({ channel: this.channelId, id: 1, type: "typing" }));
console.log("start typing...");
this.timeout = setTimeout(this.sendNumber.bind(this), 3000);
},
sendNumber: function() {
this.timeout = false;
if (this.lastUser !== userId) {
this.lastNumber++;
this.lastUser = userId;
var text = this.lastNumber >= goal ? "¡Ganamooo'!" : String(this.lastNumber)
ws.send(JSON.stringify({ channel: this.channelId, id: 1, text: text, type: "message" }));
console.log("sent: ", text);
}
else {
console.log("not sent: ", this);
}
},
};
channels[channelId] = cc;
}
return cc;
}
ws.on('open', function() {
console.log('Connected');
});
ws.on('message', function(message) {
message = JSON.parse(message);
if ((!channelId || message.channel === channelId) && message.type === 'message' && message.text) {
channelHandler(message.channel).handleNumber(message);
}
});
}