Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add method for accessing command entities hydrated with matching custom prefixes #31

Merged
merged 13 commits into from
Jul 24, 2024

Conversation

carafelix
Copy link
Member

@carafelix carafelix commented Jul 18, 2024

closes #23
closes #32 (uses the first matched entity, does not allow for multiple misspelled commands, I personally don't think it's a good idea to support that)

Allow retrieval for command entities that do not have '/' as a prefix. (Check only for prefixes registered inside the given Commands instances)

Allows:
imagen
for the given example:

bot.use(commands())

const userCommands = new Commands<MyContext>()

userCommands.command('start', 'example', () => {})
userCommands.command('ente', '_', () => {}, {
    prefix: '?',
})
userCommands.command('amigos', '_', () => {}, {
    prefix: 'abc',
})
userCommands.command('cafiche', '_', () => {}, {
    prefix: '+',
})


bot.use(userCommands)

bot.on(':text', async (ctx, next) => {
    const hydratedEntities =
        ctx.getCommandEntities(userCommands)
    if (!hydratedEntities.length) {
        await next()
    } else {
        const suggestedCommand =
            ctx.getNearestCommand(userCommands)
        if (suggestedCommand) {
            return ctx.reply(
                `Did you mean ${suggestedCommand} ?`
            )
        }
        await ctx.reply('Absolute 404')
    }
})

Relevant lines:

commands/src/context.ts

Lines 87 to 96 in 1110c6e

.map((commands) => {
const firstMatch = ctx.getCommandEntities(
commands,
)[0];
const commandLike = firstMatch?.text.replace(
firstMatch.prefix,
"",
) || "";
const result = fuzzyMatch(
commandLike,

commands/src/context.ts

Lines 124 to 170 in 1110c6e

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;
};

Note: addition of the Super-Expressive Library would make the regex much more easier to read, into:

SuperExpressive()
    .assertNotBehind
    .nonWhitespaceChar
    .end()
    .namedCapture('prefix')
    .string(`${prefix}`)
    .end()
    .oneOrMore
    .nonWhitespaceChar
    .anyOf
    .whitespaceChar
    .endOfInput
    .end()
    .toRegex();

@carafelix carafelix changed the title Add method for accessing command entities for custom prefixes Add method for accessing command entities hydrated with entities matching custom prefixes Jul 18, 2024
@carafelix carafelix changed the title Add method for accessing command entities hydrated with entities matching custom prefixes Add method for accessing command entities hydrated with matching custom prefixes Jul 18, 2024
@carafelix carafelix changed the title Add method for accessing command entities hydrated with matching custom prefixes fix: Add method for accessing command entities hydrated with matching custom prefixes Jul 18, 2024
Copy link

codecov bot commented Jul 18, 2024

Codecov Report

Attention: Patch coverage is 86.76471% with 9 lines in your changes missing coverage. Please review.

Project coverage is 85.86%. Comparing base (63bc0fa) to head (275d2cb).
Report is 47 commits behind head on main.

Files Patch % Lines
src/context.ts 89.58% 3 Missing and 2 partials ⚠️
src/commands.ts 66.66% 4 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main      #31       +/-   ##
===========================================
+ Coverage   68.13%   85.86%   +17.72%     
===========================================
  Files           7        8        +1     
  Lines         408      658      +250     
  Branches       66      102       +36     
===========================================
+ Hits          278      565      +287     
+ Misses        128       90       -38     
- Partials        2        3        +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@roziscoding roziscoding changed the title fix: Add method for accessing command entities hydrated with matching custom prefixes feat: Add method for accessing command entities hydrated with matching custom prefixes Jul 18, 2024
@carafelix
Copy link
Member Author

carafelix commented Jul 18, 2024

Force-push was a rebase for solving conflitcs over JSdoc 0ffb2c1 + squashing

- change value used in FuzzyMatch from simple text slicing to hydrated commandEntities
- add named capturing group to the prefix regex
- changes getNearestCommand to throw when calling it on an update with no text instead of returning null (matches behavior of setMyCommands and getCommandEntities)
@carafelix
Copy link
Member Author

carafelix commented Jul 19, 2024

minor additions:

  • changed getNearestCommand from returning null to throwing when calling it with insufficient conditions, to match setMyCommands and getCommandEntities behaviors.
  • add commands getter for all register Command's inside a Commands class

@carafelix carafelix marked this pull request as draft July 19, 2024 21:56
@carafelix carafelix marked this pull request as ready for review July 19, 2024 22:30
src/context.ts Outdated Show resolved Hide resolved
src/types.ts Outdated Show resolved Hide resolved
test/commands.test.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@roziscoding roziscoding left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mainly nitpicks

src/README.md Outdated Show resolved Hide resolved
src/commands.ts Outdated Show resolved Hide resolved
src/commands.ts Outdated Show resolved Hide resolved
src/commands.ts Outdated Show resolved Hide resolved
test/context.test.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@roziscoding roziscoding left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. :shipit:

@carafelix carafelix merged commit 5b09bb2 into main Jul 24, 2024
6 checks passed
@carafelix carafelix deleted the addEntities branch July 24, 2024 20:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants