-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcommands-guide.js
More file actions
629 lines (491 loc) · 17 KB
/
Copy pathcommands-guide.js
File metadata and controls
629 lines (491 loc) · 17 KB
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
620
621
622
623
624
625
626
627
628
629
// Interactive commands guide add-on for for Showdown-ChatBot
// ------------------------------------
// WARNING: Version 2.16.1 or greater required!
// ------------------------------------
// This addon turns the help command into an interactive guide.
// Note: The bot needs the bot rank in the server for this to work
// Note: The user who uses the command must be in the same room as the bot having the rank (unless it is a global bot)
// This add-on also adds a control panel section 'Commands Guide' to configure the guide.
'use strict';
// Set this to true if your bot is a global bot
const IS_GLOBAL_BOT = false;
// Max number of commands per page
const MAX_COMMANDS_PER_PAGE = 10;
// URL to download the official guide
const COMMANDS_GUIDE_DEFAULT_SOURCE = "https://raw.githubusercontent.com/wiki/AgustinSRG/Showdown-ChatBot/Commands-List.md";
// Auto update sync interval, in milliseconds
const AUTO_UPDATE_SYNC_INTERVAL = 24 * 60 * 60 * 1000;
const Path = require('path');
const HTTPS = require('https');
const Text = Tools('text');
const Chat = Tools('chat');
const DataBase = Tools('json-db');
function wget(url, callback) {
HTTPS.get(url, response => {
if (response.statusCode !== 200) {
if (response.statusCode === 404) {
return callback(null, new Error("404 - Not found"));
} else {
return callback(null, new Error("" + response.statusCode));
}
}
let data = '';
response.on('data', chunk => {
data += chunk;
});
response.on('end', () => {
callback(data);
});
response.on('error', err => {
callback(null, err);
});
}).on('error', err => {
callback(null, err);
});
}
class CommandsGuide {
constructor(App) {
this.app = App;
this.db = new DataBase(Path.resolve(App.confDir, "commands-guide.json"));
this.data = this.db.data;
if (!this.data.sections || !Array.isArray(this.data.sections)) {
// Default guide
this.data.sections = [];
}
this.autoUpdateTimer = null;
}
autoUpdate() {
if (!this.data.autoUpdate) {
return;
}
this.fetchDefaultCommandsGuide(true, (ok, error) => {
if (ok) {
this.app.log("[CommandsGuide] Auto-synced with the latest official commands guide.");
} else if (error) {
this.app.log("[CommandsGuide] Auto-sync failed: " + error);
}
});
}
startAutoUpdateTimer() {
if (this.autoUpdateTimer) {
clearInterval(this.autoUpdateTimer);
this.autoUpdateTimer = null;
}
this.autoUpdateTimer = setInterval(this.autoUpdate.bind(this), AUTO_UPDATE_SYNC_INTERVAL);
this.autoUpdate(); // Call autoUpdate on startup
}
stopAutoUpdateTimer() {
if (this.autoUpdateTimer) {
clearInterval(this.autoUpdateTimer);
this.autoUpdateTimer = null;
}
}
serializeCommandGuideConfig() {
let txt = '';
for (let section of this.data.sections) {
txt += '[' + section.name + ']\n\n';
for (let cmd of section.commands) {
txt += cmd.syntax + "\n";
if (cmd.description.length > 0) {
txt += cmd.description.join("\n") + "\n";
}
txt += '\n';
}
}
return txt;
}
parseCommandGuideConfig(txt) {
const lines = txt.split("\n");
const result = [];
let section = null;
let command = null;
for (let line of lines) {
line = line.trim();
if (!line) {
if (section && command) {
section.commands.push(command);
command = null;
}
continue;
}
if (!section || !command) {
if (line.charAt(0) === '[' && line.charAt(line.length - 1) === ']' && line.length > 2) {
if (section) {
result.push(section);
section = null;
}
const sectionName = line.substring(1, line.length - 1);
if (!sectionName) {
continue;
}
section = {
name: sectionName,
commands: [],
};
continue;
}
}
if (section) {
if (command) {
command.description.push(line);
} else {
command = {
syntax: line,
description: [],
};
}
}
}
if (section) {
if (command) {
section.commands.push(command);
}
result.push(section);
}
return result;
}
fetchDefaultCommandsGuide(overwrite, callback) {
wget(COMMANDS_GUIDE_DEFAULT_SOURCE, (text, err) => {
if (err) {
if (callback) {
return callback(null, "Error: " + err.message);
} else {
this.app.reportCrash(err);
return;
}
}
const lines = text.split("\n");
const result = [];
let section = null;
let command = null;
let prevLine = "";
for (let line of lines) {
line = line.trim();
if (line.substring(0, 3) === "---" && prevLine) {
if (section) {
result.push(section);
section = null;
}
section = {
name: prevLine.replace(/\sModule$/i, ""),
commands: [],
};
} else if (line.charAt(0) === "`" && section) {
const parts = line.split("|").map(p => p.trim());
const syntax = parts[0].substring(1, parts[0].length - 1);
const description = Chat.parseMessage(Text.escapeHTML(parts[1] || ""));
const permission = (parts[2] || "").split("\\")[0].trim();
const permissionIsBroadcast = (parts[2] || "").trim().split("\\")[1] === "*";
const permissionDescLine = Chat.parseMessage(Text.escapeHTML(permission === "-" ? "" : ("Required permission: " + Chat.italics(permission) + (permissionIsBroadcast ? " (for broadcasting)" : ""))));
section.commands.push({
syntax: syntax,
description: [description, permissionDescLine],
});
}
prevLine = line;
}
if (section) {
if (command) {
section.commands.push(command);
}
result.push(section);
}
if (overwrite || this.data.sections.length === 0) {
this.data.sections = result;
this.save();
}
if (callback) {
return callback("Successfully downloaded default commands guide", null);
}
});
}
getBotMessageCommand(command, room) {
const botId = Text.toId(this.app.bot.getBotNick());
const botToken = this.app.config.parser.tokens[0] || '.';
return '/msg ' + botId + ', /msgroom ' + room + ', /botmsg ' + botId + ', ' + botToken + command;
}
generateHelpPage(sectionIndex, pageIndex, room) {
let html = '<div style="padding: 0.5rem;">';
// Title
html += '<div style="text-align: center; padding-bottom: 0.5rem;">';
if (Chat.usernameColor) {
html += '<b><span style="color:' + Chat.usernameColor(this.app.bot.getBotNick()) + ';">' + Text.escapeHTML(this.app.bot.getBotNick().substring(1)) + '</span> - Commands Guide</b> ';
} else {
html += '<b>' + Text.escapeHTML(this.app.bot.getBotNick().substring(1)) + ' - Commands Guide</b> ';
}
html += '<button class="button" name="send" value="' + Text.escapeHTML(this.getBotMessageCommand("help !,close", room)) + '">Close page</button>';
html += '</div>';
// Sections menu
const sections = this.data.sections || [];
if (sections.length === 0) {
return "";
}
html += '<div style="text-align: center; line-height: 2rem;">';
for (let i = 0; i < sections.length; i++) {
if (i > 0) {
html += ' ';
}
html += '<button class="button' + (i === sectionIndex ? ' disabled' : '') + '"' + (i === sectionIndex ? ' disabled style="border-color: #ffffff;"' : '') + ' name="send" value="' + Text.escapeHTML(this.getBotMessageCommand("help !," + i, room)) + '">' + Text.escapeHTML(sections[i].name) + '</button>';
}
html += '</div>';
const section = sections[sectionIndex];
if (!section) {
return "";
}
let commands = section.commands || [];
const totalCommands = commands.length;
let totalPages = Math.ceil(totalCommands / MAX_COMMANDS_PER_PAGE) || 1;
pageIndex = Math.min(totalPages - 1, pageIndex);
commands = commands.slice(pageIndex * MAX_COMMANDS_PER_PAGE, (pageIndex + 1) * MAX_COMMANDS_PER_PAGE);
// Page menu
if (totalPages > 1) {
html += '<p>';
let pageStart = (pageIndex * MAX_COMMANDS_PER_PAGE) + 1;
let pageEnd = Math.min(((pageIndex + 1) * MAX_COMMANDS_PER_PAGE), totalCommands);
html += '<span>Commands (' + pageStart + ' - ' + pageEnd + ' / ' + totalCommands + '):</span> ';
for (let i = 0; i < totalPages; i++) {
if (i > 0) {
html += ' ';
}
html += '<button class="button' + (i === pageIndex ? ' disabled' : '') + '"' + (i === pageIndex ? ' disabled style="border-color: #ffffff;"' : '') + ' name="send" value="' + Text.escapeHTML(this.getBotMessageCommand("help !," + sectionIndex + ', ' + i, room)) + '">' + (i + 1) + '</button>';
}
html += '</p>';
}
// Info
html += '<p>Note: Arguments with <code><></code> means they are obligatory. Arguments with <code>[]</code> means they are optional.</p>';
html += '<hr />';
// Commands
for (let cmd of commands) {
html += '<p>';
html += '<code>' + Text.escapeHTML(cmd.syntax) + '</code> - ';
html += cmd.description.join('<br />');
html += '</p>';
}
html += '</div>';
return html;
}
findCommand(cmd) {
const aliasTarget = this.app.parser.data.aliases[cmd];
const sections = this.data.sections || [];
const entries = [];
for (const section of sections) {
const commands = section.commands || [];
for (const command of commands) {
const commandId = Text.toCmdId((command.syntax || "").split(" ")[0] || "");
if (commandId === cmd || (aliasTarget && commandId === aliasTarget)) {
entries.push(command);
}
}
}
return entries;
}
renderCommandsHtml(commands) {
let html = "";
for (const cmd of commands) {
html += '<p>';
html += '<code>' + Text.escapeHTML(cmd.syntax) + '</code> - ';
html += cmd.description.join('<br />');
html += '</p>';
}
return html;
}
renderCommandsText(commands) {
return "!code " + commands.map(cmd => {
return cmd.syntax + "\n" +
cmd.description.join("\n")
.replace(/<\/?((i)|(b)|(a))>/g, "")
.replace(/<a href=.+>/g, "");
}).join("\n\n");
}
save() {
this.db.write();
}
}
/* Setup function: Called on add-on installation */
exports.setup = function (App) {
const commandsGuide = new CommandsGuide(App);
if (commandsGuide.data.sections.length === 0) {
commandsGuide.fetchDefaultCommandsGuide();
}
function sendControlPanelPage(context, ok, error) {
let html = '';
html += '<script type="text/javascript">';
html += 'function confirmOverwrite() {';
html += 'var elem = document.getElementById("confirm-overwrite");';
html += 'if (elem) {';
html += 'elem.innerHTML = \'<form style="display:inline;" method="post" action="">\' +';
html += '\'Are you sure? This will overwrite your current guide. <input type="submit" name="download" value="Confirm" /></form>\';';
html += '}';
html += 'return false;';
html += '}';
html += '</script>';
html += '<h2>Command Guide</h2>';
html += '<details>';
html += '<summary><string>Click here for help on how to edit the guide</strong></summary>';
html += '<p>Each section starts with [Section name]. Then, each command has the format:</p>';
html += '<ol>';
html += '<li>First line: Command syntax</li>';
html += '<li>Following lines: Command description (HTML allowed)</li>';
html += '<li>Command are separated from each other by empty lines</li>';
html += '</ol>';
html += '<p>Example:</p>';
html += '<code style="border: solid 1px black; padding: 0.5rem;"><pre>';
html += [
'[Pokemon]',
'',
'usage <pokemon>, [tier]',
'Displays the basic usage stats of a pokemon',
'',
'usagedata <pokemon>, [tier]',
'Displays the full usage stats of a pokemon (moves, abilities, items, spreads and partners)',
'',
'usagetop [tier]',
'Displays the top most used pokemon of a tier.',
'',
'usagelink',
'Provides the usage stats link for the current month.',
'',
'[Misc]',
'',
'pick <option1>, <option2>, [...]',
'Randomly picks between 2 or more options',
'',
'randpoke',
'Picks a random Pokemon',
'',
'randmove',
'Picks a random move',
'',
'randitem',
'Picks a random item',
'',
'randability',
'Picks a random ability',
'',
'randnature',
'Picks a random nature',
'',
'randomdata',
'Shows a random !dt (Pokemon, moves, items, abilities)',
'',
].map(Text.escapeHTML).join("\n");
html += '</pre></code>';
html += '</details>';
html += '<p>Edit the guide in the following text box:</p>';
html += '<form method="post" action="">';
html += '<textarea name="data" style="width: 100%; max-width: 100ch;" rows="30">';
html += Text.escapeHTML(commandsGuide.serializeCommandGuideConfig());
html += '</textarea>';
html += '<p><input type="checkbox" name="autoupdate"' + (commandsGuide.data.autoUpdate ? ' checked="checked"' : '') + ' /> Automatically update guide every 24 hours (note: this will overwrite your previous guide, keep disabled for a custom guide).</p>';
html += '<p><input type="submit" name="save" value="Save Changes" /></p>';
html += '</form>';
html += '<p><button onclick="confirmOverwrite();">Download and use default guide</button> <span id="confirm-overwrite"></span></p>';
html += '<p>';
if (ok) {
html += '<span class="ok-msg">' + ok + '</span>';
} else if (error) {
html += '<span class="error-msg">' + error + '</span>';
}
html += '</p>';
context.endWithWebPage(html, { title: "Commands Guide" });
}
return Tools('add-on').forApp(App).install({
/* Add-on Commands (https://github.com/AgustinSRG/Showdown-ChatBot/wiki/Basic-Development-Guide#commands) */
commandsOverwrite: true,
commands: {
help: function (App) {
const botId = Text.toId(App.bot.getBotNick());
const pageId = botId + "-commandsguide";
const botGroup = this.parser.app.config.parser['bot'] || "*";
let roomWithBotRank = IS_GLOBAL_BOT ? "lobby" : "";
for (let room of Object.keys(this.parser.bot.rooms)) {
let roomData = this.parser.bot.rooms[room];
if (roomData.type !== 'chat') {
continue;
}
if (this.isGroupChat(room)) {
continue;
}
if (IS_GLOBAL_BOT || (roomData.users[botId] && roomData.users[this.byIdent.id] && roomData.users[botId].charAt(0) === botGroup)) {
roomWithBotRank = room;
break;
}
}
if (this.args[0] === "!" || !this.arg) {
if (!roomWithBotRank) {
return this.pmReply("Commands guide: https://github.com/AgustinSRG/Showdown-ChatBot/wiki/Commands-List");
}
if (this.args[1] === "close") {
this.send('/closehtmlpage ' + this.byIdent.id + ', ' + pageId, roomWithBotRank);
return;
}
const sectionIndex = Math.min(commandsGuide.data.sections.length - 1, Math.max(0, parseInt(this.args[1] || "0") || 0));
const sectionPage = Math.max(0, parseInt(this.args[2] || "0") || 0);
const html = commandsGuide.generateHelpPage(sectionIndex, sectionPage, roomWithBotRank);
if (html) {
this.send('/sendhtmlpage ' + this.byIdent.id + ', ' + pageId + ', ' + html, roomWithBotRank);
} else {
this.pmReply("The current commands guide is empty. Please contact the bot's administrator in order to configure it.");
}
} else {
const commandId = Text.toCmdId(this.arg);
const commandEntries = commandsGuide.findCommand(commandId);
if (commandEntries.length === 0) {
return this.pmReply("Could not find any documentation for the command " + Chat.code(commandId || this.arg) + ". Try using " + Chat.code(this.token + this.cmd) + " without arguments to view the commands list.");
}
this.htmlPrivateReply(commandsGuide.renderCommandsHtml(commandEntries), commandsGuide.renderCommandsText(commandEntries));
}
},
},
/* Control panel options (https://github.com/AgustinSRG/Showdown-ChatBot/wiki/Basic-Development-Guide#server-handlers) */
serverHandlersOverwrite: false,
serverHandlers: {
"cmdguide": function (context, parts) {
if (!context.user || !context.user.can('cmdguide')) {
context.endWith403();
return;
}
let ok = null, error = null;
if (context.post.save) {
let sections;
try {
sections = commandsGuide.parseCommandGuideConfig(context.post.data || "");
} catch (err) {
error = err.message;
}
const autoUpdate = !!context.post.autoupdate;
if (!error) {
commandsGuide.data.sections = sections;
commandsGuide.data.autoUpdate = autoUpdate;
commandsGuide.save();
App.logServerAction(context.user.id, "Updated Command Guide configuration");
ok = "Command Guide configuration successfully saved.";
}
} else if (context.post.download) {
commandsGuide.fetchDefaultCommandsGuide(true, function (ok2, error2) {
App.logServerAction(context.user.id, "Updated Command Guide configuration");
sendControlPanelPage(context, ok2, error2);
});
return;
}
sendControlPanelPage(context, ok, error);
},
},
/* Control panel permissions */
serverPermissionsOverwrite: false,
serverPermissions: {
"cmdguide": "Permission to modify the commands guide",
},
/* Control panel menu */
serverMenuOptionsOverwrite: false,
serverMenuOptions: {
"cmdguide": { name: "Commands Guide", url: "/cmdguide/", permission: "cmdguide", level: -3 },
},
customInstall: function () {
commandsGuide.startAutoUpdateTimer();
},
customUninstall: function () {
commandsGuide.stopAutoUpdateTimer();
},
});
};