This repository has been archived by the owner on Sep 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathredditbot.py
224 lines (192 loc) · 7.2 KB
/
redditbot.py
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
"""
Reddit bot that checks mentions, and launches brain.py when new mentions are detected
"""
import argparse
import os
from pprint import pprint
import re
import time
import praw
import prawcore
from praw.models import Comment, Submission
from tinydb import TinyDB
import yaml
import subprocess
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--check-replied",
help="Check if we have replied already first, only necessary once",
action="store_true",
default=False,
)
parser.add_argument(
"--config",
help="Config file path (default: ./config.yaml)",
type=str,
default="./config.yaml",
)
parser.add_argument(
"--log-db",
help="Log db path (default: ./lob_db.json",
type=str,
default="./log_db.json",
)
args = parser.parse_args()
assert os.path.isfile(args.config)
assert os.path.isfile(args.log_db)
return args
def load_config_yaml(file):
with open(file) as fp:
config = yaml.safe_load(fp)
return config
class MentionsBot:
def __init__(
self,
config,
config_file,
db_file,
):
self.config = config
self.config_file = config_file
self.reddit = praw.Reddit(check_for_async=False, **config["user_info"])
self.inbox = praw.models.Inbox(self.reddit, _data={})
self.whitelisted_subreddits = set(config["whitelisted"])
self.blacklisted_subreddits = set(["suicidewatch", "depression"]).union(
set(config["blacklisted"])
)
self.whitelisted_subreddits = set(
[s.lower() for s in self.whitelisted_subreddits]
)
self.blacklisted_subreddits = set(
[s.lower() for s in self.blacklisted_subreddits]
)
self.db = TinyDB(db_file)
self.db_file = db_file
self.replied = set()
self.fill_replied()
def fill_replied(self):
"""
Populates the replied set
"""
for entry in self.db.all():
self.replied.add(entry["mention_id"])
if "parent_id" in entry:
self.replied.add(entry["parent_id"])
def clear_already_replied(self):
"""
Go through mentions manually to tick off if we have already replied
"""
for mention in self.inbox.mentions(limit=None):
if mention.id not in self.replied:
if isinstance(mention, Comment):
parent = mention.parent()
reply_info = {
"mention_id": mention.id,
"mention_username": mention.author.name
if mention.author
else None,
"mention_text": mention.body,
"mention_date": mention.created_utc,
"subreddit": mention.subreddit.display_name.lower(),
"parent_id": parent.id,
"parent_username": parent.author.name
if parent.author
else None,
"outcome": "Already replied, but not found in DB",
}
if isinstance(parent, Comment):
parent.refresh()
replies = parent.replies.list()
elif isinstance(parent, Submission):
replies = parent.comments.list()
else:
replies = None
if replies:
reply_authors = [r.author for r in replies]
if "animalsupportbot" in reply_authors:
self.replied.add(mention.id)
self.replied.add(parent.id)
self.db.insert(reply_info)
def check_mentions(self, limit=None):
"""
Check for mentions, run brain.py if a valid mention is detected
"""
for mention in self.inbox.mentions(limit=limit):
reply_info = {
"mention_id": mention.id,
"mention_username": mention.author.name if mention.author else None,
"mention_text": mention.body,
"mention_date": mention.created_utc,
"subreddit": mention.subreddit.display_name.lower(),
}
# Skip mention if not in whitelisted subreddits
if (
mention.subreddit.display_name.lower()
not in self.whitelisted_subreddits
):
reply_info[
"outcome"
] = "Mention not in whitelisted subreddit: {}".format(
mention.subreddit.display_name.lower()
)
self.replied.add(mention.id)
self.db.insert(reply_info)
continue
# Skip mention if included in blacklisted subreddits
# TODO: currently irrelevant as whitelist exists, enable this if whitelist is not enabled
if mention.subreddit.display_name.lower() in self.blacklisted_subreddits:
reply_info["outcome"] = "Blacklisted Subreddit"
self.replied.add(mention.id)
self.db.insert(reply_info)
continue
# Proceed if mention has not been dealt with
if mention.id not in self.replied:
self.launch_brain()
self.replied.add(mention.id)
def launch_brain(self):
"""
Closes db, runs brain.py, opens db again
"""
self.db.close()
p = subprocess.call(["python3", "brain.py", "--log-db", self.db_file, "--config", self.config_file])
self.db = TinyDB(self.db_file)
def run(self, refresh_rate=600, timeout_retry=600, check_replied=True, limit=None):
"""
Run the bot, checking for mentions every refresh_rate seconds
In case of timeout, waits for timeout_retry seconds
If check_replied is True, will check all previous mentions to see if we have already replied
"""
if check_replied:
print("Checking previous mentions to see if we have replied already...")
self.clear_already_replied()
while True:
try:
self.check_mentions(limit=limit)
print(
"{}\tReplied to mentions, sleeping for {} seconds...".format(
time.ctime(), refresh_rate
)
)
time.sleep(refresh_rate)
except prawcore.exceptions.ServerError or prawcore.exceptions.ResponseException:
print(
"Got a ServerError, sleeping for {} seconds before trying again...".format(
timeout_retry
)
)
time.sleep(timeout_retry)
if __name__ == "__main__":
args = parse_args()
config = load_config_yaml(args.config)
pprint(config)
refresh_rate = int(config["refresh_rate"])
mb = MentionsBot(
config,
args.config,
args.log_db,
)
mb.run(
refresh_rate=refresh_rate,
check_replied=args.check_replied,
)