-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.js
359 lines (311 loc) · 11.9 KB
/
client.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/*
* client.js: Client and connection with PS
*
* This file handles connecting to PS, loading plugins, parsing incoming messages and running commands.
*/
const WebSocketClient = require('websocket').client;
const fs = require('fs');
const request = require('request');
const config = require('./config');
const utils = require('./utils');
const BASE_RECONNECT_TIME = 2;
const ACTION_URL = 'http://play.pokemonshowdown.com/action.php';
const RANKS = ['+', '%', '@', '*', '#', '&', '~'];
class CommandWrapper {
constructor(send, commands, userlists, gameRooms, gameClasses) {
this.send = send;
this.commands = commands;
this.userlists = userlists;
this.gameRooms = gameRooms;
this.gameClasses = gameClasses;
}
hasPerms(rank) {
return RANKS.indexOf(this.rank) >= RANKS.indexOf(rank);
}
sendPM(userid, message) {
this.send(`/pm ${userid}, ${message}`);
}
// Checks `roomid` to see if the current game within it is `gameId`. You should use
// this if you only need to check whether or not a game exists; use CommandWrapper#findCurrentGame
// if you need verification AND the game object.
currentGame(roomid, gameId) {
return this.gameRooms[roomid] && this.gameRooms[roomid].nameId === gameId;
}
// This allows games to have PM commands by returning the game object (which is
// already set to the roomid itself) and the roomid in which the game is occurring
// if the game's ID is the same as specified.
findCurrentGame(gameId) {
if (!this.gameClasses.has(gameId)) return []; // Prevent needless searching
for (const roomid in this.gameRooms) {
if (this.gameRooms[roomid].nameId === gameId) {
return [this.gameRooms[roomid], roomid];
}
}
return [];
}
newGame(roomid, gameId, options) {
// Can't use `this.currentGame` here since that will return false if there is a game that isn't `gameId`,
// and we don't want multiple games running at the same time in the same room.
if (this.gameRooms[roomid]) return this.send(`There is already an active game of ${this.gameRooms[roomid].name}.`);
if (!this.gameClasses.has(gameId)) return this.send(`Invalid game. Use \`\`${config.commandToken}game\`\` to see the list of games.`);
if (!options.send) options.send = (message, isAnnouncement) => this.send(`${isAnnouncement ? "/wall " : ""}${message}`);
if (!options.sendPM) options.sendPM = this.sendPM;
this.gameRooms[roomid] = new (this.gameClasses.get(gameId))(roomid, options);
this.gameRooms[roomid].signups();
}
async run(commandName, rank, userid, roomid, message) {
// Get highest auth if used in PM.
if (!roomid) {
for (const room of config.rooms) {
if (this.userlists[room] && this.userlists[room][userid]) {
const roomrank = this.userlists[room][userid][0];
if (RANKS.indexOf(roomrank) > RANKS.indexOf(rank)) rank = roomrank;
}
}
}
this.rank = config.owners.includes(userid) ? '~' : rank;
this.command = commandName;
let command = this.commands.get(commandName);
command.apply(this, [userid, roomid, message]).catch(e => {
utils.errorMsg(`An error occurred within the ${commandName} command: ${e.stack}`);
});
}
}
class Client {
constructor(url) {
this.url = url;
this.client = new WebSocketClient();
this.reconnects = 0;
this.userlists = {};
this.joinHandlers = [];
this.leaveHandlers = [];
this.initHandlers = [];
this.commands = new Map();
this.gameRooms = {};
this.gameClasses = new Map();
this.client.on('connectFailed', error => {
this.reconnects++;
utils.errorMsg(`Connection failed with error: ${error}. Retrying in ${BASE_RECONNECT_TIME ** this.reconnects} seconds.`);
setTimeout(this.connect, (BASE_RECONNECT_TIME ** this.reconnects) * 1000);
});
this.client.on('connect', connection => {
this.connection = connection;
this.reconnects = 0;
utils.statusMsg('WebSocket Client connected successfully.');
connection.on('error', e => {
utils.errorMsg(`Connection error: ${e.stack}`);
// `close` is emitted directly after `error`, so we don't need to handle reconnecting here
});
connection.on('close', () => {
this.reconnects++;
utils.errorMsg(`Connection closed. Reconnecting in ${BASE_RECONNECT_TIME ** this.reconnects} seconds.`);
setTimeout(this.connect, (BASE_RECONNECT_TIME ** this.reconnects) * 1000);
});
connection.on('message', message => {
this.parse(message.utf8Data);
});
});
this.connect();
}
connect() {
utils.statusMsg(`Attempting to connect to ${this.url}...`);
this.client.connect(this.url);
}
parse(message) {
if (!message) return;
let split = message.split('|');
let roomid = utils.toRoomId(split[0]) || 'lobby';
let userid = utils.toId(config.username);
let username, oldUsername;
switch (split[1]) {
case 'challstr':
let challstr = split.slice(2).join('|');
request.post(ACTION_URL, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `act=login&name=${config.username}&pass=${config.password}&challstr=${challstr}`,
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
if (body[0] === ']') {
try {
body = JSON.parse(body.substr(1));
} catch (e) {
utils.errorMsg(`Invalid JSON response from server: ${body}. Exiting.`);
process.exit(1);
}
if (body.assertion && body.assertion[0] !== ';') {
this.init();
this.send('', `/trn ${config.username},0,${body.assertion}`);
} else {
utils.errorMsg(`Something went wrong logging in. Assertion: ${body.assertion.slice(2)} Exiting.`);
process.exit(1);
}
} else {
utils.errorMsg(`Something went wrong with a request (status code ${response.statusCode})${error ? `: ${error}` : ''}. Exiting.`);
process.exit(1);
}
}
});
break;
case 'updateuser':
if (utils.toId(split[2]) !== userid) return false;
utils.statusMsg(`Successfully set up and logged in as ${split[2]}.`);
break;
case 'J':
case 'j':
username = split[2].slice(1).split('@')[0];
if (!this.userlists[roomid]) this.userlists[roomid] = {}; // failsafe, is this even needed? im paranoid and shit
this.userlists[roomid][utils.toId(username)] = [split[2][0], username];
Promise.all(this.joinHandlers.map(handler => handler.apply(this, [utils.toId(username), roomid]))).catch(e => utils.errorMsg(`Failed to parse join handler: ${e}`));
break;
case 'L':
case 'l':
username = split[2].slice(1).split('@')[0];
delete this.userlists[roomid][utils.toId(username)];
// if the user leaves while in a game, jsplit[2].slice(1).split('@')[0]ust make them leave here
if (this.gameRooms[roomid]) {
let game = this.gameRooms[roomid];
if (game.players.includes(utils.toId(username))) game.userLeave(utils.toId(username));
}
Promise.all(this.leaveHandlers.map(handler => handler.apply(this, [utils.toId(username), roomid]))).catch(e => utils.errorMsg(`Failed to parse leave handler: ${e}`));
break;
case 'N':
case 'n':
username = split[2].slice(1).split('@')[0];
oldUsername = split[3].slice(1).split('@')[0];
if (this.userlists[roomid]) {
delete this.userlists[roomid][utils.toId(oldUsername)];
} else {
this.userlists[roomid] = {}; // paranoia again.
}
this.userlists[roomid][utils.toId(username)] = [split[2][0], username];
break;
case 'noinit':
case 'deinit':
utils.errorMsg(`Attempted to join the room '${roomid}', but failed to do so.`);
break;
case 'init':
let list = {};
for (let str of split[6].trim().split(',').slice(1)) {
let username = str.slice(1).split('@')[0];
list[utils.toId(username)] = [str[0], username];
}
this.userlists[roomid] = list;
Promise.all(this.initHandlers.map(handler => handler.apply(this, [roomid]))).catch(e => utils.errorMsg(`Failed to parse init handler: ${e}`));
break;
case 'pm':
if (utils.toId(split[2]) === userid) return false;
this.parseMessage(split[2], null, split.slice(4).join('|').trim()).catch(e => utils.errorMsg(`Failed to parse |pm| message: ${e}`));
break;
case 'c':
if (utils.toId(split[2]) === userid) return false;
this.parseMessage(split[2], roomid, split.slice(3).join('|').trim()).catch(e => utils.errorMsg(`Failed to parse |c| message: ${e}`));
break;
case 'c:':
if (utils.toId(split[3]) === userid) return false;
this.parseMessage(split[3], roomid, split.slice(4).join('|').trim()).catch(e => utils.errorMsg(`Failed to parse |c:| message: ${e}`));
break;
}
}
init() {
this.send('', `/avatar ${config.avatar}`);
this.send('', `/autojoin ${config.rooms.join(',')}`);
let core = require('./core-commands');
for (let c in core.commands) {
this.commands.set(c, core.commands[c]);
}
for (let a in core.aliases) {
this.commands.set(a, core.commands[core.aliases[a]]);
}
fs.readdirSync('./plugins')
.filter(file => file.endsWith('.js'))
.forEach(file => {
let plugin = require(`./plugins/${file}`);
if (plugin.onInit) {
this.initHandlers.push(plugin.onInit);
}
if (plugin.onJoin) {
this.joinHandlers.push(plugin.onJoin);
}
if (plugin.onLeave) {
this.leaveHandlers.push(plugin.onLeave);
}
if (plugin.commands) {
for (let c in plugin.commands) {
this.commands.set(c, plugin.commands[c]);
}
if (plugin.aliases) {
for (let a in plugin.aliases) {
this.commands.set(a, plugin.commands[plugin.aliases[a]]);
}
}
}
if (plugin.games) {
for (let id in plugin.games) {
this.gameClasses.set(id, plugin.games[id]);
}
}
});
}
send(room, message) {
return this.connection.send(`${room}|${message}`);
}
sendPM(userid, message) {
return this.connection.send(`|/pm ${userid}, ${message}`);
}
async parseMessage(user, roomid, message) {
let userid = utils.toId(user);
if (!message.startsWith(config.commandToken)) {
if (roomid) {
// Parse game joins/leaves via "/me in" or "/me out"
let game = this.gameRooms[roomid];
if (!game) return;
if (message.startsWith("/me ")) {
let meCommand = utils.toId(message.slice(4));
if (meCommand === "in") {
game.userJoin(userid);
} else if (meCommand === "out") {
game.userLeave(userid);
}
}
return;
}
if (message.startsWith("/invite ")) {
// Since subroom groupchats use the format "groupchat-MAINROOMID-NAME",
// we make sure that the bot is located within the main room and that the user
// who is inviting the bot is within the main room and has auth.
let toJoin = utils.toRoomId(message.slice(8));
if (toJoin.startsWith("groupchat-") && this.userlists[toJoin.split('-')[1]] && this.userlists[toJoin.split('-')[1]][userid] && this.userlists[toJoin.split('-')[1]][userid][0] !== ' ') {
this.send('', `/join ${toJoin}`);
}
return;
}
this.sendPM(userid, "Hi, I'm only a bot. Please PM another staff member for assistance.");
utils.pmMsg(`PM received from ${userid}: ${message}`);
return;
}
let [commandName, ...words] = message.slice(config.commandToken.length).split(' ');
commandName = utils.toId(commandName);
if (!this.commands.has(commandName)) {
if (!roomid) {
let matches = Array.from(this.commands).map(([name]) => name).sort((a, b) => utils.levenshtein(commandName, a) - utils.levenshtein(commandName, b));
this.sendPM(userid, `Invalid command. Did you mean ${utils.arrayToPhrase(matches.slice(0, 3), 'or')}?`);
}
return;
}
// The closure allows us to optionally specify an alternate room
// to send to. If we only specify a message, then it will either
// default to either the room it was sent to or the sender's PMs.
let send = (message, room = roomid) => {
if (room) {
this.send(room, message);
} else {
this.sendPM(userid, message);
}
};
let wrapper = new CommandWrapper(send, this.commands, this.userlists, this.gameRooms, this.gameClasses);
await wrapper.run(commandName, user[0], userid, roomid, words.join(' '));
}
}
module.exports = new Client(`ws://${config.host}:${config.port}/showdown/websocket`);