Advertisement
Guest User

Untitled

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