grammyjs / commands

Work-in-progress plugin for managing commands with grammY.
https://grammy.dev/plugins/commands
MIT License
13 stars 2 forks source link

feat: Add ctx.getNearestCommand using jaro-winkler algorithm #5

Closed Camelik closed 11 months ago

Camelik commented 1 year ago

Implement the functionality of acquiring the closest similar command in case of an misspelled command.

The .getNearestCommand(commands, ...options) function has been added to ctx, as it was suggested.

options: { ignoreCase?: boolean; similarityThreshold?: number; }

Example of use:

import { Bot, Context } from "grammy";
import { Commands, commands, ComandsFlavor } from "@grammyjs/commands

type BotContext = CommandsFlavor & Context;

const bot = new Bot<BotContext>(
    "BOT-TOKEN",
);

const cmds = new Commands();

cmds.command("start", "Initializes bot configuration")
    .localize("pt", "start", "Inicializa as configurações do bot")
    .addToScope(
        { type: "all_private_chats" },
        (ctx) => ctx.reply(`Hello, ${ctx.chat.first_name}!`),
    )
    .addToScope(
        { type: "all_group_chats" },
        (ctx) => ctx.reply(`Hello, members of ${ctx.chat.title}!`),
    );

bot.use(commands());

bot.use(cmds);

bot.on("message::bot_command", (ctx) => {
    const nearestCommand = ctx.getNearestCommand(cmds);

    nearestCommand
        ? ctx.reply(`Did you mean /${nearestCommand}?`)
        : ctx.reply(`This command doesn't exists!`);
});

bot.start()
roziscoding commented 1 year ago

This is awesome! Do you think you could add some tests for the new method, please?

codecov[bot] commented 1 year ago

Codecov Report

Attention: 11 lines in your changes are missing coverage. Please review.

Comparison is base (416734d) 14.08% compared to head (0bf47a1) 69.13%.

Files Patch % Lines
src/context.ts 22.22% 7 Missing :warning:
src/jaro-winkler.ts 96.29% 4 Missing :warning:
Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #5 +/- ## =========================================== + Coverage 14.08% 69.13% +55.04% =========================================== Files 5 6 +1 Lines 291 405 +114 Branches 10 41 +31 =========================================== + Hits 41 280 +239 + Misses 250 125 -125 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

Camelik commented 1 year ago

This is awesome! Do you think you could add some tests for the new method, please?

Yes, done

KnorpelSenf commented 1 year ago

This is obviously very cool, I am just not sure if there is enough demand to justify the complexity. But this is more of a strategic decision that I'll leave up to @roziscoding. From a technical point of view, this is pretty awesome!

roziscoding commented 1 year ago

I like this, and I think we should go ahead with it, especially since it's opt-in