【问题标题】:Discord.py spellcheck commandsDiscord.py 拼写检查命令
【发布时间】:2021-08-03 21:51:06
【问题描述】:

最近,我查看了 Stack Overflow,发现了这段代码可以检查潜在的拼写错误:

from difflib import SequenceMatcher
SequenceMatcher(None, "help", "hepl").ratio()
# Returns 0.75

这适用于 inside bot 命令的代码。但是,我应该如何做到这一点,如果我在命令名称中输入了拼写错误,它会更正并执行命令?

【问题讨论】:

  • 你的意思是如果你不知道第一个参数('help')?我认为您需要一份可用命令的列表,然后将您的输入与每个命令进行比较并决定最高的 SequenceMatcher.ratio。
  • 我有一个它们的列表,但是我如何让它执行一个与有错字的命令不同的命令?

标签: python discord.py


【解决方案1】:
from difflib import SequenceMatcher

@bot.event
async def on_command_error(ctx, error):
    if not isinstance(error, commands.CommandNotFound):
        return

    message = ctx.message  # later overwrite the attributes

    used_prefix = ctx.prefix  # the prefix used
    used_command = message.content.split()[0][len(used_prefix):]  # getting the command, `!foo a b c` -> `foo`

    available_commands = [cmd.name for cmd in bot.commands]
    matches = {  # command name: ratio
        cmd: SequenceMatcher(None, cmd, used_command).ratio()
        for cmd in available_commands
    }

    command = max(matches.items(), key=lambda item: item[1])[0]  # the most similar command

    try:
        arguments = message.content.split(" ", 1)[1]
    except IndexError:
        arguments = ""  # command didn't take any arguments

    new_content = f"{used_prefix}{command} {arguments}".strip()
    message.content = new_content  # overwriting the "original" message

    await bot.process_commands(message)  # processing commands with the new, updated message

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 2021-07-15
    • 1970-01-01
    • 2011-02-11
    • 2010-12-01
    • 2011-01-05
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多