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