首页 文章

捕获Argparse错误并将其传递给Discord客户端

提问于
浏览
0

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

1 回答

  • 0

    你的第一个错误是使用 argparse . 这绝对是错误的工具 . 您应该使用command parsing扩展内置的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.")
    

相关问题