Search code examples
pythontelegram-botpy-telegram-bot-api

How to extract one value at a time?


I'm trying to add a '/fact' command with Telebot module which returns a fact about dogs from API. However, I want it to return only one fact at a time, and a new one each time. I just don't know how to approach the issue. Here's my code:

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

OR:

@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'])

Solution

  • You need to initialize the index outside of the command function definition so that it is not reset every time, with that you can then fetch a fact from the dog facts API and confirm that a fact was received from the JSON payload. If it is empty then reset the factIndex back to 1 and start again, this way you display a new fact every time until you reach the end of the fact list.

    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"])