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

如何修改Python代码解决Telegram机器人的不可达代码错误

解决Telegram机器人代码不可达及定时任务与bot轮询共存问题

问题原因

你的代码里while True是无限死循环,程序会一直卡在这个循环里执行,永远到不了下面的if __name__ == '__main__'代码块,所以PyCharm提示“最后两行代码不可达”。同时,schedule定时任务依赖run_pending()的循环调用才能触发,但直接和bot的polling()串行运行的话,总有一方会被阻塞。

解决方案:用多线程实现任务并行

把schedule的循环放到单独的线程里,让它和bot的轮询任务同时运行,既解决代码不可达问题,又保证两个功能都正常工作。修改后的代码如下:

import telebot
import gspread
import datetime
import schedule
import time
import threading

bot_token = '____'
googlesheet_id = '___'
bot = telebot.TeleBot(bot_token)
gc = gspread.service_account(filename='.json')
sh = gc.open('___')
wks = sh.worksheet('sheet1')
CHAT_ID = "___"

def check_date():
    current_date = datetime.datetime.now()
    current_date_string = current_date.strftime('%d.%m.%Y')
    try:
        # 查找当前日期对应的行
        search_data = wks.find(current_date_string)
        row_data = wks.row_values(search_data.row)
        bot.send_message(CHAT_ID, '%s expires today' % (row_data[0]))
    except gspread.exceptions.CellNotFound:
        # 处理找不到日期的情况,避免程序崩溃
        pass

# 设置每日定时任务
schedule.every().day.at("12:00:00").do(check_date)

def run_schedule_loop():
    # 单独的循环用于触发schedule任务
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == '__main__':
    # 启动schedule线程,daemon=True表示主线程结束时自动终止该线程
    schedule_thread = threading.Thread(target=run_schedule_loop, daemon=True)
    schedule_thread.start()
    
    # 启动Telegram bot的轮询
    bot.polling(none_stop=True)

关键修改说明

  1. 新增线程支持:导入threading模块,把schedule的循环封装成独立函数,通过线程运行,不阻塞主线程的bot轮询。
  2. 修复不可达问题:把所有执行逻辑放到if __name__ == '__main__'块内,确保代码能正常执行到bot.polling。
  3. 异常处理:给check_date函数加了CellNotFound异常捕获,避免找不到对应日期时程序直接崩溃。
  4. 优化资源使用:去掉了check_date里重复的sh = gc.open('___'),直接复用全局的表格对象,减少不必要的资源消耗。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:27:28