首页 文章

Discord.py的命令解析

提问于
浏览
-2

是否有一个类似于'argparse'模块的Discord.py命令参数解析器?我创建了一个discord bot,接受2个整数和1个字符串变量,处理它们并将结果输出到客户端 . 当用户正确使用它时,这一切都很好,但是当它们不能正常使用时,我需要一种简单的方法将错误传递给客户端,告诉用户他们错误地使用了命令 . 如果我可以使用argparse就好了,否则我将不得不从头开始编写一个解析器 - 这将是一个痛苦!这是代码:

import discord
from discord.ext import commands
from discord.ext.commands import Bot
import random
import asyncio

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("#compton_scatter_eq"):
        args = message.content.split(" ")
        a = int(args[1])
        b = int(args[2])
        c = args[3]
        result = str(a + b) + c
        await bot.send_message(message.channel, result)

bot.run(...)

你能告诉我是否有一个类似于argparse的模块,或者是否有办法在Discord.py中使用argparse模块?

编辑:

@Rishav - 你真是太棒了!它奏效了,但现在我遇到了一个新问题 . 这是我的代码:

#Another, more sophisticated command that accepts parameters parses them.
    if message.content.lower().startswith("#compton_scatter_eq"):
        args = message.content.split(" ")

        #Pass arguments through argparse module.
        parser = argparse.ArgumentParser(description="Example program to get my bot to use argparse")
        parser.add_argument("a", nargs='?', type=int, default=10, help="This is your first variable.")
        parser.add_argument("b", nargs='?', type=int, default=10, help="This is your second variable.")
        parser.add_argument("c", nargs='?', type=str, default="East", help="This is your third variable.")

        #Catch errors and pass them back to the client.
        try:
            await bot.send_message(message.channel, vars(parser.parse_args(args[1:])))
        except BaseException as e:
            await bot.send_message(message.channel, str(e))

不幸的是,错误出现在命令行终端中,但不在客户端中 . 如何将错误传递回客户端?我如何访问变量a,b和c?感谢您的帮助到目前为止!

2 回答

  • -1

    您正在导入 discord.ext.commands 扩展程序,但实际上并未使用它 . It has great, easy to write command parsing built in .

    from discord.ext import commands
    
    bot = commands.Bot('#')
    
    @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)
    
    @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))
        elif isinstance(error, commands.BadArgument):
            bot.send_message(channel, "Could not parse commands argument.")
    

    如果您想要更细粒度的错误处理,可以实现per-command error handlers

  • 1

    是的,请参阅argparse文档中的this示例 .

    它完全描述了我的需求 .

    parser = argparse.ArgumentParser()
    parser.add_argument(
    ...'integers',metavar ='int',type = int,choices = range(10),
    ... nargs ='',help ='0到9'范围内的整数')
    parser.add_argument(
    ...' - sum',dest ='accumulate',action ='store_const',const = sum,
    ... default = max,help ='求和整数(默认:找到最大值)')
    parser.parse_args(['1','2','3','4'])
    命名空间(accumulate = <内置函数max>,整数= [1,2,3,4])
    parser.parse_args(['1','2','3','4',' - sum'])
    命名空间(accumulate = <内置函数sum>,整数= [1,2,3,4])

相关问题