【问题标题】:Command parsing for Discord.pyDiscord.py 的命令解析
【发布时间】:2018-11-12 17:57:48
【问题描述】:

Discord.py 是否有类似于“argparse”模块的命令参数解析器?我创建了一个不和谐的机器人,它接受 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 的模块,或者是否有办法将 argparse 模块与 Discord.py 一起使用?

编辑:

@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?感谢您迄今为止的帮助!

【问题讨论】:

  • 不清楚你在问什么。但是this在各个方面都优于argparse。

标签: python parameter-passing argparse discord discord.py


【解决方案1】:

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

我认为它完美地描述了您的需求。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
...     'integers', metavar='int', type=int, choices=range(10),
...     nargs='+', help='an integer in the range 0..9')
>>> parser.add_argument(
...     '--sum', dest='accumulate', action='store_const', const=sum,
...     default=max, help='sum the integers (default: find the max)')
>>> parser.parse_args(['1', '2', '3', '4'])
Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
>>> parser.parse_args(['1', '2', '3', '4', '--sum'])
Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])

【讨论】:

    【解决方案2】:

    您正在导入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

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2020-09-11
      • 2021-03-26
      • 2021-08-28
      • 2021-01-22
      • 2021-03-30
      • 2021-05-17
      • 2021-01-15
      • 2022-12-04
      相关资源
      最近更新 更多