@mushinjs/plugin-bots 0.0.0-stage → 0.2.0-next.20261113103537

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Commands such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the
3
+ * built-in `/help` all register commands per bot, so help menus, the Agent and the overview can
4
+ * list them in one place.
5
+ */
6
+ import { Segment } from "@mushinjs/core";
7
+ /**
8
+ * What an argument takes: `text` a word (or the rest, for the last one), `number` a number,
9
+ * `boolean` yes or no (是/否, true/false, on/off, 1/0), `user` an @mention or a user id, `choice` one
10
+ * of `choices`.
11
+ */
12
+ export type CommandArgType = 'text' | 'number' | 'boolean' | 'user' | 'choice';
13
+ /** One argument of a command, in the order they are written. */
14
+ export interface CommandArg {
15
+ name: string;
16
+ type: CommandArgType;
17
+ /** Can be left out; then `default` is used, or the argument is missing from the values. */
18
+ optional?: boolean;
19
+ /** Takes the rest of the message. Only text arguments can; the last text argument always does. */
20
+ rest?: boolean;
21
+ default?: string | number | boolean;
22
+ /** For `choice` arguments. */
23
+ choices?: string[];
24
+ /** Shown in the usage reply and the editor. */
25
+ description?: string;
26
+ }
27
+ export type ArgValue = string | number | boolean;
28
+ export interface CommandDef {
29
+ /** Without the prefix, e.g. `score`. */
30
+ name: string;
31
+ aliases?: string[];
32
+ description?: string;
33
+ /** What follows the name, in order. */
34
+ args?: CommandArg[];
35
+ /** Prefixes of this command only, e.g. `['#']`; empty or missing uses the bot's. */
36
+ prefixes?: string[];
37
+ /** Left out of `/help`. */
38
+ hidden?: boolean;
39
+ /** Who may run it: `admin` lets admins and masters, `master` only masters. Needs the permissions plugin. */
40
+ permission?: 'all' | 'admin' | 'master';
41
+ /** The same as `permission`, as a role: `{ role: 'admin' }`. */
42
+ role?: 'user' | 'admin' | 'master';
43
+ }
44
+ export interface CommandSource {
45
+ kind: 'flow' | 'plugin' | 'builtin';
46
+ /** Flow id or plugin name. */
47
+ id: string;
48
+ /** Flow or plugin name, for display. */
49
+ name: string;
50
+ /** The command node, for flows. */
51
+ nodeId?: string;
52
+ }
53
+ export interface CommandEntry extends CommandDef {
54
+ botId: string;
55
+ source: CommandSource;
56
+ /** For flow commands: higher answers first when two register the same name. */
57
+ priority?: number;
58
+ }
59
+ /** Per-bot command settings, stored on the bot record. */
60
+ export interface CommandSettings {
61
+ /** Defaults to `['/']`. */
62
+ prefixes?: string[];
63
+ /** Answer `/help` with the list of commands; on unless set to false. */
64
+ help?: boolean;
65
+ /** First line of the help menu. */
66
+ helpTitle?: string;
67
+ /** User ids allowed to run admin-only commands. Moved to the permissions plugin, which reads it once. */
68
+ admins?: string[];
69
+ /** `/help` lists only the commands the asker may run. */
70
+ helpByRole?: boolean;
71
+ }
72
+ export declare const DEFAULT_PREFIXES: string[];
73
+ export declare const DEFAULT_HELP_TITLE = "可用指令:";
74
+ /** A message split into prefix, command name and the text after it. */
75
+ export interface ParsedCommand {
76
+ prefix: string;
77
+ /** As written, without the prefix. */
78
+ name: string;
79
+ rest: string;
80
+ /** The registered command the name or alias belongs to, if any. */
81
+ entry?: CommandEntry;
82
+ }
83
+ /** Splits a message into a command, or nothing when it does not start with a prefix. */
84
+ export declare function splitCommand(text: string, prefixes?: string[]): Omit<ParsedCommand, 'entry'> | undefined;
85
+ /** Whether a command (by name or alias) is the one written. Names are compared without case. */
86
+ export declare function commandMatches(def: Pick<CommandDef, 'name' | 'aliases'>, written: string): boolean;
87
+ export type ArgsResult = {
88
+ ok: true;
89
+ values: Record<string, ArgValue>;
90
+ } | {
91
+ ok: false;
92
+ error: string;
93
+ arg?: string;
94
+ };
95
+ /**
96
+ * Fills a command's arguments from the text after the command. `segments` are the message's, so an
97
+ * @mention fills a `user` argument with the id rather than the name shown in the text.
98
+ */
99
+ export declare function parseArgs(args: CommandArg[], rest: string, segments?: Segment[]): ArgsResult;
100
+ /** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */
101
+ export declare function argTypeLabel(arg: Pick<CommandArg, 'type' | 'choices'>, locale?: 'zh-CN' | 'en'): string;
102
+ /** The arguments as written in a usage line: `<分数:数字> [备注]`. */
103
+ export declare function formatArgs(args: CommandArg[] | undefined): string;
104
+ /** The prefix a command is shown with: its own first prefix, else the bot's. */
105
+ export declare function commandPrefix(def: Pick<CommandDef, 'prefixes'>, botPrefix?: string): string;
106
+ /** How a command is written, e.g. `/score <score:数字>`. */
107
+ export declare function commandUsage(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string): string;
108
+ /** The reply when a command's arguments do not fit: the usage line, then what each argument is. */
109
+ export declare function usageReply(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string): string;
110
+ /** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */
111
+ export declare function requiredRole(def: Pick<CommandDef, 'permission' | 'role'>): 'admin' | 'master' | undefined;
112
+ /** The help menu for a bot's commands: one line per command, hidden ones left out. */
113
+ export declare function helpText(entries: CommandEntry[], settings?: CommandSettings): string;
114
+ /** Names (and aliases) that more than one source registers on the same bot. */
115
+ export declare function commandConflicts(entries: CommandEntry[]): {
116
+ botId: string;
117
+ name: string;
118
+ entries: CommandEntry[];
119
+ }[];
@@ -0,0 +1,186 @@
1
+ // src/commands.ts
2
+ const DEFAULT_PREFIXES = ["/"];
3
+ const DEFAULT_HELP_TITLE = "可用指令:";
4
+ /** Splits a message into a command, or nothing when it does not start with a prefix. */
5
+ function splitCommand(text, prefixes = DEFAULT_PREFIXES) {
6
+ const trimmed = text.trim();
7
+ const prefix = [...prefixes].filter(Boolean).sort((a, b) => b.length - a.length).find((item) => trimmed.startsWith(item));
8
+ if (prefix === void 0) return;
9
+ const body = trimmed.slice(prefix.length);
10
+ const match = /^(\S+)(?:\s+([\s\S]*))?$/.exec(body);
11
+ if (!match) return;
12
+ return {
13
+ prefix,
14
+ name: match[1],
15
+ rest: (match[2] ?? "").trim()
16
+ };
17
+ }
18
+ /** Whether a command (by name or alias) is the one written. Names are compared without case. */
19
+ function commandMatches(def, written) {
20
+ const name = written.toLowerCase();
21
+ return [def.name, ...def.aliases ?? []].some((item) => !!item && item.toLowerCase() === name);
22
+ }
23
+ const YES = /* @__PURE__ */ new Set([
24
+ "是",
25
+ "对",
26
+ "开",
27
+ "开启",
28
+ "yes",
29
+ "y",
30
+ "true",
31
+ "on",
32
+ "1"
33
+ ]);
34
+ const NO = /* @__PURE__ */ new Set([
35
+ "否",
36
+ "不",
37
+ "关",
38
+ "关闭",
39
+ "no",
40
+ "n",
41
+ "false",
42
+ "off",
43
+ "0"
44
+ ]);
45
+ /**
46
+ * Fills a command's arguments from the text after the command. `segments` are the message's, so an
47
+ * @mention fills a `user` argument with the id rather than the name shown in the text.
48
+ */
49
+ function parseArgs(args, rest, segments = []) {
50
+ const words = tokenize(rest, segments.filter((segment) => segment.type === "at" && segment.data.qq !== "all"));
51
+ const values = {};
52
+ const lastText = args.findLastIndex((arg) => arg.type === "text");
53
+ for (const [index, arg] of args.entries()) {
54
+ let word;
55
+ if (arg.type === "text" && (arg.rest || index === lastText) && index === args.length - 1) {
56
+ const taken = words.splice(0);
57
+ word = taken.length ? { text: taken.map((item) => item.text).join(" ") } : void 0;
58
+ } else if (arg.type === "text" && (arg.rest || index === lastText)) {
59
+ const later = args.length - 1 - index;
60
+ const taken = words.splice(0, Math.max(words.length - later, words.length ? 1 : 0));
61
+ word = taken.length ? { text: taken.map((item) => item.text).join(" ") } : void 0;
62
+ } else word = words.shift();
63
+ if (!word?.text) {
64
+ if (arg.default !== void 0 && arg.default !== "") values[arg.name] = arg.default;
65
+ else if (!arg.optional) return {
66
+ ok: false,
67
+ error: `missing ${arg.name}`,
68
+ arg: arg.name
69
+ };
70
+ continue;
71
+ }
72
+ const value = convertArg(arg, word);
73
+ if (value === void 0) return {
74
+ ok: false,
75
+ error: `${arg.name} should be ${argTypeLabel(arg, "en")}`,
76
+ arg: arg.name
77
+ };
78
+ values[arg.name] = value;
79
+ }
80
+ return {
81
+ ok: true,
82
+ values
83
+ };
84
+ }
85
+ /** Splits text into words; `@name` words that stand for an @mention carry its user id. */
86
+ function tokenize(text, mentions) {
87
+ const queue = [...mentions];
88
+ return (text.trim() ? text.trim().split(/\s+/) : []).map((word) => {
89
+ const index = queue.findIndex((segment) => word === `@${segment.data.name ?? segment.data.qq}`);
90
+ if (index < 0) return { text: word };
91
+ const [segment] = queue.splice(index, 1);
92
+ return {
93
+ text: word,
94
+ user: String(segment.data.qq)
95
+ };
96
+ });
97
+ }
98
+ function convertArg(arg, word) {
99
+ const raw = word.text;
100
+ switch (arg.type) {
101
+ case "number": {
102
+ const number = Number(raw);
103
+ return Number.isFinite(number) ? number : void 0;
104
+ }
105
+ case "boolean": {
106
+ const folded = raw.toLowerCase();
107
+ return YES.has(folded) ? true : NO.has(folded) ? false : void 0;
108
+ }
109
+ case "user": {
110
+ if (word.user) return word.user;
111
+ const id = raw.replace(/^@/, "");
112
+ return /^\d{4,}$/.test(id) ? id : void 0;
113
+ }
114
+ case "choice": return (arg.choices ?? []).find((choice) => choice.toLowerCase() === raw.toLowerCase());
115
+ default: return raw;
116
+ }
117
+ }
118
+ /** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */
119
+ function argTypeLabel(arg, locale = "zh-CN") {
120
+ const zh = locale === "zh-CN";
121
+ switch (arg.type) {
122
+ case "number": return zh ? "数字" : "a number";
123
+ case "boolean": return zh ? "是/否" : "yes or no";
124
+ case "user": return zh ? "@某人" : "an @mention or user id";
125
+ case "choice": return (arg.choices ?? []).join("|") || (zh ? "选项" : "a choice");
126
+ default: return zh ? "文本" : "text";
127
+ }
128
+ }
129
+ /** The arguments as written in a usage line: `<分数:数字> [备注]`. */
130
+ function formatArgs(args) {
131
+ return (args ?? []).map((arg) => {
132
+ const type = arg.type === "text" ? "" : `:${argTypeLabel(arg)}`;
133
+ const body = `${arg.name}${type}${arg.rest ? "..." : ""}`;
134
+ return arg.optional || arg.default !== void 0 && arg.default !== "" ? `[${body}]` : `<${body}>`;
135
+ }).join(" ");
136
+ }
137
+ /** The prefix a command is shown with: its own first prefix, else the bot's. */
138
+ function commandPrefix(def, botPrefix = DEFAULT_PREFIXES[0]) {
139
+ return def.prefixes?.find(Boolean) ?? botPrefix;
140
+ }
141
+ /** How a command is written, e.g. `/score <score:数字>`. */
142
+ function commandUsage(def, prefix) {
143
+ const args = formatArgs(def.args);
144
+ return `${prefix ?? commandPrefix(def)}${def.name}${args ? ` ${args}` : ""}`;
145
+ }
146
+ /** The reply when a command's arguments do not fit: the usage line, then what each argument is. */
147
+ function usageReply(def, prefix) {
148
+ const notes = (def.args ?? []).filter((arg) => arg.description).map((arg) => `${arg.name}:${arg.description}`);
149
+ return [`用法:${commandUsage(def, prefix)}`, ...notes].join("\n");
150
+ }
151
+ /** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */
152
+ function requiredRole(def) {
153
+ const role = def.role ?? (def.permission === "all" ? void 0 : def.permission);
154
+ return role === "admin" || role === "master" ? role : void 0;
155
+ }
156
+ /** The help menu for a bot's commands: one line per command, hidden ones left out. */
157
+ function helpText(entries, settings = {}) {
158
+ const botPrefix = settings.prefixes?.[0] ?? DEFAULT_PREFIXES[0];
159
+ const seen = /* @__PURE__ */ new Set();
160
+ const lines = [];
161
+ for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {
162
+ const key = entry.name.toLowerCase();
163
+ if (entry.hidden || seen.has(key)) continue;
164
+ seen.add(key);
165
+ const prefix = commandPrefix(entry, botPrefix);
166
+ const aliases = entry.aliases?.filter(Boolean).map((alias) => `${prefix}${alias}`).join("、");
167
+ lines.push(`${commandUsage(entry, prefix)}${aliases ? `(${aliases})` : ""}${entry.description ? ` —— ${entry.description}` : ""}`);
168
+ }
169
+ return [settings.helpTitle || "可用指令:", ...lines].join("\n");
170
+ }
171
+ /** Names (and aliases) that more than one source registers on the same bot. */
172
+ function commandConflicts(entries) {
173
+ const owners = /* @__PURE__ */ new Map();
174
+ for (const entry of entries) for (const name of new Set([entry.name, ...entry.aliases ?? []].filter(Boolean).map((item) => item.toLowerCase()))) {
175
+ const key = `${entry.botId}|${name}`;
176
+ owners.set(key, [...owners.get(key) ?? [], entry]);
177
+ }
178
+ return [...owners.entries()].filter(([, list]) => list.length > 1).map(([key, list]) => ({
179
+ botId: key.split("|")[0],
180
+ name: key.slice(key.indexOf("|") + 1),
181
+ entries: [...list].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
182
+ }));
183
+ }
184
+ export { DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply };
185
+
186
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.js","names":[],"sources":["../src/commands.ts"],"sourcesContent":["/**\n * Commands such as `/score 85`: a name after a prefix, then arguments. Flows, bot plugins and the\n * built-in `/help` all register commands per bot, so help menus, the Agent and the overview can\n * list them in one place.\n */\n\nimport type { Segment } from '@mushinjs/core'\n\n/**\n * What an argument takes: `text` a word (or the rest, for the last one), `number` a number,\n * `boolean` yes or no (是/否, true/false, on/off, 1/0), `user` an @mention or a user id, `choice` one\n * of `choices`.\n */\nexport type CommandArgType = 'text' | 'number' | 'boolean' | 'user' | 'choice'\n\n/** One argument of a command, in the order they are written. */\nexport interface CommandArg {\n name: string\n type: CommandArgType\n /** Can be left out; then `default` is used, or the argument is missing from the values. */\n optional?: boolean\n /** Takes the rest of the message. Only text arguments can; the last text argument always does. */\n rest?: boolean\n default?: string | number | boolean\n /** For `choice` arguments. */\n choices?: string[]\n /** Shown in the usage reply and the editor. */\n description?: string\n}\n\nexport type ArgValue = string | number | boolean\n\nexport interface CommandDef {\n /** Without the prefix, e.g. `score`. */\n name: string\n aliases?: string[]\n description?: string\n /** What follows the name, in order. */\n args?: CommandArg[]\n /** Prefixes of this command only, e.g. `['#']`; empty or missing uses the bot's. */\n prefixes?: string[]\n /** Left out of `/help`. */\n hidden?: boolean\n /** Who may run it: `admin` lets admins and masters, `master` only masters. Needs the permissions plugin. */\n permission?: 'all' | 'admin' | 'master'\n /** The same as `permission`, as a role: `{ role: 'admin' }`. */\n role?: 'user' | 'admin' | 'master'\n}\n\nexport interface CommandSource {\n kind: 'flow' | 'plugin' | 'builtin'\n /** Flow id or plugin name. */\n id: string\n /** Flow or plugin name, for display. */\n name: string\n /** The command node, for flows. */\n nodeId?: string\n}\n\nexport interface CommandEntry extends CommandDef {\n botId: string\n source: CommandSource\n /** For flow commands: higher answers first when two register the same name. */\n priority?: number\n}\n\n/** Per-bot command settings, stored on the bot record. */\nexport interface CommandSettings {\n /** Defaults to `['/']`. */\n prefixes?: string[]\n /** Answer `/help` with the list of commands; on unless set to false. */\n help?: boolean\n /** First line of the help menu. */\n helpTitle?: string\n /** User ids allowed to run admin-only commands. Moved to the permissions plugin, which reads it once. */\n admins?: string[]\n /** `/help` lists only the commands the asker may run. */\n helpByRole?: boolean\n}\n\nexport const DEFAULT_PREFIXES = ['/']\nexport const DEFAULT_HELP_TITLE = '可用指令:'\n\n/** A message split into prefix, command name and the text after it. */\nexport interface ParsedCommand {\n prefix: string\n /** As written, without the prefix. */\n name: string\n rest: string\n /** The registered command the name or alias belongs to, if any. */\n entry?: CommandEntry\n}\n\n/** Splits a message into a command, or nothing when it does not start with a prefix. */\nexport function splitCommand(text: string, prefixes: string[] = DEFAULT_PREFIXES): Omit<ParsedCommand, 'entry'> | undefined {\n const trimmed = text.trim()\n const prefix = [...prefixes].filter(Boolean).sort((a, b) => b.length - a.length).find((item) => trimmed.startsWith(item))\n if (prefix === undefined) return\n const body = trimmed.slice(prefix.length)\n const match = /^(\\S+)(?:\\s+([\\s\\S]*))?$/.exec(body)\n if (!match) return\n return { prefix, name: match[1], rest: (match[2] ?? '').trim() }\n}\n\n/** Whether a command (by name or alias) is the one written. Names are compared without case. */\nexport function commandMatches(def: Pick<CommandDef, 'name' | 'aliases'>, written: string) {\n const name = written.toLowerCase()\n return [def.name, ...(def.aliases ?? [])].some((item) => !!item && item.toLowerCase() === name)\n}\n\nexport type ArgsResult =\n | { ok: true; values: Record<string, ArgValue> }\n | { ok: false; error: string; arg?: string }\n\nconst YES = new Set(['是', '对', '开', '开启', 'yes', 'y', 'true', 'on', '1'])\nconst NO = new Set(['否', '不', '关', '关闭', 'no', 'n', 'false', 'off', '0'])\n\n/**\n * Fills a command's arguments from the text after the command. `segments` are the message's, so an\n * @mention fills a `user` argument with the id rather than the name shown in the text.\n */\nexport function parseArgs(args: CommandArg[], rest: string, segments: Segment[] = []): ArgsResult {\n const mentions = segments.filter((segment) => segment.type === 'at' && segment.data.qq !== 'all')\n const words = tokenize(rest, mentions)\n const values: Record<string, ArgValue> = {}\n const lastText = args.findLastIndex((arg) => arg.type === 'text')\n for (const [index, arg] of args.entries()) {\n let word: Token | undefined\n if (arg.type === 'text' && (arg.rest || index === lastText) && index === args.length - 1) {\n const taken = words.splice(0)\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else if (arg.type === 'text' && (arg.rest || index === lastText)) {\n // Leaves one word for each argument after it.\n const later = args.length - 1 - index\n const taken = words.splice(0, Math.max(words.length - later, words.length ? 1 : 0))\n word = taken.length ? { text: taken.map((item) => item.text).join(' ') } : undefined\n } else {\n word = words.shift()\n }\n if (!word?.text) {\n if (arg.default !== undefined && arg.default !== '') values[arg.name] = arg.default\n else if (!arg.optional) return { ok: false, error: `missing ${arg.name}`, arg: arg.name }\n continue\n }\n const value = convertArg(arg, word)\n if (value === undefined) return { ok: false, error: `${arg.name} should be ${argTypeLabel(arg, 'en')}`, arg: arg.name }\n values[arg.name] = value\n }\n return { ok: true, values }\n}\n\ninterface Token {\n text: string\n /** The user an @mention names. */\n user?: string\n}\n\n/** Splits text into words; `@name` words that stand for an @mention carry its user id. */\nfunction tokenize(text: string, mentions: Segment[]): Token[] {\n const queue = [...mentions]\n return (text.trim() ? text.trim().split(/\\s+/) : []).map((word) => {\n const index = queue.findIndex((segment) => word === `@${segment.data.name ?? segment.data.qq}`)\n if (index < 0) return { text: word }\n const [segment] = queue.splice(index, 1)\n return { text: word, user: String(segment.data.qq) }\n })\n}\n\nfunction convertArg(arg: CommandArg, word: Token): ArgValue | undefined {\n const raw = word.text\n switch (arg.type) {\n case 'number': {\n const number = Number(raw)\n return Number.isFinite(number) ? number : undefined\n }\n case 'boolean': {\n const folded = raw.toLowerCase()\n return YES.has(folded) ? true : NO.has(folded) ? false : undefined\n }\n case 'user': {\n if (word.user) return word.user\n const id = raw.replace(/^@/, '')\n return /^\\d{4,}$/.test(id) ? id : undefined\n }\n case 'choice': {\n const found = (arg.choices ?? []).find((choice) => choice.toLowerCase() === raw.toLowerCase())\n return found\n }\n default:\n return raw\n }\n}\n\n/** How an argument's type reads in usage lines: `数字`, `@某人`, `a|b`. */\nexport function argTypeLabel(arg: Pick<CommandArg, 'type' | 'choices'>, locale: 'zh-CN' | 'en' = 'zh-CN') {\n const zh = locale === 'zh-CN'\n switch (arg.type) {\n case 'number': return zh ? '数字' : 'a number'\n case 'boolean': return zh ? '是/否' : 'yes or no'\n case 'user': return zh ? '@某人' : 'an @mention or user id'\n case 'choice': return (arg.choices ?? []).join('|') || (zh ? '选项' : 'a choice')\n default: return zh ? '文本' : 'text'\n }\n}\n\n/** The arguments as written in a usage line: `<分数:数字> [备注]`. */\nexport function formatArgs(args: CommandArg[] | undefined) {\n return (args ?? []).map((arg) => {\n const type = arg.type === 'text' ? '' : `:${argTypeLabel(arg)}`\n const body = `${arg.name}${type}${arg.rest ? '...' : ''}`\n return arg.optional || (arg.default !== undefined && arg.default !== '') ? `[${body}]` : `<${body}>`\n }).join(' ')\n}\n\n/** The prefix a command is shown with: its own first prefix, else the bot's. */\nexport function commandPrefix(def: Pick<CommandDef, 'prefixes'>, botPrefix = DEFAULT_PREFIXES[0]) {\n return def.prefixes?.find(Boolean) ?? botPrefix\n}\n\n/** How a command is written, e.g. `/score <score:数字>`. */\nexport function commandUsage(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const args = formatArgs(def.args)\n return `${prefix ?? commandPrefix(def)}${def.name}${args ? ` ${args}` : ''}`\n}\n\n/** The reply when a command's arguments do not fit: the usage line, then what each argument is. */\nexport function usageReply(def: Pick<CommandDef, 'name' | 'args' | 'prefixes'>, prefix?: string) {\n const notes = (def.args ?? []).filter((arg) => arg.description).map((arg) => `${arg.name}:${arg.description}`)\n return [`用法:${commandUsage(def, prefix)}`, ...notes].join('\\n')\n}\n\n/** The role a command needs, from `role` or `permission`; nothing when everyone may run it. */\nexport function requiredRole(def: Pick<CommandDef, 'permission' | 'role'>): 'admin' | 'master' | undefined {\n const role = def.role ?? (def.permission === 'all' ? undefined : def.permission)\n return role === 'admin' || role === 'master' ? role : undefined\n}\n\n/** The help menu for a bot's commands: one line per command, hidden ones left out. */\nexport function helpText(entries: CommandEntry[], settings: CommandSettings = {}) {\n const botPrefix = settings.prefixes?.[0] ?? DEFAULT_PREFIXES[0]\n const seen = new Set<string>()\n const lines: string[] = []\n for (const entry of [...entries].sort((a, b) => a.name.localeCompare(b.name))) {\n const key = entry.name.toLowerCase()\n if (entry.hidden || seen.has(key)) continue\n seen.add(key)\n const prefix = commandPrefix(entry, botPrefix)\n const aliases = entry.aliases?.filter(Boolean).map((alias) => `${prefix}${alias}`).join('、')\n lines.push(`${commandUsage(entry, prefix)}${aliases ? `(${aliases})` : ''}${entry.description ? ` —— ${entry.description}` : ''}`)\n }\n return [settings.helpTitle || DEFAULT_HELP_TITLE, ...lines].join('\\n')\n}\n\n/** Names (and aliases) that more than one source registers on the same bot. */\nexport function commandConflicts(entries: CommandEntry[]) {\n const owners = new Map<string, CommandEntry[]>()\n for (const entry of entries) {\n for (const name of new Set([entry.name, ...(entry.aliases ?? [])].filter(Boolean).map((item) => item.toLowerCase()))) {\n const key = `${entry.botId}|${name}`\n owners.set(key, [...(owners.get(key) ?? []), entry])\n }\n }\n return [...owners.entries()]\n .filter(([, list]) => list.length > 1)\n // The first entry is the one that answers: highest priority, then registration order.\n .map(([key, list]) => ({ botId: key.split('|')[0], name: key.slice(key.indexOf('|') + 1), entries: [...list].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)) }))\n}\n"],"mappings":";AAgFA,MAAa,mBAAmB,CAAC,GAAG;AACpC,MAAa,qBAAqB;;AAalC,SAAgB,aAAa,MAAc,WAAqB,kBAA4D;CAC1H,MAAM,UAAU,KAAK,KAAK;CAC1B,MAAM,SAAS,CAAC,GAAG,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,MAAM,SAAS,QAAQ,WAAW,IAAI,CAAC;CACxH,IAAI,WAAW,KAAA,GAAW;CAC1B,MAAM,OAAO,QAAQ,MAAM,OAAO,MAAM;CACxC,MAAM,QAAQ,2BAA2B,KAAK,IAAI;CAClD,IAAI,CAAC,OAAO;CACZ,OAAO;EAAE;EAAQ,MAAM,MAAM;EAAI,OAAO,MAAM,MAAM,GAAA,CAAI,KAAK;CAAE;AACjE;;AAGA,SAAgB,eAAe,KAA2C,SAAiB;CACzF,MAAM,OAAO,QAAQ,YAAY;CACjC,OAAO,CAAC,IAAI,MAAM,GAAI,IAAI,WAAW,CAAC,CAAE,CAAC,CAAC,MAAM,SAAS,CAAC,CAAC,QAAQ,KAAK,YAAY,MAAM,IAAI;AAChG;AAMA,MAAM,sBAAM,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAM;CAAO;CAAK;CAAQ;CAAM;AAAG,CAAC;AACxE,MAAM,qBAAK,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAM;CAAM;CAAK;CAAS;CAAO;AAAG,CAAC;;;;;AAMxE,SAAgB,UAAU,MAAoB,MAAc,WAAsB,CAAC,GAAe;CAEhG,MAAM,QAAQ,SAAS,MADN,SAAS,QAAQ,YAAY,QAAQ,SAAS,QAAQ,QAAQ,KAAK,OAAO,KACvD,CAAC;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OAAO,EAAE,YAAY,MAAM,EAAE,YAAY,EAAE;CAAE,EAAE;AACzK"}
@@ -0,0 +1,6 @@
1
+ import { BotLogLine, BotManager, BotStatusInfo, CommandCall, CommandProvider, MessageUsage, RunCommandInput } from "./manager.js";
2
+ import { MessageArchive, MessageQuery, MessageRow, fromRow, toRow } from "./archive.js";
3
+ import { BUILTIN_PRIORITY, Bot, BotHooks, CommandHandler, Middleware, MiddlewareOptions, Sendable, Session, byteSize } from "./bot.js";
4
+ import { ArgValue, ArgsResult, CommandArg, CommandArgType, CommandDef, CommandEntry, CommandSettings, CommandSource, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ParsedCommand, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
5
+ import { AdapterType, BotConnectionInfo, BotEvent, BotPluginEntry, BotRecord, BotRole, BotStatus, Contact, ContactResolver, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, PermissionProvider, ROLE_RANK, ResolvedMedia, SANDBOX_CHANNEL, SANDBOX_USER, SourcedContent, Transport, isSandbox, roleAtLeast } from "./types.js";
6
+ export { AdapterType, ArgValue, ArgsResult, BUILTIN_PRIORITY, Bot, BotConnectionInfo, BotEvent, BotHooks, BotLogLine, BotManager, BotPluginEntry, BotRecord, BotRole, BotStatus, BotStatusInfo, CommandArg, CommandArgType, CommandCall, CommandDef, CommandEntry, CommandHandler, CommandProvider, CommandSettings, CommandSource, Contact, ContactResolver, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, ForwardedMessage, GroupRole, GroupRoleResolver, IncomingMessage, MediaResolver, MessageArchive, MessageQuery, MessageRow, MessageUsage, Middleware, MiddlewareOptions, ParsedCommand, PermissionProvider, ROLE_RANK, ResolvedMedia, RunCommandInput, SANDBOX_CHANNEL, SANDBOX_USER, Sendable, Session, SourcedContent, Transport, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, BotManager as default, formatArgs, fromRow, helpText, isSandbox, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import { BotManager } from "./manager.js";
2
+ import { MessageArchive, fromRow, toRow } from "./archive.js";
3
+ import { BUILTIN_PRIORITY, Bot, Session, byteSize } from "./bot.js";
4
+ import { DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, argTypeLabel, commandConflicts, commandMatches, commandPrefix, commandUsage, formatArgs, helpText, parseArgs, requiredRole, splitCommand, usageReply } from "./commands.js";
5
+ import { ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, isSandbox, roleAtLeast } from "./types.js";
6
+ // src/index.ts
7
+ var src_default = BotManager;
8
+ export { BUILTIN_PRIORITY, Bot, BotManager, DEFAULT_HELP_TITLE, DEFAULT_PREFIXES, MessageArchive, ROLE_RANK, SANDBOX_CHANNEL, SANDBOX_USER, Session, argTypeLabel, byteSize, commandConflicts, commandMatches, commandPrefix, commandUsage, src_default as default, formatArgs, fromRow, helpText, isSandbox, parseArgs, requiredRole, roleAtLeast, splitCommand, toRow, usageReply };
9
+
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { BotManager } from './manager'\n\nexport * from './archive'\nexport * from './bot'\nexport * from './commands'\nexport * from './manager'\nexport * from './types'\n\nexport default BotManager\n"],"mappings":";;;;;;AAQA,IAAA,cAAe"}