Telegram Bot调用last_chapter命令时图片发送给所有启动用户的问题
Telegram Bot 群发异常问题定位与修复方案
核心问题原因
- 全局可变对象滥用:你将
images、stripped_images定义为全局列表,每次调用download_last_chapter函数时,都是向列表末尾追加新的图片链接,永远不会清空旧数据,直接导致每次调用命令都会叠加发送之前所有请求的全部图片。 - 多线程竞态条件:
pyTelegramBotAPI默认启用多线程处理用户请求,当多个用户同时触发命令时,多个线程会同时修改全局的images、stripped_images列表,出现数据错乱,极端情况下会出现不同用户的请求数据交叉,触发发错人的问题。 - 异常被完全吞掉:你使用了
except: None的写法,忽略了所有发送过程中的报错,无法感知运行过程中的异常,进一步提升了问题定位的难度。 - 章节链接仅启动时爬取一次:
lastchapterlink仅在Bot服务启动时爬取一次,后续目标网站更新章节后,Bot无法感知到内容变化,永远只会返回服务启动时的最新章节。
修复方案
将所有可变的临时变量放到函数内部作用域,每次调用命令时重新初始化,避免全局共享导致的数据错乱和累积,同时补充必要的错误打印逻辑,章节爬取逻辑也调整为每次调用命令时重新请求,保证内容时效性。
修复后代码
import requests import os import telebot from bs4 import BeautifulSoup as bs API_KEY = os.getenv("API_KEY") bot = telebot.TeleBot(API_KEY) url_mainpage = "https://url.com" def download_last_chapter(): # 每次调用都先爬取最新的章节链接 soup = bs(requests.get(url_mainpage).content, "html.parser") full_link = soup.find("h5", class_="elementor-image-box-title") selectlist = full_link.select(".elementor-image-box-title a") lastchapterlink = selectlist[0]['href'] # 临时变量放在函数内部,每次调用重新初始化,不会累积也不会被其他线程修改 images = [] stripped_images = [] soup = bs(requests.get(lastchapterlink).content, "html.parser") images_link = soup.findAll("img") for img in images_link: images.append(img.get("src")) for link in images: stripped_images.append(link.strip()) return stripped_images @bot.message_handler(commands=["last_chapter"]) def send_images(message): stripped_images = download_last_chapter() for telegram_send in stripped_images: try: bot.send_photo(message.chat.id, photo = telegram_send) except Exception as e: # 打印错误信息方便排查 print(f"发送图片失败:{e},聊天ID:{message.chat.id},图片链接:{telegram_send}") bot.polling()
内容的提问来源于stack exchange,提问作者Miguel Arrieche
相关产品推荐
相关产品推荐

