【发布时间】:2018-06-04 19:10:45
【问题描述】:
我创建了一个 Discord 机器人,它接受命令,使用 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)发送到客户端,同时将错误消息打印到命令行 - 我真的想要相反,将错误消息发送到客户端。我该怎么做?
【问题讨论】:
-
查看单元测试文件github.com/python/cpython/blob/master/Lib/test/test_argparse.py。它有一个捕获消息的
ArgumentParser子类。 -
如何使用子类来捕获错误?能给个代码示例吗?
-
argparse 文档还简要讨论了自定义
error和exit方法。您必须在argparse.py中研究该代码
标签: python argparse discord discord.py