Reddit评论机器人定向特定文本和链接帖子失效问题排查
Reddit评论机器人故障分析及修复方案
核心错误点
- 重复遍历subreddit流:代码里存在两个独立的
for submission in subreddit.stream.submissions()循环,第一个循环仅读取已回复帖子列表就陷入无限阻塞(stream是持续监听新内容的),永远无法执行到第二个处理评论的循环,这是机器人停止工作的直接原因。 - 错误调用
subreddit.comments.enable():该方法用于开启整个子reddit的评论功能,且需要子reddit管理员权限才能执行。你的机器人大概率没有此权限,调用后会直接抛出权限异常导致程序崩溃。另外,这个方法完全不符合你“对特定帖子评论”的需求场景。 - 过滤逻辑未生效:当前代码的评论逻辑是只要帖子未回复过就直接评论,之前的URL和标题条件判断没有和评论触发逻辑关联,完全没起到过滤作用。
修复后的代码
import random import time import datetime import os import praw sendSlackAlerts = False mybot = praw.Reddit("bot1") subreddit = mybot.subreddit("test") # 初始化已回复帖子文件 if not os.path.isfile("posts_replied_to.txt"): with open("posts_replied_to.txt", 'w') as f: f.write('') def docomment(): print("Bot started - Commenting every minute") # 一次性读取评论模板,避免重复IO操作 with open("randomposts.txt") as f: randomposts = f.read().split('|') # 一次性读取已回复列表并清理无效内容 with open("posts_replied_to.txt", 'r') as f: done = f.read().split(',') done = [id.strip() for id in done if id.strip()] # 仅保留一个流遍历循环,合并过滤与评论逻辑 for submission in subreddit.stream.submissions(): # 同时满足条件+未回复过才执行评论 if ('youtube.com' in submission.url and 'test text' in submission.title) and submission.id not in done: rand = random.randint(0, len(randomposts)-1) randompost = randomposts[rand] print(f"Replying to post: {submission.title}") try: submission.reply(randompost) except Exception as e: print(f"Failed to reply: {str(e)}") continue # 回复失败直接跳过,避免阻塞流程 # 延迟操作 for i in range(80): time.sleep(1) print(i) # 更新已回复列表与文件 done.append(submission.id) with open("posts_replied_to.txt", "a") as posts_replied_to: posts_replied_to.write(submission.id + ",") def go(): try: docomment() except KeyboardInterrupt: print("\nOk stopping bot") exit(0) except Exception as error: if not os.path.isfile("logs.txt"): with open("logs.txt", 'w') as f: f.write('') now = datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") with open("logs.txt", 'a') as f: f.write(f"\n{date}\n{str(error)}") print("Unknown error, find the error in logs.txt") print('Waiting for 30 min') time.sleep(60*30) if sendSlackAlerts: from slack import WebClient with open("slacktoken.txt") as f: slacktoken = f.read() client = WebClient(token=slacktoken) client.chat_postMessage( channel='alerts', text=f"An error has occured:\n{error}") go() go()
额外优化说明
- 补充了原代码缺失的模块导入,避免运行时依赖报错。
- 优化文件操作:一次性读取静态资源,用
with语句自动管理文件句柄,减少IO开销与资源泄漏风险。 - 增加回复异常捕获:避免因单个帖子回复失败(如权限限制、Rate Limit)导致整个机器人崩溃。
- 清理已回复列表中的空字符串,避免出现误判情况。
内容的提问来源于stack exchange,提问作者MasterMind
相关产品推荐
相关产品推荐

