首页 > 解决方案 > 如何制作拼写错误信息?

问题描述

当用户打错字时,我想添加类似的命令建议。

示例:右命令:clear // 用户输入:Cler // 机器人响应:您的意思是“clear”吗?

我听说了difflib.get_close_matches,我可以在 .py 脚本中使用它,但不能使用 discord.py

标签: python-3.xdiscord.py

解决方案


您可以拥有所有机器人命令的列表。然后,如果未找到命令,则使用命令错误事件和命令错误事件进行测试,如果未测试命令是否接近列表中的一个命令,然后向用户发送带有命令的消息。这是我如何做的一个例子):

import discord
from discord.ext import commands
from difflib import SequenceMatcher

BOT_PREFIX = '!'
bot = discord.Client(intents=discord.Intents.all(), status=discord.Status.dnd)
bot = commands.Bot(command_prefix=BOT_PREFIX)
bot_commands = ['Command_1', 'Command_2', 'Clear'] #Declare commands

@bot.event
async def on_message(message):
    global MESSAGE
    MESSAGE = message #So we can use message like a global
    await bot.process_commands(message)

@bot.event
async def on_command_error(ctx, error): #catch error
    if isinstance(error, commands.CommandNotFound):
        for i in bot_commands: #Looking for close matches in commands
            if float(SequenceMatcher(a=str(MESSAGE.content).replace(BOT_PREFIX, '').lower(), b=i.lower()).ratio()) > float(0.67): #You can adjust the second float
                await ctx.send(f'Did you mean {i}?') #Your message
                break #Ignore similiar matches
    #raise error (optional)

bot.run('token')

推荐阅读