This repository has been archived by the owner on May 17, 2020. It is now read-only.
forked from Slayer95/Pokemon-Showdown-Bot
-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathmain.js
217 lines (180 loc) · 5.53 KB
/
main.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
/**
* This is the main file of Pokémon Showdown Bot
*
* Some parts of this code are taken from the Pokémon Showdown server code, so
* credits also go to Guangcong Luo and other Pokémon Showdown contributors.
* https://github.com/Zarel/Pokemon-Showdown
*
* @license MIT license
*/
const MESSAGE_THROTTLE = 650;
// First dependencies and welcome message
require('babel/register')({
blacklist: [
'es6.arrowFunctions',
'es6.blockScoping',
'es6.classes',
'es6.constants',
'es6.forOf',
'es6.templateLiterals',
'regenerator'
],
optional: ['asyncToGenerator']
});
require('sugar');
global.colors = require('colors');
global.info = function (text) {
if (Config.debuglevel > 3) return;
console.log('info'.cyan + ' ' + text);
};
global.debug = function (text) {
if (Config.debuglevel > 2) return;
console.log('debug'.blue + ' ' + text);
};
global.recv = function (text) {
if (Config.debuglevel > 0) return;
console.log('recv'.grey + ' ' + text);
};
global.cmdr = function (text) { // receiving commands
if (Config.debuglevel !== 1) return;
console.log('cmdr'.grey + ' ' + text);
};
global.dsend = function (text) {
if (Config.debuglevel > 1) return;
console.log('send'.grey + ' ' + text);
};
global.error = function (text) {
console.log('error'.red + ' ' + text);
};
global.ok = function (text) {
if (Config.debuglevel > 4) return;
console.log('ok'.green + ' ' + text);
};
console.log('------------------------------------'.yellow);
console.log('| Welcome to Pokemon Showdown Bot! |'.yellow);
console.log('------------------------------------'.yellow);
console.log('');
global.toId = function (text) {
return text.toLowerCase().replace(/[^a-z0-9]/g, '');
};
global.stripCommands = function (text) {
text = text.trim();
if (text.charAt(0) === '/') return '/' + text;
if (text.charAt(0) === '!' || /^>>>? /.test(text)) return ' ' + text;
return text;
};
// Config and config.js watching...
try {
global.Config = require('./config.js');
} catch (e) {
error('config.js doesn\'t exist; are you sure you copied config-example.js to config.js?');
process.exit(-1);
}
var checkCommandCharacter = function () {
if (!/[^a-z0-9 ]/i.test(Config.commandcharacter)) {
error('invalid command character; should at least contain one non-alphanumeric character');
process.exit(-1);
}
};
checkCommandCharacter();
var fs = require('fs');
if (Config.watchconfig) {
fs.watchFile('./config.js', function (curr, prev) {
if (curr.mtime <= prev.mtime) return;
try {
delete require.cache[require.resolve('./config.js')];
Config = require('./config.js');
info('reloaded config.js');
checkCommandCharacter();
} catch (e) {}
});
}
// And now comes the real stuff...
info('starting server');
var WebSocketClient = require('websocket').client;
global.Commands = require('./commands.js').commands;
global.Users = require('./users.js');
global.Rooms = require('./rooms.js');
global.Parse = require('./parser.js').parse;
global.Connection = null;
var queue = [];
var dequeueTimeout = null;
var lastSentAt = 0;
global.send = function (data) {
if (!data || !Connection.connected) return false;
var now = Date.now();
if (now < lastSentAt + MESSAGE_THROTTLE - 5) {
queue.push(data);
if (!dequeueTimeout) {
dequeueTimeout = setTimeout(dequeue, now - lastSentAt + MESSAGE_THROTTLE);
}
return false;
}
if (!Array.isArray(data)) data = [data.toString()];
data = JSON.stringify(data);
dsend(data);
Connection.send(data);
lastSentAt = now;
if (dequeueTimeout) {
if (queue.length) {
dequeueTimeout = setTimeout(dequeue, MESSAGE_THROTTLE);
} else {
dequeueTimeout = null;
}
}
};
function dequeue() {
send(queue.shift());
}
var connect = function (retry) {
if (retry) {
info('retrying...');
}
var ws = new WebSocketClient();
ws.on('connectFailed', function (err) {
error('Could not connect to server ' + Config.server + ': ' + err.stack);
info('retrying in one minute');
setTimeout(function () {
connect(true);
}, 60000);
});
ws.on('connect', function (con) {
Connection = con;
ok('connected to server ' + Config.server);
con.on('error', function (err) {
error('connection error: ' + err.stack);
});
con.on('close', function (code, reason) {
// Is this always error or can this be intended...?
error('connection closed: ' + reason + ' (' + code + ')');
info('retrying in one minute');
for (var i in Users.users) {
delete Users.users[i];
}
Rooms.rooms.clear();
setTimeout(function () {
connect(true);
}, 60000);
});
con.on('message', function (response) {
if (response.type !== 'utf8') return false;
var message = response.utf8Data;
recv(message);
// SockJS messages sent from the server begin with 'a'
// this filters out other SockJS response types (heartbeats in particular)
if (message.charAt(0) !== 'a') return false;
Parse.data(message);
});
});
// The connection itself
var id = ~~(Math.random() * 1000);
var chars = 'abcdefghijklmnopqrstuvwxyz0123456789_';
var str = '';
for (var i = 0, l = chars.length; i < 8; i++) {
str += chars.charAt(~~(Math.random() * l));
}
var conStr = 'ws://' + Config.server + ':' + Config.port + '/showdown/' + id + '/' + str + '/websocket';
info('connecting to ' + conStr + ' - secondary protocols: ' + (Config.secprotocols.join(', ') || 'none'));
ws.connect(conStr, Config.secprotocols);
};
connect();