python:telegram bots命令参数

问题描述 投票:1回答:1

我正在开发一个电报机器人。有命令,在我的情况下,它是/leaderboard

命令可以有参数(基本上是命令之后的任何内容)。

我想为页面添加一个参数int,为类别添加一个int参数。它们都是可选的。

我想知道做的事情:

/leaderboard {page} {category}

所以我能做到:

page, category = text.split(" ")

既然两者都是可选的,我的问题是:如何解决我不知道的问题,如果第一个arg被引用到页面或类别(如果未指定页面并保留为可选)。因为如果用户没有指定页面,则该类别占据首位。

我想让它用户友好。

我在想的是:

/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]

我刚刚在这里写了代码,所以它可能是错的,但我更担心要使用的概念,而不是在代码中。所以我问你是否有比这更好的解决方案。提前致谢。

python parameters arguments telegram-bot
1个回答
1
投票

尝试这样的事情:

在我的情况下,我只添加了两个变量和布尔类别

在try部分我检查第一个arg中是否有int(count = int(args [0]))

如果没有,在“除ValueError”之外我将category_only设置为true并处理这种情况。我认为您应该尝试解析第二个arg,如果只有一个参数,则使用其他变量。

@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”

© www.soinside.com 2019 - 2024. All rights reserved.