【问题标题】:How make a typo message?如何制作拼写错误信息?
【发布时间】:2021-10-08 16:49:01
【问题描述】:

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

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

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

【问题讨论】:

标签: python-3.x discord.py


【解决方案1】:

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

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')

【讨论】:

  • 请记住,如果您的机器人的命令前缀足够常见,那么用户很可能实际上是在尝试使用同一服务器/公会中的其他机器人。因此,您应该将阈值(if 右侧的值)设置得相当高,以便它仅在您确定是拼写错误的单词上触发,而不仅仅是您不知道的命令.
猜你喜欢
  • 1970-01-01
  • 2011-07-21
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 2019-07-12
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
相关资源
最近更新 更多