You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Telebot调用狗事实API每次返回单条不重复的新事实

问题原因

  • 第一段代码的问题:index定义在函数内部,每次触发/fact命令都会被重置为0,同时嵌套了死循环,触发一次会无限发送消息,完全不符合预期。
  • 第二段代码的问题:每次触发命令都会重新请求全量事实列表、新建迭代器,永远只会返回列表第一条数据。

修复方案

基础版:所有用户共享同一条读取进度

在函数外部定义全局索引存储读取进度,每次调用后自增索引即可:

# 在get_fact函数外部定义全局索引,不要写在函数内部
current_index = 0

@bot.message_handler(commands=['fact'])
def get_fact(message):
    global current_index
    # 请求当前索引对应的事实
    resp = requests.get(f'https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index={current_index}')
    # 处理索引越界的情况,所有事实都遍历完就重置回0
    if not resp.json():
        current_index = 0
        resp = requests.get(f'https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index={current_index}')
    fact_content = resp.json()[0]['fact']
    bot.send_message(message.chat.id, fact_content)
    # 索引自增,下次调用取下一条
    current_index += 1

进阶版:每个用户单独维护读取进度,互不影响

用字典存储不同用户的对应索引,适配多用户使用场景:

# 键为用户chat_id,值为对应用户的当前读取索引
user_index_map = {}

@bot.message_handler(commands=['fact'])
def get_fact(message):
    user_id = message.chat.id
    # 新用户默认初始索引为0
    if user_id not in user_index_map:
        user_index_map[user_id] = 0
    current_index = user_index_map[user_id]
    
    resp = requests.get(f'https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index={current_index}')
    if not resp.json():
        user_index_map[user_id] = 0
        current_index = 0
        resp = requests.get(f'https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?index={current_index}')
    
    fact_content = resp.json()[0]['fact']
    bot.send_message(message.chat.id, fact_content)
    user_index_map[user_id] += 1

内容的提问来源于stack exchange,提问作者Dirael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 22:54:04