【发布时间】: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