假设用户输入的命令无效,机器人会建议使用(y / n)的命令?如果为y,则漫游器应触发建议的命令。我认为可以通过两种方式实现:
我似乎都无法正常工作。
这是一个例子,可以帮助你们更好地帮助我:
我们只说下面的代码来自一个叫做Joke.py的齿轮:
@commands.command()
async def joke(self,ctx):
await ctx.send("A Joke")
然后还有另一个齿轮“ CommandsCorrection.py”,它可以纠正用户使用的错误命令,这些命令保存在data.json文件中:
@commands.Cog.listener()
async def on_message(self, message):
channel = message.channel
prefix = get_prefix(self,message)
if message.author.id == bot.id:
return
elif message.content.startswith(prefix):
withoutprefix = message.content.replace(prefix,"")
if withoutprefix in data:
return
else:
try:
rightCommand= get_close_matches(withoutprefix, data.keys())[0]
await message.channel.send(f"Did you mean {prefix}%s instead? Enter Y if yes, or N if no:" %rightCommand)
def check(m):
return m.content == "Y" or "N" and m.channel == channel
msg = await self.client.wait_for('message', check=check, timeout = 10.0)
msg.content = msg.content.lower()
if msg.content == "y":
await channel.send(f'{prefix}{rightCommand}')
elif msg.content == "n":
await channel.send('You said no.')
except asyncio.TimeoutError:
await channel.send('Timed Out')
except IndexError as error:
await channel.send("Command Not Found. Try !help for the list of commands and use '!' as prefix.")
上面的代码中await message.channel.send(f"Did you mean {prefix}%s instead? Enter Y if yes, or N if no:" %rightCommand)
建议正确的命令并await channel.send(f'{prefix}{rightCommand}')
发送正确的命令。
因此,例如:
user : !jok
bot : Did you mean !joke instead? Enter Y if yes, or N if no:
user : y
bot : !joke **I want to trigger the command when it sends this message by reading its own message or my just calling that command/function
我应该怎么做?
一种解决方案是将命令的逻辑与命令回调分开,并将其放入自己的协程中。然后,您可以从任何命令回调中自由调用这些协程。
因此,您应将代码变成这样:
@bot.command()
async def my_command(ctx):
await ctx.send("Running command")
@bot.command()
async def other_command(ctx, arg):
if arg == "command":
await ctx.send("Running command")
变成这样的东西:
async def command_logic(ctx):
await ctx.send("Running command")
@bot.command()
async def my_command(ctx):
await command_logic(ctx)
@bot.command()
async def other_command(ctx, arg):
if arg == "command":
await command_logic(ctx)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句