是否有一个类似于'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 回答
您正在导入
discord.ext.commands
扩展程序,但实际上并未使用它 . It has great, easy to write command parsing built in .如果您想要更细粒度的错误处理,可以实现per-command error handlers
是的,请参阅argparse文档中的this示例 .
它完全描述了我的需求 .