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