python - 捕获 Argparse 错误并将其传递给 Discord 客户端
问题描述
我创建了一个 Discord 机器人,它接受命令,使用 argparse 模块解析它们并将答案传递回 Discord 客户端。但是,我也对如何将错误返回给客户端感到困惑。这是代码:
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import random
import asyncio
import argparse
client = discord.Client()
bot = commands.Bot(command_prefix='#')
#Tells you when the bot is ready.
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
#The bot listens in on every message.
@bot.event
async def on_message(message):
#New command beginning with # to make the bot say "Hello there!" Always remember to begin with # as you have specified the command prefix as # above.
if message.content.lower().startswith("#greet"):
userID = message.author.id
await bot.send_message(message.channel, "<@" + userID + ">" + " Hello there!")
#Another command that accepts parameters.
if message.content.lower().startswith("#say"):
args = message.content.split(" ") #This turns everything in the string after the command "#say" into a string.
await bot.send_message(message.channel, args[1:])
await bot.send_message(message.channel, " ".join(args[1:])) #This joins all the strings back without [] and commas.
#Another, more sophisticated command that accepts parameters parses them.
if message.content.lower().startswith("#example_function"):
args = message.content.split(" ")
#Pass arguments through argparse module.
parser = argparse.ArgumentParser(description="Example program that accepts input and parses them using argparse...")
parser.add_argument("var", nargs='?', type=int, default=10, help="This is an example variable...")
#Catch errors and pass them back to the client.
try:
#The variable "dict" is a DICTIONARY. You'll have to access each variable by calling attribute["variable"].
dict = vars(parser.parse_args(args[1:]))
await bot.send_message(message.channel, attribute["var"])
except SystemExit as e:
await bot.send_message(message.channel, e)
bot.run('...')
上面的代码只是将系统错误(即 2)发送到客户端,同时将错误消息打印到命令行 - 我真的想要相反,将错误消息发送到客户端。我该怎么做呢?
解决方案
您的第一个错误是使用argparse
. 这绝对是错误的工具。您应该使用扩展中内置的命令解析和错误处理。discord.ext.commands
from discord.ext import commands
bot = commands.Bot('#')
@bot.event
async def on_command_error(ctx, error):
channel = ctx.message.channel
if isinstance(error, commands.MissingRequiredArgument):
await bot.send_message(channel, "Missing required argument: {}".format(error.param))
@bot.command(pass_context=True)
async def greet(ctx):
await bot.say("{} Hello there!".format(ctx.author.mention))
@bot.command(pass_context=True, name="say")
async def _say(ctx, *, message):
await bot.say(message)
@bot.command(pass_context=True)
async def compton_scatter_eq(ctx, a: int, b: int, c):
await bot.say(str(a + b) + c)
@compton_scatter_eq.error
async def scatter_error(ctx, error):
channel = ctx.message.channel
if isinstance(error, commands.BadArgument):
await bot.send_message(channel, "Could not convert argument to an integer.")
推荐阅读
- react-native - 无法在 StackNavigator 中显示对话框 - React Native
- json - JSON 格式的日期
- node.js - 使用 Node 代理 HTTP 到 HTTPS
- firebase - 'AppAnalytics.logLogin'('未来
Function()') 不是 'FirebaseAnalytics.logLogin' ('logLogin') 的有效覆盖 - asp.net-core - 如何获取 foreach 中每个项目的先前值
- javascript - Flow.js 不知道 React 中存在 ComponentProps
- unix - 如何从 Unix 的平面文件中删除页眉、页脚和第一列?
- python - 如何在 Python 中动态格式化模板化字符串?
- python - 执行除法运算时,如何使该算法返回整数?
- javascript - 如何通过更改宽度并在其中插入图标来设置 vue-bootstrap-datetimepicker 的样式?