【问题标题】:Catching Argparse errors and passing it to Discord client捕获 Argparse 错误并将其传递给 Discord 客户端
【发布时间】:2018-06-04 19:10:45
【问题描述】:

我创建了一个 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)发送到客户端,同时将错误消息打印到命令行 - 我真的想要相反,将错误消息发送到客户端。我该怎么做?

【问题讨论】:

  • 查看单元测试文件github.com/python/cpython/blob/master/Lib/test/test_argparse.py。它有一个捕获消息的ArgumentParser 子类。
  • 如何使用子类来捕获错误?能给个代码示例吗?
  • argparse 文档还简要讨论了自定义 errorexit 方法。您必须在 argparse.py 中研究该代码

标签: python argparse discord discord.py


【解决方案1】:

您的第一个错误是使用argparse。这绝对是错误的工具。您应该使用 discord.ext.commands 扩展中内置的 command parsingerror handling

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.")

【讨论】:

  • @MonkeyBot2020 哎呀,on_command_error 应该用@bot.event 装饰,而不是@bot.error。立即尝试。
  • 我是ctx.send,但感谢您的帮助,伙计! Discord.py 现在正在运行,我的项目已经启动并运行!
猜你喜欢
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
  • 2018-09-03
  • 2015-11-24
  • 1970-01-01
  • 2017-04-02
  • 2018-06-14
  • 1970-01-01
相关资源
最近更新 更多