Skip to content

Commit

Permalink
fixes #32:
Browse files Browse the repository at this point in the history
- change value used in FuzzyMatch from simple text slicing to hydrated commandEntities
- add named capturing group to the prefix regex
  • Loading branch information
carafelix committed Jul 18, 2024
1 parent e7f0b48 commit 1110c6e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 17 deletions.
37 changes: 20 additions & 17 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,18 @@ export function commands<C extends Context>() {
};

ctx.getNearestCommand = (commands, options) => {
if (ctx.msg?.text) {
commands = ensureArray(commands);
const results = commands
if (ctx.has(":text")) {
const results = ensureArray(commands)
.map((commands) => {
const userInput = ctx.msg!.text!.substring(1);
const firstMatch = ctx.getCommandEntities(
commands,
)[0];
const commandLike = firstMatch?.text.replace(
firstMatch.prefix,
"",
) || "";
const result = fuzzyMatch(
userInput,
commandLike,
commands,
{
...options,
Expand Down Expand Up @@ -135,34 +140,32 @@ export function commands<C extends Context>() {
const regexes = prefixes.map(
(prefix) =>
new RegExp(
`(\?\<\!\\S)${
`(\?\<\!\\S)(\?<prefix>${
escapeSpecial(
prefix,
)
}\\S+(\\s|$)`,
})\\S+(\\s|$)`,
"g",
),
);
const allMatches = regexes.flatMap((regex) => {
let match;
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: match[0].trim(),
text,
offset: match.index,
prefix: match.groups!.prefix,
type: "bot_command",
length: text.length,
});
}
return matches;
return matches as botCommandEntity[];
});

const entities = allMatches.map((match) => ({
...match,
type: "bot_command",
length: match.text.length,
})) as botCommandEntity[];

return entities;
};

Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ export interface CommandElementals {
export interface botCommandEntity extends MessageEntity.CommonMessageEntity {
type: "bot_command";
text: string;
prefix: string;
}
3 changes: 3 additions & 0 deletions test/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,18 +415,21 @@ describe("Commands", () => {
offset: 0,
type: "bot_command",
length: 3,
prefix: "/",
},
{
text: "?momi",
offset: 4,
type: "bot_command",
length: 5,
prefix: "?",
},
{
text: "abcdfghi",
offset: 10,
type: "bot_command",
length: 8,
prefix: "abcd",
},
]);
});
Expand Down

0 comments on commit 1110c6e

Please sign in to comment.