Skip to main content
 首页 » 编程设计

python:电报机器人命令参数

2025年01月19日8powertoolsteam

我正在开发电报机器人。 有命令,在我的例子中是 /排行榜

命令可以有参数(基本上是命令后面的任何东西)。

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

我想做这样的事情:

/leaderboard {page} {category}

所以我可以这样做:

页面, 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] 

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

请您参考如下方法:

尝试这样的事情:

在我的例子中,我添加了两个变量和 bool 值 category_only

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

如果不是,在“除了 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 或其他值的 bool 变量,然后像“if page > -1”一样检查它