【问题标题】:How to extract one value at a time?如何一次提取一个值?
【发布时间】:2021-11-21 21:07:01
【问题描述】:

我正在尝试使用 Telebot 模块添加一个“/fact”命令,该模块从 API 返回关于狗的事实。但是,我希望它一次只返回一个事实,并且每次都返回一个新事实。我只是不知道如何处理这个问题。这是我的代码:

@bot.message_handler(commands=['fact'])
def get_fact(message):
    index = 0
    while True:
        facts = requests.get('https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=' + str(index)).json()
        f = facts[0]['fact']
        index += 1
        bot.send_message(message.chat.id, f)

或者:

@bot.message_handler(commands=['fact'])
def get_fact(message):
        facts = requests.get('https://dog-facts-api.herokuapp.com/api/v1/resources/dogs/all').json()
        f = list(facts)
        iterator = iter(f)
        bot.send_message(message.chat.id, iterator.__next__()['fact'])

【问题讨论】:

    标签: python telegram-bot py-telegram-bot-api


    【解决方案1】:

    您需要在命令函数定义之外初始化索引,以便它不会每次都重置,然后您可以从 dogfacts API 中获取一个事实并确认从 JSON 有效负载接收到一个事实。如果它为空,则将 factIndex 重置为 1 并重新开始,这样您每次都会显示一个新的事实,直到到达事实列表的末尾。

    factIndex = 1 # Start the index
    
    @bot.message_handler(commands=['fact'])
    def get_fact(message):
        facts = json.loads(requests.get("https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=" + str(factIndex)).content)
        
        # Check to see if we obtained a fact
        if (not facts): # If we got not fact
            factIndex = 1 # Reset the index
            facts = json.loads(requests.get("https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index=" + str(factIndex)).content)
    
        bot.send_message(message.chat.id, facts[0]["fact"])
    

    【讨论】:

    • 据我了解,我需要将factIndex全球化才能使用,对吧?
    • 是的,这是正确的——如果你把它放在函数中,那么它每次都会被重置。
    • 谢谢!这很有帮助。
    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 2016-01-21
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多