forked from TalkTakesTime/Pokemon-Showdown-Bot
-
Notifications
You must be signed in to change notification settings - Fork 3
/
parser.ts
619 lines (579 loc) · 23.1 KB
/
parser.ts
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
/**
* This is the file where commands get parsed
*
* 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
*/
import {Config, send} from './main'
import {Room, getRoom, addRoom, joinRooms} from './rooms'
import {isEmpty, toId, info, cmdr, error, ok} from './utils'
import {User, self, getUser, addUser} from './users'
import commands from './commands'
import {writeFile, rename} from 'fs'
import {request as httpRequest} from 'http'
import {request as httpsRequest, get as httpsGet} from 'https'
import {parse} from 'url'
const ACTION_COOLDOWN = 3 * 1000
const FLOOD_MESSAGE_NUM = 5
const FLOOD_PER_MSG_MIN = 500 // this is the minimum time between messages for legitimate spam. It's used to determine what "flooding" is caused by lag
const FLOOD_MESSAGE_TIME = 6 * 1000
const MIN_CAPS_LENGTH = 12
const MIN_CAPS_PROPORTION = 0.8
// TODO: move to rooms.js
// TODO: store settings by room, not command/blacklists
export let settings: any
try {
settings = require('./settings')
} catch (e) {} // file doesn't exist [yet]
if (!settings) settings = {}
const actionUrl = parse('https://play.pokemonshowdown.com/~~' + Config.serverid + '/action.php')
// TODO: handle chatdata in users.js
export const chatData: any = {}
// TODO: handle blacklists in rooms.js
const blacklistRegexes: {[roomid: string]: RegExp} = {}
const rawCommands: {[name: string]: (spl: string[], room?: Room, message?: string) => boolean} = {
challstr(spl: string[], room?: Room, message?: string) {
info('received challstr, logging in...')
const id = spl[2]
const str = spl[3]
const requestOptions = {
hostname: actionUrl.hostname,
port: +actionUrl.port,
path: actionUrl.pathname,
agent: false,
method: 'GET',
headers: {}
}
let data: string
if (!Config.pass) {
requestOptions.path += '?act=getassertion&userid=' + toId(Config.nick) + '&challengekeyid=' + id + '&challenge=' + str
} else {
requestOptions.method = 'POST'
data = 'act=login&name=' + Config.nick + '&pass=' + Config.pass + '&challengekeyid=' + id + '&challenge=' + str
requestOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length
}
}
const req = httpsRequest(requestOptions, res => {
res.setEncoding('utf8')
let data = ''
res.on('data', (chunk: string) => {
data += chunk
})
res.on('end', () => {
if (data === ';') {
error('failed to log in; nick is registered - invalid or no password given')
process.exit(-1)
}
if (data.length < 50) {
error('failed to log in: ' + data)
process.exit(-1)
}
if (data.indexOf('heavy load') !== -1) {
error('the login server is under heavy load; trying again in one minute')
setTimeout(() => parseMessage(message), 60 * 1000)
return
}
if (data.substr(0, 16) === '<!DOCTYPE html>') {
error('Connection error 522; trying again in one minute')
setTimeout(() => parseMessage(message), 60 * 1000)
return
}
try {
const parsedData = JSON.parse(data.substr(1))
if (parsedData.actionsuccess) {
data = parsedData.assertion
} else {
error('could not log in; action was not successful: ' + JSON.stringify(data))
process.exit(-1)
}
} catch (e) {}
send('|/trn ' + Config.nick + ',0,' + data)
})
})
req.on('error', (err: Error) => {
error('login error: ' + err.stack)
})
if (data) req.write(data)
req.end()
return true
},
updateuser(spl: string[]) {
if (spl[2] !== Config.nick) return
if (spl[3] !== '1') {
error('failed to log in, still guest')
process.exit(-1)
}
ok('logged in as ' + spl[2])
send('|/blockchallenges')
if (Config.rooms || Config.privaterooms) {
joinRooms()
}
else {
// Receive list of rooms the bot is auth in.
send('|/userauth')
}
if (!Config.rooms) Config.rooms = []
if (!Config.privaterooms) Config.privaterooms = []
if (settings.blacklist) {
const blacklist = settings.blacklist
for (const room in blacklist) {
updateBlacklistRegex(room)
}
}
setInterval(cleanChatData, 30 * 60 * 1000)
return true
},
c(spl: string[], room: Room) {
const username = spl[2]
const user = getUser(username)
if (!user) return false // various "chat" responses contain other data
if (user === self) return false
if (isBlacklisted(user.id, room.id)) say(room, '/roomban ' + user.id + ', Blacklisted user')
const message = spl.slice(3).join('|')
if (!user.hasRank(room.id, '%')) processChatData(user.id, room.id, message)
processChatMessage(message, user, room)
return true
},
'c:'(spl: string[], room: Room) {
const username = spl[3]
const user = getUser(username)
if (!user) return false // various "chat" responses contain other data
if (user === self) return false
if (isBlacklisted(user.id, room.id)) say(room, '/roomban ' + user.id + ', Blacklisted user')
const message = spl.slice(4).join('|')
updateSeen(user.id, 'c', room.id)
if (!user.hasRank(room.id, '%')) processChatData(user.id, room.id, message, +spl[2] * 1000)
processChatMessage(message, user, room)
return true
},
pm(spl: string[]) {
const username = spl[2]
const user = getUser(username) || addUser(username)
const group = username.charAt(0)
if (user === self) return false
const message = spl.slice(4).join('|')
const inviteCommand = '/invite '
if (message.slice(0, inviteCommand.length) === inviteCommand && user.hasRank(group, '%') &&
!(toId(message.substr(8)) === 'lobby' && Config.serverid === 'showdown')) {
return send('|/join ' + message.substr(8))
}
const isCommand = processChatMessage(message, user, user)
if (!isCommand) {
unrecognizedCommand(message, user)
}
return true
},
N(spl: string[], room: Room) {
const username = spl[2]
const oldid = spl[3]
const user = room.onRename(username, oldid)
if (isBlacklisted(user.id, room.id)) say(room, '/roomban ' + user.id + ', Blacklisted user')
updateSeen(oldid, spl[1], user.id)
return true
},
j(spl: string[], room: Room) {
const username = spl[2]
const user = room.onJoin(username, username.charAt(0))
if (user === self) return false
if (isBlacklisted(user.id, room.id)) say(room, '/roomban ' + user.id + ', Blacklisted user')
updateSeen(user.id, spl[1], room.id)
return true
},
J(spl: string[], room: Room) {
this.j(spl, room)
return true
},
l(spl: string[], room: Room) {
const username = spl[2]
const user = room.onLeave(username)
if (user) {
if (user === self) return false
updateSeen(user.id, spl[1], room.id)
} else {
updateSeen(toId(username), spl[1], room.id)
}
return true
},
L(spl: string[], room: Room) {
this.l(spl, room)
return true
},
popup(spl: string[], room: Room) {
const parts = spl.slice(2).join('|').split('||||')
if (!/ auth:$/.test(parts[0])) return
Config.privaterooms = []
for (let i = 1; i < parts.length; i++) {
const part = parts[i]
const roomAuthMessage = "Room auth: "
const privateRoomAuthMessage = "Private room auth: "
const hiddenRoomAuthMessage = "Hidden room auth: "
const globalAuthMessage = "Global auth: "
if (part.slice(0, roomAuthMessage.length) === roomAuthMessage) {
Config.rooms = part.slice(roomAuthMessage.length).split(', ').map(toId)
} else if (part.slice(0, privateRoomAuthMessage.length) === privateRoomAuthMessage) {
Config.privaterooms.push(...part.slice(privateRoomAuthMessage.length).split(', '))
} else if (part.slice(0, hiddenRoomAuthMessage.length) === hiddenRoomAuthMessage) {
Config.privaterooms.push(...part.slice(hiddenRoomAuthMessage.length).split(', '))
} else if (part.slice(0, globalAuthMessage.length) === globalAuthMessage) {
if (part.slice(globalAuthMessage.length) !== '+') {
throw new Error("This bot doesn't support global staff promotions")
}
}
Config.privaterooms = Config.privaterooms.map(toId)
}
joinRooms()
return true
},
}
export function parseData(data: string) {
splitMessage(data)
}
function splitMessage(message: string) {
if (!message) return
let room: Room = null
if (message.indexOf('\n') < 0) {
parseMessage(message, room)
return
}
const spl = message.split('\n')
if (spl[0].charAt(0) === '>') {
if (spl[1].substr(1, 10) === 'tournament') return false
const roomid = spl.shift().substr(1)
room = getRoom(roomid)
if (spl[0].substr(1, 4) === 'init') {
const users = spl[2].substr(7)
room = addRoom(roomid, (Config.rooms || []).indexOf(roomid) === -1)
room.onUserlist(users)
ok('joined ' + room.id)
return
}
}
for (let i = 0, len = spl.length; i < len; i++) {
parseMessage(spl[i], room)
}
}
function parseMessage(message: string, room?: Room) {
const spl = message.split('|')
const command = spl[1]
if (rawCommands[command]) {
rawCommands[command](spl, room, message)
}
}
function processChatMessage(message: string, user: User, room: Room) {
const cmdrMessage = '["' + room.id + '|' + user.name + '|' + message + '"]'
message = message.trim()
if (message.substr(0, Config.commandcharacter.length) !== Config.commandcharacter) return false
message = message.substr(Config.commandcharacter.length)
const index = message.indexOf(' ')
let arg = ''
let cmd = message
if (index > -1) {
cmd = cmd.substr(0, index)
arg = message.substr(index + 1).trim()
}
if (commands[cmd]) {
let failsafe = 0
while (typeof commands[cmd] !== "function" && failsafe++ < 10) {
cmd = <string> commands[cmd]
}
if (typeof commands[cmd] === "function") {
cmdr(cmdrMessage)
;(<(arg: string, user: User, room: Room) => void> commands[cmd])(arg, user, room)
} else {
error("invalid command type for " + cmd + ": " + (typeof commands[cmd]))
}
}
return true
}
function say(target: Room, text: string) {
const targetId = target.id
if (getRoom(targetId)) {
send((targetId !== 'lobby' ? targetId : '') + '|' + text)
} else {
send('|/pm ' + targetId + ', ' + text)
}
}
function isBlacklisted(userid: string, roomid: string) {
const blacklistRegex = blacklistRegexes[roomid]
return blacklistRegex && blacklistRegex.test(userid)
}
export function blacklistUser(userid: string, roomid: string) {
const blacklist = settings.blacklist || (settings.blacklist = {})
if (blacklist[roomid]) {
if (blacklist[roomid][userid]) return false
} else {
blacklist[roomid] = {}
}
blacklist[roomid][userid] = 1
updateBlacklistRegex(roomid)
return true
}
export function unblacklistUser(userid: string, roomid: string) {
const blacklist = settings.blacklist
if (!blacklist || !blacklist[roomid] || !blacklist[roomid][userid]) return false
delete blacklist[roomid][userid]
if (isEmpty(blacklist[roomid])) {
delete blacklist[roomid]
delete blacklistRegexes[roomid]
} else {
updateBlacklistRegex(roomid)
}
return true
}
function updateBlacklistRegex(roomid: string) {
const blacklist = settings.blacklist[roomid]
const buffer: string[] = []
for (const entry in blacklist) {
if (entry.startsWith('/') && entry.endsWith('/i')) {
buffer.push(entry.slice(1, -2))
} else {
buffer.push('^' + entry + '$')
}
}
blacklistRegexes[roomid] = new RegExp(buffer.join('|'), 'i')
}
export function uploadToHastebin(toUpload: string, callback: (result: string) => void) {
if (typeof callback !== 'function') return false
const reqOpts = {
hostname: 'hastebin.com',
method: 'POST',
path: '/documents'
}
const req = httpRequest(reqOpts, function (res) {
res.on('data', (chunk: string) => {
// CloudFlare can go to hell for sending the body in a header request like this
if (typeof chunk === 'string' && chunk.substr(0, 15) === '<!DOCTYPE html>') return callback('Error uploading to Hastebin.')
const filename = JSON.parse(chunk.toString()).key
callback('http://hastebin.com/raw/' + filename)
})
})
req.on('error', (e: Error) => {
callback('Error uploading to Hastebin: ' + e.message)
})
req.write(toUpload)
req.end()
}
function processChatData(userid: string, roomid: string, msg: string, now = Date.now()) {
// NOTE: this is still in early stages
msg = msg.trim().replace(/[ \u0000\u200B-\u200F]+/g, ' ') // removes extra spaces and null characters so messages that should trigger stretching do so
if (!chatData[userid]) chatData[userid] = {
zeroTol: 0,
lastSeen: '',
seenAt: now
}
const userData = chatData[userid]
if (!userData[roomid]) userData[roomid] = {
times: [],
points: 0,
lastAction: 0
}
const roomData = userData[roomid]
roomData.times.push(now)
// this deals with punishing rulebreakers, but note that the bot can't think, so it might make mistakes
if (Config.allowmute && self.hasRank(roomid, '%') && Config.whitelist.indexOf(userid) < 0) {
const useDefault = !(settings.modding && settings.modding[roomid])
let pointVal = 0
let muteMessage = ''
const modSettings = useDefault ? null : settings.modding[roomid]
// moderation for banned words
if ((useDefault || !settings.banword[roomid]) && pointVal < 2) {
const bannedPhraseSettings = settings.bannedphrases
const bannedPhrases = !!bannedPhraseSettings ? (Object.keys(bannedPhraseSettings[roomid] || {})).concat(Object.keys(bannedPhraseSettings.global || {})) : []
for (let bannedPhrase of bannedPhrases) {
if (msg.toLowerCase().indexOf(bannedPhrase) > -1) {
pointVal = 2
muteMessage = ', Automated response: your message contained a banned phrase'
break
}
}
}
// moderation for flooding (more than x lines in y seconds)
const times = roomData.times
const timesLen = times.length
const isFlooding = (timesLen >= FLOOD_MESSAGE_NUM && (now - times[timesLen - FLOOD_MESSAGE_NUM]) < FLOOD_MESSAGE_TIME &&
(now - times[timesLen - FLOOD_MESSAGE_NUM]) > (FLOOD_PER_MSG_MIN * FLOOD_MESSAGE_NUM))
if ((useDefault || !('flooding' in modSettings)) && isFlooding) {
if (pointVal < 2) {
pointVal = 2
muteMessage = ', Automated response: flooding'
}
}
// moderation for caps (over x% of the letters in a line of y characters are capital)
const capsMatch = msg.replace(/[^A-Za-z]/g, '').match(/[A-Z]/g)
if ((useDefault || !('caps' in modSettings)) && capsMatch && toId(msg).length > MIN_CAPS_LENGTH && (capsMatch.length >= ~~(toId(msg).length * MIN_CAPS_PROPORTION))) {
if (pointVal < 1) {
pointVal = 1
muteMessage = ', Automated response: caps'
}
}
// moderation for stretching (over x consecutive characters in the message are the same)
const stretchMatch = /(.)\1{7,}/gi.test(msg) || /(..+)\1{4,}/gi.test(msg) // matches the same character (or group of characters) 8 (or 5) or more times in a row
if ((useDefault || !('stretching' in modSettings)) && stretchMatch) {
if (pointVal < 1) {
pointVal = 1
muteMessage = ', Automated response: stretching'
}
}
// moderation for group chat links
const groupChatMatch = /(?:\bplay\.pokemonshowdown\.com\/|\bpsim\.us\/|<<)groupchat-/i.test(msg);
if ((useDefault || !('groupchat' in modSettings)) && groupChatMatch) {
if (pointVal < 1) {
pointVal = 1
muteMessage = ', Automated response: groupchat links'
}
}
if (pointVal > 0 && now - roomData.lastAction >= ACTION_COOLDOWN) {
const room = getRoom(roomid)
if (roomid === 'japanese') {
if ((<any> Array).from(room.users).find(([name, rank]) => name !== 'usainbot' && ' +!‽'.indexOf(rank) === -1)) {
pointVal += 1
}
}
let cmd = 'mute'
// defaults to the next punishment in Config.punishVals instead of repeating the same action (so a second warn-worthy
// offence would result in a mute instead of a warn, and the third an hourmute, etc)
if (roomData.points >= pointVal && pointVal < 4) {
roomData.points++
cmd = Config.punishvals[roomData.points] || cmd
} else { // if the action hasn't been done before (is worth more points) it will be the one picked
cmd = Config.punishvals[pointVal] || cmd
roomData.points = pointVal // next action will be one level higher than this one (in most cases)
}
// if the bot has % and not @, it will default to hourmuting as its highest level of punishment instead of roombanning
if (roomData.points >= 4 && !self.hasRank(roomid, '@')) cmd = 'hourmute'
if (userData.zeroTol > 4) { // if zero tolerance users break a rule they get an instant roomban or hourmute
muteMessage = ', Automated response: zero tolerance user'
cmd = self.hasRank(roomid, '@') ? 'roomban' : 'hourmute'
}
if (roomData.points > 1) userData.zeroTol++ // getting muted or higher increases your zero tolerance level (warns do not)
roomData.lastAction = now
say(room, '/' + cmd + ' ' + userid + muteMessage)
}
}
}
function cleanChatData() {
for (const user in chatData) {
for (const room in chatData[user]) {
const roomData = chatData[user][room]
if (!roomData) continue
if (!roomData.times || !roomData.times.length) {
delete chatData[user][room]
continue
}
const newTimes: number[] = []
const now = Date.now()
const times = roomData.times
for (let time of times) {
if (now - time < 5 * 1000) newTimes.push(time)
}
newTimes.sort(function (a, b) {
return a - b
})
roomData.times = newTimes
if (roomData.points > 0 && roomData.points < 4) roomData.points--
}
}
}
function updateSeen(user: string, type: string, detail: string) {
if (type !== 'n' && Config.rooms.indexOf(detail) < 0 || Config.privaterooms.indexOf(detail) > -1) return
const now = Date.now()
if (!chatData[user]) chatData[user] = {
zeroTol: 0,
lastSeen: '',
seenAt: now
}
if (!detail) return
const userData = chatData[user]
let msg = ''
switch (type) {
case 'j':
case 'J':
msg += 'joining '
break
case 'l':
case 'L':
msg += 'leaving '
break
case 'c':
case 'c:':
msg += 'chatting in '
break
case 'N':
msg += 'changing nick to '
if (detail.charAt(0) !== ' ') detail = detail.substr(1)
break
}
msg += detail.trim() + '.'
userData.lastSeen = msg
userData.seenAt = now
}
export function getTimeAgo(time: number) {
time = ~~((Date.now() - time) / 1000)
const seconds = time % 60
const times: string[] = []
if (seconds) times.push(seconds + (seconds === 1 ? ' second': ' seconds'))
if (time >= 60) {
time = ~~((time - seconds) / 60)
const minutes = time % 60
if (minutes) times.unshift(minutes + (minutes === 1 ? ' minute' : ' minutes'))
if (time >= 60) {
time = ~~((time - minutes) / 60)
const hours = time % 24
if (hours) times.unshift(hours + (hours === 1 ? ' hour' : ' hours'))
if (time >= 24) {
const days = ~~((time - hours) / 24)
if (days) times.unshift(days + (days === 1 ? ' day' : ' days'))
}
}
}
if (!times.length) return '0 seconds'
return times.join(', ')
}
// Writing settings
let writing = false
let writePending = false // whether or not a new write is pending
function finishWriting() {
writing = false
if (writePending) {
writePending = false
writeSettings()
}
}
export function writeSettings() {
if (writing) {
writePending = true
return
}
writing = true
const data = JSON.stringify(settings)
writeFile('settings.json.0', data, function () {
// rename is atomic on POSIX, but will throw an error on Windows
rename('settings.json.0', 'settings.json', function (err) {
if (err) {
// This should only happen on Windows.
writeFile('settings.json', data, finishWriting)
return
}
finishWriting()
})
})
}
function unrecognizedCommand(message: string, user: User) {
if (user.id === self.id) return
let failureMessage: string
const scavengers = getRoom('scavengers')
if (scavengers && scavengers.users.has(user.id) && /\b(?:starthunt|[hp]astebin)\b/i.test(message)) {
failureMessage = "Thank you for submitting a hunt, but I'm just a bot. Please PM some other staff member to start your hunt."
} else {
failureMessage = "Hi, " + user.name + "! I'm just a bot, for assistance, please ask another staff member."
if (Config.botguide) {
failureMessage += " Command list: " + Config.botguide
}
}
user.say(failureMessage)
}