【发布时间】: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