-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot_sitewide.py
106 lines (69 loc) · 2.6 KB
/
bot_sitewide.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
"""
This bot searches for all Reddit posts that are from the reddit.com
domain and replies to them with a transcribed tweet.
"""
import praw
import config
from twitter import transcribe_tweet
POSTS_LOG = "./processed_posts.txt"
ERROR_LOG = "./error.log"
MESSAGE_TEMPLATE = open("./templates/en.txt", "r", encoding="utf-8").read()
def init_bot():
"""Inits the bot and checks for new posts."""
reddit = praw.Reddit(client_id=config.APP_ID, client_secret=config.APP_SECRET,
user_agent=config.USER_AGENT, username=config.REDDIT_USERNAME,
password=config.REDDIT_PASSWORD)
check_posts(reddit)
def check_posts(reddit):
"""Checks the latest posts from the twiter.com domain.
Parameters
----------
reddit : praw.Reddit
A Reddit instance.
"""
processed_posts = load_log(POSTS_LOG)
# We iterate over all new twitter.com posts.
for submission in reddit.domain("twitter.com").new(limit=100):
if "twitter.com" in submission.url and "status" in submission.url and submission.id not in processed_posts:
try:
reddit.submission(submission.id).reply(
transcribe_tweet(submission.url.replace("mobile.", ""), MESSAGE_TEMPLATE))
update_log(POSTS_LOG, submission.id)
print("Replied:", submission.id)
except Exception as e:
update_log(POSTS_LOG, submission.id)
log_error("{}:{}".format(submission.url, e))
print("Failed:", submission.id)
def load_log(log_file):
"""Reads the processed posts log file and creates it if it doesn't exist.
Returns
-------
list
A list of Reddit posts ids.
"""
try:
with open(log_file, "r", encoding="utf-8") as temp_file:
return temp_file.read().splitlines()
except FileNotFoundError:
with open(log_file, "a", encoding="utf-8") as temp_file:
return []
def update_log(log_file, item_id):
"""Updates the processed posts log with the given post id.
Parameters
----------
comment_id : str
A Reddit post id.
"""
with open(log_file, "a", encoding="utf-8") as temp_file:
temp_file.write("{}\n".format(item_id))
def log_error(error_message):
"""Updates the error log.
Parameters
----------
error_message : str
A string containing the faulty url and the exception message.
"""
with open(ERROR_LOG, "a", encoding="utf-8") as log_file:
log_file.write("{}\n".format(error_message))
if __name__ == "__main__":
init_bot()