Search code examples
pythondiscorddiscord.pylevenshtein-distancefuzzywuzzy

Match to the nearest command name in discord.py


I'm trying to create a feature for my discord.py bot that would send command names that are similar to what the user has used as a command when what they have typed in is incorrect. For example, a command called .slap exists. But the user enters .slp or something similar.

I want the bot to respond with the most similar command(s) which in this case is gonna be .slap. I'm a beginner still so I have no idea how to do this. I discovered about a lib called fuzzywuzzy and Levenshtein distance and I have no idea how to use them for my bot.

Any help would be highly appreciated! Thanks


Solution

  • First of all, fuzzymatching commands and executing what it thinks is right, is not a great thing to add to your bot. It adds a point of failure, which can be pretty frustrating for the user regardless.

    However, if you suggest a list of possible commands, it would probably work a lot better.

    FuzzyWuzzy is a great tool for this.
    The documentations for it are extremely helpful, so I really don't think you would have an issue if you actually read them.

    My 2 cents for implementing would be (in pythonian pesudocode)

    # user had input an invalid command
    invalid_command = #userinput
    
    command_list = [#list of your commands]
    fuzzy_ratios = []
    for command in command_list:
       ratio = fuzzywuzzy.ratio(invalid_command, command)
       fuzzy_ratios.append(ratio)
    
    max_ratio_index = fuzzy_ratios.index(max(fuzzy_ratios))
    fuzzy_matched = command_list[max_ratio_index]
    
    return f"did you mean {fuzzy_matched}?"
    

    Please try to implement and think why you need to implement it.
    You need to actually try to implement yourself, or you will never learn.