Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # alot-of-bot
- # A bot for Alot
- # --------------
- import os
- import time
- import praw
- import json
- import requests
- from requests import HTTPError
- # Reddit
- # ------
- reddit = praw.Reddit('ThanksAlot by /u/my_hat_stinks v1.3')
- reddit.set_oauth_app_info(client_id='', client_secret='', redirect_uri='http://127.0.0.1:65010/authorize_callback')
- access_info = {
- 'access_token': '',
- 'refresh_token': '',
- 'scope': {'history', 'submit', 'edit', 'read', 'identity', 'save'}
- }
- reddit.refresh_access_information( access_info['refresh_token'] )
- reddit.set_access_credentials( **access_info )
- alotbot = reddit.get_me()
- subreddits = {}
- # Blacklist
- # ---------
- blacklist_user = ["alot-of-bot", "AlotOfLoops", "WeylandTheDwarf"]
- blacklist_phrase = ["(#bot)", "(#nobots)"] # Don't respond to bots or people that don't want bots
- # Phrases
- # -------
- phrase = {}
- # Used when there's no custom subreddit footer
- footer_default = """
- ___
- _I'm just a bot! ^^Don't ^^hurt ^^me!_
- """
- # Non-automated footer
- footer_manual = """
- ___
- _This comment was not automated!_
- _^^Comment ^^will ^^be ^^removed ^^if ^^downvoted_ ^^| [_^^Bot ^^Source_](http://pastebin.com/JtBuWff4) ^^| ^^[_Confused?_](http://hyperboleandahalf.blogspot.co.uk/2010/04/alot-is-better-than-you-at-everything.html)
- """
- # Generic footer text
- response_footer = """
- _^^Comment ^^will ^^be ^^removed ^^if ^^downvoted_ ^^| ^^[_Source_](http://pastebin.com/JtBuWff4) ^^| ^^[_Confused?_](http://hyperboleandahalf.blogspot.co.uk/2010/04/alot-is-better-than-you-at-everything.html)
- """
- # Temporary variables
- # -------------------
- last_id = {} # ID of the last comment we checked
- last_time = {} # Time of the last comment
- next_post = {} # Time of next post for limited subreddits
- for subname in subreddits: # Fill with placeholders
- last_id[subname] = ''
- last_time[subname] = 0
- # Search a subreddit
- # ------------------
- def search_sub( subname ):
- if 'limit' in subreddits[subname]:
- if subname not in next_post: # We've restarted or something, we need to find our last post
- next_post[subname] = 0 # If we've never posted
- for comment in alotbot.get_comments(limit=100):
- if (comment.subreddit.display_name.lower())==subname: # It's the right sub
- next_post[subname] = comment.created_utc + (subreddits[subname]['limit'] * 3600) # Hours to seconds
- break
- if next_post[subname]>time.time():
- print( "Failed to search subreddit '"+subname+"', limit reached." )
- return
- print( "Searching subreddit '" + subname + "'..." )
- sub = reddit.get_subreddit(subname) # Get our subreddit
- try:
- for comment in sub.get_comments(limit=100, place_holder=last_id[subname]):
- text = comment.body.lower() # Lower case
- if (comment.author.name in blacklist_user) or (any(string in text for string in blacklist_phrase)): # Blacklisted
- continue
- if (comment.id==last_id[subname]): # We've already checked it (This should be the last in the loop)
- continue
- if comment.saved: # It's saved, that means we've processed it before
- break
- if (comment.created_utc>last_time[subname]): # If this is the latest comment, store the data
- last_time[subname] = comment.created_utc
- last_id[subname] = comment.id
- for k in phrase: # Search each phrase
- if any(string in text for string in phrase[k]["trigger"]): # If it matches
- comment.save() # Simplest way to keep it saved between sessions - Save it on Reddit!
- print( "MATCH: " + k )
- print( "RESPOND: " + phrase[k]["response"] )
- footer = ""
- if 'footer' in subreddits[subname]: # Custom subreddit footer
- footer = subreddits[subname]['footer'] + response_footer
- else:
- footer = footer_default + response_footer # Default footer
- if 'source' in phrase[k]: # Image source
- footer = footer + phrase[k]['source']
- else:
- footer = footer + "^^Image ^^source ^^unknown" # Source unknown
- footer = footer + " [](#bot)" # Tag our post as a bot post for other bots to see
- comment.reply( phrase[k]["response"] + footer ) # Post reply
- if 'limit' in subreddits[subname]:
- next_post[subname] = time.time() + (subreddits[subname]['limit'] * 3600)
- break # Break to prevent two replies when subreddit is limited
- except AttributeError:
- print( "Something went wrong! Missing attribute" ) # How did this even happen?
- # Scan submissions
- # ----------------
- def alot_cleanup(): # Remove downvoted submissions
- print( "Starting alot-of-bot comment cleanup..." )
- for comment in alotbot.get_comments(limit=100):
- if comment.score<=-1:
- print( "Removing comment!" )
- comment.delete()
- elif not comment.saved:
- text = comment.body.lower()
- if not (("#bot" in text) or ("#nobot" in text)): # Non-automated response
- comment.save()
- comment.edit( comment.body + footer_manual )
- # Update phrases
- # --------------
- def update_phrases():
- try:
- global phrase
- global subreddits
- r = requests.get( "http://pastebin.com/raw/YJLqLbjk" )
- newPhrase = json.loads( r.text )
- if len(newPhrase)>0:
- phrase = newPhrase
- r = requests.get( "http://pastebin.com/raw/4QB6mstL" )
- newSubs = json.loads( r.text )
- if len(newSubs)>0:
- subreddits = newSubs
- for subname in subreddits: # Fill with placeholders
- last_id[subname] = ''
- last_time[subname] = 0
- except:
- print( "Phrase update: Something went wrong!" )
- # Main
- # ----
- next_cleanup = 1
- next_update = 1
- while True:
- next_cleanup=next_cleanup-1
- if next_cleanup<=0:
- try:
- alot_cleanup()
- except HTTPError as err:
- print( "ERROR: HTTP Error in Cleanup." )
- except praw.errors.HTTPException as err:
- print( "ERROR: Praw HTTP Error in Cleanup." )
- except praw.errors.RateLimitExceeded as err:
- print( "ERROR: Rate limit exceeded." )
- next_cleanup=10
- next_update=next_update-1
- if next_update<=0:
- update_phrases()
- next_update=1200
- print( "Starting checks..." )
- for subname in subreddits:
- try:
- search_sub(subname)
- except HTTPError as err:
- print( "ERROR: HTTP Error in subreddit '" + subname + "'." )
- except requests.exceptions.ReadTimeout as err:
- print( "ERROR: Read timeout in subreddit '" + subname + "'." )
- except praw.errors.RateLimitExceeded as err:
- print( "ERROR: Rate limit exceeded." )
- except praw.errors.HTTPException as err:
- print( "ERROR: Praw HTTP Error in subreddit '" + subname + "'." )
- except:
- print( "Error: Something went wrong!" )
- print( "Done!" )
- time.sleep( 30 )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement