· 9 years ago · Jan 31, 2017, 11:34 PM
1import sqlite3
2from time import sleep, time
3import praw
4
5conn = sqlite3.connect('bdb_pa_FoxK56.db')
6c = conn.cursor()
7
8reddit = praw.Reddit(
9 client_id='',
10 client_secret='',
11 password='',
12 user_agent='Linux:borrow_limiter:0.1 (by /u/Foxk56)',
13 username=''
14)
15
16
17def build_db():
18 """Create a 3-column database table if it doesn't exist"""
19
20 c.execute("""CREATE TABLE IF NOT EXISTS bph(auth TEXT, time TEXT, id TEXT)""")
21 conn.commit()
22
23
24def monitor():
25 """Stream new submissions to /r/borrow and evaluate each
26 If the bot experiences an error, notify the owner and attempt to restart every 10 minutes.
27 If unable to restart after 5 attempts, stop the bot"""
28
29 notified = False
30 restart = 0
31 while restart < 6:
32 try:
33 subreddit = reddit.subreddit('borrow')
34 submission_stream = subreddit.stream.submissions()
35 for submission in submission_stream:
36 if '[req]' in str(submission.title).lower():
37 evaluate(submission)
38 except Exception as e:
39 reset = 'Reset {} {}\n'.format(time(), e)
40 with open('req_bot_log.txt', 'a') as log:
41 log.write(reset)
42 if not notified:
43 msg = 'Your bot experienced a terminal error and is attempting to restart.' \
44 'Please manually restart the bot to ensure a clean restart.'
45 reddit.redditor('Foxk56').message('BOT ERROR', msg)
46 notified = True
47 sleep(600)
48 restart += 1
49 continue
50 terminal = 'Shut down {}\n'.format(time())
51 with open('req_bot_log.txt', 'a') as log:
52 log.write(terminal)
53
54
55def evaluate(sub):
56 """Compare this sub's time with previous time and disposition"""
57
58 prev_auth, prev_time, prev_id = get_last(sub.author.name)
59 if prev_auth:
60 if sub.id != prev_id and sub.created_utc - float(prev_time) < 86400:
61 notify(sub)
62 else:
63 update_author(sub)
64 else:
65 new_author(sub)
66
67
68def get_last(author):
69 """Get the last post by this author. If no history, return 0"""
70
71 # (author, time, id)
72 c.execute("""SELECT * FROM bph WHERE auth=(?)""", (author,))
73 entries = [row for row in c.fetchall()]
74 if entries:
75 return entries[0]
76 return None, 0, None
77
78
79def notify(sub):
80 """Report previous post made < 24hrs ago"""
81
82 reason = """Redditor has made a [REQ] less than 24 hours ago"""
83 sub.report(reason)
84
85
86def update_author(sub):
87 """Find last post by author and update time/id"""
88
89 c.execute("""UPDATE bph SET time=(?), id=(?)
90 WHERE auth=(?)""", (sub.created_utc, sub.id, sub.author.name))
91 conn.commit()
92
93
94def new_author(sub):
95 """Create an entry for the author"""
96
97 c.execute("""INSERT INTO bph(auth, time, id)
98 VALUES (?,?,?)""", (sub.author.name, sub.created_utc, sub.id))
99 conn.commit()
100
101if __name__ == '__main__':
102 build_db()
103 monitor()