如何在discord.py中用feedparser更新RSS feed并避免重复发帖
解决Discord机器人重复发送Reddit帖子的问题
问题原因
- 每次循环固定取
Feed.entries[1],导致重复发送同一篇帖子 - 未持久化存储已发送帖子的标识,每次循环变量重置,无法实现去重逻辑
- 同时初始化了
discord.Client和commands.Bot两个实例,属于冗余操作,两者选其一即可
解决方案
- 统一使用
commands.Bot实例(适配tasks和commands扩展) - 将已发送帖子的唯一标识(用帖子
id,比标题更可靠)绑定到Bot实例上,避免循环重置 - 每次拉取RSS后,遍历最新帖子,仅发送未记录过的内容并更新已发送列表
修改后的代码
import discord import os import feedparser from discord.ext import tasks, commands # 仅保留一个Bot实例,避免冗余 bot = commands.Bot(command_prefix='$', intents=discord.Intents.default()) # 将已发送帖子ID集合绑定到Bot实例,防止循环重置 bot.sent_post_ids = set() @bot.event async def on_ready(): print(f'已登录为 {bot.user}') check_reddit_feed.start() @tasks.loop(seconds=30) async def check_reddit_feed(): feed = feedparser.parse('https://www.reddit.com/r/askreddit/.rss') channel_id = 351023004001763339 channel = bot.get_channel(channel_id) if not channel: print(f"无法找到ID为 {channel_id} 的频道") return # 遍历RSS条目(最新内容在前) for entry in feed.entries: post_id = entry.id if post_id not in bot.sent_post_ids: await channel.send(f"新帖子:{entry.title}\n{entry.link}") bot.sent_post_ids.add(post_id) # 仅发送最新一条,如需批量发送所有未发内容可删除此行 break bot.run(os.environ['TOKEN'])
关键修改说明
- 移除冗余的
discord.Client实例,统一使用commands.Bot管理机器人逻辑 - 用
bot.sent_post_ids存储已发送帖子的唯一ID,确保跨循环状态不丢失 - 使用帖子
id作为去重标识,避免标题重复导致的漏发或误判 - 添加频道不存在的异常判断,提升代码稳定性
内容的提问来源于stack exchange,提问作者Carter S
相关产品推荐
相关产品推荐

