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
|
import Translation from '@util/Translation';
import { IContact } from './Contact.interface';
import MultiUserContact from './MultiUserContact';
export class OnlyGroupChatError extends Error {
constructor() {
super(Translation.t('Command_only_available_in_groupchat'));
}
}
export class ArgumentError extends Error {
constructor() {
super(Translation.t('Wrong_number_of_arguments'));
}
}
export type CommandAction = (
args: string[],
contact: IContact | MultiUserContact,
message?: string
) => Promise<boolean>;
export default class CommandRepository {
private commands: {
[command: string]: {
action: CommandAction;
description: string;
category: string;
};
} = {};
public register(command: string, action: CommandAction, description: string, category: string = 'general') {
if (command && !this.commands[command.toLowerCase()]) {
this.commands[command.toLowerCase()] = {
action,
description,
category,
};
}
}
public execute(message: string, contact: IContact | MultiUserContact) {
let args = message.split(' ').filter(arg => !!arg);
if (args.length === 0) {
return Promise.resolve(false);
}
let command = args[0].toLowerCase();
if (!this.commands[command]) {
return Promise.resolve(false);
}
return this.commands[command].action(args, contact, message);
}
public getHelp() {
let help: {
[category: string]: { command: string; description: string }[];
} = {};
Object.keys(this.commands)
.sort()
.forEach(id => {
let command = this.commands[id];
if (!command.description) {
return;
}
if (!help[command.category]) {
help[command.category] = [];
}
help[command.category].push({
command: id,
description: command.description,
});
});
return Object.keys(help)
.sort()
.map(category => ({
label: 'cmd_category_' + category,
commands: help[category],
}));
}
}
|