Python Discord bot 在异常时发送文本
Python Discord bot send text upon exception
我的 Discord 机器人中有一个功能,它充当一个神奇的 8 球,您可以在其中提出问题并给出随机答复。调用函数但未询问任何问题时会发生异常,我想将某种错误消息打印到调用它的通道,以通知用户发生了此错误。这是我的尝试:
@client.command(aliases=['8ball', 'eightball'])
async def _8ball(ctx, *,question):
responses = ['yes', 'no', 'maybe so']
response = random.choice(responses)
try:
await ctx.send(f'Question: {question}\n\
Answer: {response}')
except MissingRequiredArgument:
await ctx.send("Please ask a question")
pass
但是除了在终端中,什么也没有打印出来。
有什么建议吗?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument) and "replace me" in str(error):
await ctx.send("You're missing a required argument idiot.¯\_(ツ)_/¯")
使用 discord.py 你不能真正使用 try and except。您需要检查 on_command_error 事件。将 "replace me"
替换为 MissingRequiredArgument 错误后出现的任何内容。例如MissingRequiredArgument: arg is a required argument that is missing.
然后将 "replace me"
替换为 "arg is a required argument that is missing"
顺便说一句,下次当您在代码中收到错误时,请将它们添加到您的问题中。它帮助我们了解出了什么问题。
我的 Discord 机器人中有一个功能,它充当一个神奇的 8 球,您可以在其中提出问题并给出随机答复。调用函数但未询问任何问题时会发生异常,我想将某种错误消息打印到调用它的通道,以通知用户发生了此错误。这是我的尝试:
@client.command(aliases=['8ball', 'eightball'])
async def _8ball(ctx, *,question):
responses = ['yes', 'no', 'maybe so']
response = random.choice(responses)
try:
await ctx.send(f'Question: {question}\n\
Answer: {response}')
except MissingRequiredArgument:
await ctx.send("Please ask a question")
pass
但是除了在终端中,什么也没有打印出来。 有什么建议吗?
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument) and "replace me" in str(error):
await ctx.send("You're missing a required argument idiot.¯\_(ツ)_/¯")
使用 discord.py 你不能真正使用 try and except。您需要检查 on_command_error 事件。将 "replace me"
替换为 MissingRequiredArgument 错误后出现的任何内容。例如MissingRequiredArgument: arg is a required argument that is missing.
然后将 "replace me"
替换为 "arg is a required argument that is missing"
顺便说一句,下次当您在代码中收到错误时,请将它们添加到您的问题中。它帮助我们了解出了什么问题。