python-3.x - 如何制作拼写错误信息?
问题描述
当用户打错字时,我想添加类似的命令建议。
示例:右命令:clear // 用户输入:Cler // 机器人响应:您的意思是“clear”吗?
我听说了difflib.get_close_matches
,我可以在 .py 脚本中使用它,但不能使用 discord.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')
推荐阅读
- c++ - GDB:在未捕获的 C++ 异常后获取有用的堆栈跟踪
- ruby-on-rails-5 - 错误(状态 402)(请求 req_QPLfwLnwBf2OeY)您的卡资金不足
- python - 如何迭代 (key, value) boost::python:dict
- linux - 运行`helm version`时`错误:找不到分蘖`
- angular - 角度条件的ng级问题?
- vb.net - 如何在没有 ElementID 的情况下自动填充 webbrowser 表单?
- django - 用于文件上传的 Django UpdateView 和 ModelForm 不起作用
- mobile - 使用 MobileFirst 的基于位置的推送通知
- mysql - 当我没有匹配的列时如何从其他表中获取特定 id 的结果
- javascript - 使用@public JsDoc 标记和@export 会导致警告