我正在开发一个电报机器人。有一些命令,在我的例子中是/leaderboard
命令可以有参数(基本上是命令后面的任何参数)。
我想为页面添加一个参数int,为类别添加一个int参数。它们都是可选的。
我想做一些类似这样的事情:
/leaderboard {page} {category}
所以我可以这样做:
page, category = text.split(" ")
因为两者都是可选的,所以我的问题是:我如何才能摆脱这样的问题:我不知道第一个参数是指向页面还是引用类别(如果页面未指定,则保留为可选)。因为如果用户不指定页面,类别就会放在第一位。
我想让它变得用户友好。
我是这样想的:
/leaderboard page={int} categ={int}
然后
for arg in text.split(" "):
if arg.startswith("page"):
page = arg.split("=")[1]
elif arg.startswith("categ"):
categ = arg.split("=")[1]我只是在这里写的代码,所以它可能是错误的,但我更担心的是使用的概念,而不是如果在代码中。所以我问你是否有比这些更好的解决方案。提前谢谢。
发布于 2018-01-04 15:51:19
尝试如下所示:
在我的例子中,我添加了两个变量和布尔型category_only
在try部分中,im检查第一个参数中是否有int (count = int(args))
如果不是,在“除了ValueError”中,我将category_only设置为true并处理这种情况。我认为你应该尝试解析第二个参数,如果只有一个参数,则使用额外的变量。
@run_async
def cats_command(self, bot, update, args):
logging.info(str(update.message.from_user) + ' /cats')
count, category = 3, ''
category_only = False
try:
if int(args[0]) > 20:
raise TooMuchCountError('too much')
if int(args[0]) < 1:
raise TooSmallCountError('too small')
count = int(args[0])
except TooMuchCountError:
update.message.reply_text(
TextMessages.too_much_count_error_message.format(count))
except TooSmallCountError:
update.message.reply_text(
TextMessages.too_small_count_error_message.format(args[0]))
except IndexError:
update.message.reply_text(
TextMessages.index_error_message.format(count))
except ValueError:
category_only = True
try:
if category_only:
category = str(args[0])
else:
category = str(args[1])
l = map(lambda x: x.name, self.categories)
if category not in l:
raise WrongCategoryError('not in list')
except WrongCategoryError:
update.message.reply_text(
TextMessages.worng_category_error_message)
category = ''
except IndexError:
pass
logging.info(' catting for user {}'.format(update.message.from_user.first_name))
images = Parser.get_images('xml', count, category)所以,你的代码:
args = text.split(" ")
category_only = False;
page, category = 0,0
try:
category = int(args[0])
except ValueError:
print('there is no good params at all!')
/* catch this and return*/
try:
page = int(args[1])
except ValueError:
category_only = True您还可以使用page=-1或其他值来避免布尔变量,然后像"if page > -1“那样检查它。
https://stackoverflow.com/questions/48088104
复制相似问题