-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontext.ts
288 lines (271 loc) · 9.65 KB
/
context.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
import { Commands } from "./commands.ts";
import { BotCommandScopeChat, Context, NextFunction } from "./deps.deno.ts";
import { fuzzyMatch, JaroWinklerOptions } from "./jaro-winkler.ts";
import { SetMyCommandsParams } from "./mod.ts";
import { botCommandEntity } from "./types.ts";
import { ensureArray, escapeSpecial } from "./utils.ts";
export interface CommandsFlavor<C extends Context = Context> extends Context {
/**
* Sets the provided commands for the current chat.
* Cannot be called on updates that don't have a `chat` property.
*
* [!IMPORTANT]
* Calling this method with upperCased command names registered, will throw
* @see https://core.telegram.org/bots/api#botcommand
* @see https://core.telegram.org/method/bots.setBotCommands
*
* @example
* ```typescript
* bot.hears("sudo", (ctx) =>
* ctx.setMyCommands(userCommands, adminCommands));
* bot.hears("logout", (ctx) =>
* ctx.setMyCommands(userCommands));
* bot.hears("example", (ctx) =>
* ctx.setMyCommands([aCommands, bCommands, cCommands]));
* ```
*
* @param commands List of available commands
* @returns Promise with the result of the operations
*/
setMyCommands: (
commands: Commands<C> | Commands<C>[],
...moreCommands: Commands<C>[]
) => Promise<void>;
/**
* Returns the nearest command to the user input.
* If no command is found, returns `null`.
*
* @param commands List of available commands
* @param options Options for the Jaro-Winkler algorithm
* @returns The nearest command or `null`
*/
getNearestCommand: (
commands: Commands<C> | Commands<C>[],
options?: Omit<
Partial<JaroWinklerOptions>,
"language"
>,
) => string | null;
/**
* @param commands
* @returns command entities hydrated with the custom prefixes
*/
getCommandEntities: (
commands: Commands<C> | Commands<C>[],
) => botCommandEntity[];
}
/**
* Installs the commands flavor into the context.
*/
export function commands<C extends Context>() {
return (ctx: CommandsFlavor<C>, next: NextFunction) => {
ctx.setMyCommands = async (
commands,
...moreCommands: Commands<C>[]
) => {
if (!ctx.chat) {
throw new Error(
"cannot call `ctx.setMyCommands` on an update with no `chat` property",
);
}
commands = ensureArray(commands).concat(moreCommands);
await Promise.all(
MyCommandParams.from(
commands,
ctx.chat.id,
).map((args) => ctx.api.raw.setMyCommands(args)),
);
};
ctx.getNearestCommand = (commands, options) => {
if (ctx.has(":text")) {
const results = ensureArray(commands)
.map((commands) => {
const firstMatch = ctx.getCommandEntities(
commands,
)[0];
const commandLike = firstMatch?.text.replace(
firstMatch.prefix,
"",
) || "";
const result = fuzzyMatch(
commandLike,
commands,
{
...options,
language: !options?.ignoreLocalization
? ctx.from
?.language_code
: undefined,
},
);
return result;
})
.sort(
(a, b) =>
(b?.similarity ?? 0) -
(a?.similarity ?? 0),
);
const result = results[0];
if (!result || !result.command) return null;
return (
result.command.prefix +
result.command.name
);
}
return null;
};
ctx.getCommandEntities = (
commands: Commands<C> | Commands<C>[],
) => {
if (!ctx.has(":text")) {
throw new Error(
"cannot call `ctx.commandEntities` on an update with no `text`",
);
}
const text = ctx.msg.text;
if (!text) return [];
const prefixes = ensureArray(commands).flatMap(
(cmds) => cmds.prefixes,
);
if (!prefixes.length) return [];
const regexes = prefixes.map(
(prefix) =>
new RegExp(
`(\?\<\!\\S)(\?<prefix>${
escapeSpecial(
prefix,
)
})\\S+(\\s|$)`,
"g",
),
);
const entities = regexes.flatMap((regex) => {
let match: RegExpExecArray | null;
const matches = [];
while (
(match = regex.exec(text)) !== null
) {
const text = match[0].trim();
matches.push({
text,
offset: match.index,
prefix: match.groups!.prefix,
type: "bot_command",
length: text.length,
});
}
return matches as botCommandEntity[];
});
return entities;
};
return next();
};
}
/**
* Static class for getting and manipulating {@link SetMyCommandsParams}.
* The main function is {@link from}
*/
export class MyCommandParams {
/**
* Merges and serialize one or more Commands instances into a single array
* of commands params that can be used to set the commands menu displayed to the user.
* @example
```ts
const adminCommands = new Commands();
const userCommands = new Commands();
adminCommands
.command("do a",
"a description",
(ctx) => ctx.doA());
userCommands
.command("do b",
"b description",
(ctx) => ctx.doB());
const mergedParams =
MyCommandParams.from([a, b], someChatId);
```
* @param commands An array of one or more Commands instances.
* @returns an array of {@link SetMyCommandsParams} grouped by language
*/
static from<C extends Context>(
commands: Commands<C>[],
chat_id: BotCommandScopeChat["chat_id"],
) {
const commandsParams = this._serialize(
commands,
chat_id,
).flat();
if (!commandsParams.length) return [];
return this.mergeByLanguage(commandsParams);
}
/**
* Serializes one or multiple {@link Commands} instances, each one into their respective
* single scoped SetMyCommandsParams version.
* @example
```ts
const adminCommands = new Commands();
// add to scope, localize, etc
const userCommands = new Commands();
// add to scope, localize, etc
const [
singleScopedAdminParams,
singleScopedUserParams
] = MyCommandsParams.serialize([adminCommands,userCommands])
```
* @param commandsArr an array of one or more commands instances
* @param chat_id the chat id relative to the message update, coming from the ctx object.
* @returns an array of scoped {@link SetMyCommandsParams} mapped from their respective Commands instances
*/
static _serialize<C extends Context>(
commandsArr: Commands<C>[],
chat_id: BotCommandScopeChat["chat_id"],
) {
return commandsArr.map((commands) =>
commands.toSingleScopeArgs({
type: "chat",
chat_id,
})
);
}
/**
* Lexicographically sorts commandParams based on their language code.
* @returns the sorted array
*/
static _sortByLanguage(params: SetMyCommandsParams[]) {
return params.sort((a, b) => {
if (!a.language_code) return -1;
if (!b.language_code) return 1;
return a.language_code.localeCompare(
b.language_code,
);
});
}
/**
* Iterates over an array of CommandsParams
* merging their respective {@link SetMyCommandsParams.commands}
* when they are from the same language, separating when they are not.
*
* @param params a flattened array of commands params coming from one or more Commands instances
* @returns an array containing all commands grouped by language
*/
private static mergeByLanguage(
params: SetMyCommandsParams[],
) {
const sorted = this._sortByLanguage(params);
return sorted.reduce((result, current, i, arr) => {
if (
i === 0 ||
current.language_code !==
arr[i - 1].language_code
) {
result.push(current);
return result;
} else {
result[result.length - 1].commands = result[
result.length - 1
].commands.concat(current.commands);
return result;
}
}, [] as SetMyCommandsParams[]);
}
}