-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
227 lines (182 loc) · 7.98 KB
/
bot.py
File metadata and controls
227 lines (182 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
"""
FactCheckBot — Main Entry Point
https://github.com/liveupx/factcheckbot
An open-source AI-powered fact-checking bot for Reddit.
Responds to !FactCheck triggers with verified verdicts.
Developer: Liveupx.com
License: MIT
"""
import sys
import time
import logging
from collections import deque
from datetime import datetime
import praw
from praw.models import Comment
from src.config import Config
from src.checker import fact_check
from src.database import Database
# ── Logging ─────────────────────────────────────────────────────
logging.basicConfig(
level=getattr(logging, Config.LOG_LEVEL),
format="%(asctime)s | %(name)-18s | %(levelname)-7s | %(message)s",
handlers=[
logging.FileHandler(Config.LOG_FILE, encoding="utf-8"),
logging.StreamHandler(sys.stdout),
],
)
log = logging.getLogger("factcheckbot")
# ── Rate Limiter ────────────────────────────────────────────────
class RateLimiter:
"""Sliding-window rate limiter to stay within Reddit guidelines."""
def __init__(self):
self._window: deque = deque()
self._last = 0.0
def acquire(self) -> bool:
now = time.time()
while self._window and self._window[0] < now - 3600:
self._window.popleft()
if len(self._window) >= Config.MAX_REPLIES_PER_HOUR:
return False
if now - self._last < Config.MIN_REPLY_INTERVAL:
return False
return True
def record(self):
now = time.time()
self._window.append(now)
self._last = now
@property
def wait_seconds(self) -> float:
now = time.time()
waits = []
if now - self._last < Config.MIN_REPLY_INTERVAL:
waits.append(Config.MIN_REPLY_INTERVAL - (now - self._last))
if len(self._window) >= Config.MAX_REPLIES_PER_HOUR and self._window:
waits.append(self._window[0] + 3600 - now)
return max(waits) if waits else 0
# ── Bot ─────────────────────────────────────────────────────────
class FactCheckBot:
"""
Core bot class.
Monitors Reddit comment streams for the trigger phrase,
runs the fact-checking pipeline, and posts replies.
"""
def __init__(self):
self._validate()
self.reddit = praw.Reddit(
client_id=Config.REDDIT_CLIENT_ID,
client_secret=Config.REDDIT_CLIENT_SECRET,
username=Config.REDDIT_USERNAME,
password=Config.REDDIT_PASSWORD,
user_agent=Config.USER_AGENT,
)
self.db = Database(Config.DB_PATH)
self.limiter = RateLimiter()
log.info("Authenticated as u/%s", Config.REDDIT_USERNAME)
log.info("Monitoring: r/%s", Config.SUBREDDITS)
log.info("Trigger: %s", Config.TRIGGER)
# ── Validation ──────────────────────────────────────────────
@staticmethod
def _validate():
missing = []
for key in ("REDDIT_CLIENT_ID", "REDDIT_CLIENT_SECRET",
"REDDIT_USERNAME", "REDDIT_PASSWORD", "GROQ_API_KEY"):
if not getattr(Config, key, None):
missing.append(key)
if missing:
log.error("Missing config: %s", ", ".join(missing))
log.error("Copy .env.example → .env and fill in your keys.")
sys.exit(1)
# ── Context extraction ──────────────────────────────────────
@staticmethod
def _get_claim_text(comment: Comment) -> str:
"""
Determine what text to fact-check.
Priority:
1. Text after the trigger phrase in the comment itself
2. The parent comment body
3. The parent submission title + body
"""
body = comment.body
after = body.lower().split(Config.TRIGGER.lower(), 1)[-1].strip()
if len(after) > 10:
return after
parent = comment.parent()
if isinstance(parent, Comment):
return parent.body
return f"{parent.title}. {parent.selftext}" if parent.selftext else parent.title
# ── Process a single comment ────────────────────────────────
def _process(self, comment: Comment):
cid = comment.id
if self.db.is_processed(cid):
return
if not self.limiter.acquire():
wait = self.limiter.wait_seconds
log.warning("Rate-limited — waiting %.0fs", wait)
time.sleep(wait)
sub = str(comment.subreddit)
author = str(comment.author or "[deleted]")
log.info("Processing %s in r/%s by u/%s", cid, sub, author)
try:
text = self._get_claim_text(comment)
result = fact_check(text)
if result is None:
reply_body = (
"I couldn't identify a clear factual claim to check.\n\n"
f"Try tagging me with a specific statement, e.g.:\n\n"
f"`{Config.TRIGGER} The Earth is flat`"
f"{Config.FOOTER}"
)
else:
reply_body = result.to_reddit_comment()
reply = comment.reply(reply_body)
self.limiter.record()
self.db.save(
comment_id=cid,
subreddit=sub,
author=author,
claim=result.claim if result else "N/A",
verdict=result.verdict if result else "NO_CLAIM",
confidence=result.confidence if result else 0,
reply_id=reply.id if reply else "",
)
if result:
log.info("Replied: %s (%d%%)", result.verdict, result.confidence)
except praw.exceptions.RedditAPIException as exc:
log.error("Reddit API error: %s", exc)
self.db.log_error(cid, str(exc))
if "RATELIMIT" in str(exc).upper():
log.warning("Reddit rate-limit hit — sleeping 120s")
time.sleep(120)
except Exception as exc:
log.error("Error on %s: %s", cid, exc, exc_info=True)
self.db.log_error(cid, str(exc))
# ── Main loop ───────────────────────────────────────────────
def run(self):
"""Start the bot. Blocks forever until Ctrl+C."""
log.info("=" * 56)
log.info(" FactCheckBot by Liveupx.com")
log.info(" %s", datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"))
log.info("=" * 56)
stats = self.db.stats()
log.info("Lifetime: %d checks processed", stats["total"])
stream = self.reddit.subreddit(Config.SUBREDDITS)
while True:
try:
for comment in stream.stream.comments(skip_existing=True):
if comment is None:
continue
if Config.TRIGGER.lower() not in comment.body.lower():
continue
if str(comment.author).lower() == Config.REDDIT_USERNAME.lower():
continue
self._process(comment)
except KeyboardInterrupt:
log.info("Shutting down.")
break
except Exception as exc:
log.error("Stream error: %s — reconnecting in 30s", exc)
time.sleep(30)
# ── Entry ───────────────────────────────────────────────────────
if __name__ == "__main__":
FactCheckBot().run()