Discord用户新帖子抓取Bot异常:仅抓取固定首帖问题排查
问题解决:Discord Bot仅抓取固定首帖不更新新帖子
问题根源
- 选择器未排除置顶帖:目标论坛的首帖可能是长期置顶的固定帖,原代码始终抓取页面第一个帖子,导致新帖无法被检测到。
- 请求未禁用缓存:
requests.get默认会接受服务器返回的缓存页面,可能无法获取最新的论坛内容。 - 初始化逻辑缺失:首次运行时直接发送首帖,且未提前初始化记录变量,可能导致重复发送或后续检测逻辑异常。
修复后的代码
import asyncio import requests from bs4 import BeautifulSoup import discord # Discord bot token BOT_TOKEN = "" # Discord channel ID CHANNEL_ID = "1106329342897827960" # 存储最新帖子链接的全局变量 latest_post_link = None async def check_for_updates(): global latest_post_link try: url = "https://forum.cfx.re/c/development/releases/7" # 添加请求头禁用缓存,强制获取最新页面 headers = { 'Cache-Control': 'no-cache', 'Pragma': 'no-cache' } response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, "html.parser") # 排除置顶帖,选择第一个非置顶的普通帖子 post_elements = soup.select("tr.topic-list-item:not(.pinned) a.title.raw-link.raw-topic-link") if post_elements: new_post_link = post_elements[0]["href"] post_title = post_elements[0].text.strip() if new_post_link != latest_post_link: channel = bot.get_channel(int(CHANNEL_ID)) if channel: message = f"新帖子:{post_title}\n链接:{new_post_link}" await channel.send(message) latest_post_link = new_post_link except Exception as e: print(f"检查更新时出错:{str(e)}") async def background_task(): # 初始化:先获取当前最新帖子链接,避免首次发送重复内容 await check_for_updates() while True: await asyncio.sleep(60) # 每60秒检查一次 await check_for_updates() # 创建Discord Bot实例 intents = discord.Intents.default() intents.typing = False intents.presences = False bot = discord.Client(intents=intents) @bot.event async def on_ready(): print(f"已登录为 {bot.user.name} ({bot.user.id})") print("------") # 启动后台任务,避免阻塞on_ready事件 asyncio.create_task(background_task()) # 运行Bot if __name__ == "__main__": asyncio.run(bot.start(BOT_TOKEN))
关键修改点
- 选择器优化:使用
tr.topic-list-item:not(.pinned)排除置顶帖,确保抓取的是最新用户发布的帖子。 - 禁用缓存:添加
Cache-Control和Pragma请求头,避免获取缓存的旧页面。 - 初始化逻辑调整:后台任务启动时先执行一次检查,初始化
latest_post_link,避免首次运行重复发送帖子;同时改用asyncio.create_task启动后台任务,避免阻塞on_ready事件。 - 通道存在性检查:添加
if channel:判断,防止因通道不存在导致报错。
内容的提问来源于stack exchange,提问作者RedPhoenix
相关产品推荐
相关产品推荐

