Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- import time
- import praw
- import datetime
- CONFIG_INTERVAL = 6 * 3600 # Number of seconds between updating
- CONFIG_CLIENT_ID = "" # Client ID from /prefs/apps
- CONFIG_CLIENT_SECRET = "" # Client secret from /prefs/apps
- CONFIG_USERNAME = "" # Username for the bot account
- CONFIG_PASSWORD = "" # Password for the bot account
- CONFIG_SUBREDDIT = "" # Subreddit(s) the script runs on
- CONFIG_SCRIPTHOST = "" # Your Reddit username
- CONFIG_USER_AGENT = "catsubtracker 1.0 for /r/%s, hosted by /u/%s" \
- %(CONFIG_SUBREDDIT, CONFIG_SCRIPTHOST)
- CONFIG_WIKIPAGE = "" # The name of the wiki page to check/edit
- catmatch = r'indexing\s[0-9]*\scategories'
- submatch = r'categories\sand\s[0-9]*\ssubreddits'
- datemtch = r'Last updated [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2} UTC'
- pformat = 'The directory is currently indexing %d' + \
- ' categories and %d subreddits. (Last updated %s UTC)'
- def get_counts(body):
- _catmatch = r'###\s*[^\s]*'
- _submatch = r'/r/[^\s]*'
- return (len(re.findall(_catmatch, body)),
- len(re.findall(_submatch, body)))
- def get_old_counts(body):
- if 'The directory is currently' in body:
- return (int(re.findall(catmatch, body)[0].split(' ')[1]),
- int(re.findall(submatch, body)[0].split(' ')[2]))
- else:
- return (0, 0)
- def gen_new_page(body, cats, subs):
- datestr = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M')
- base = re.sub(catmatch, 'indexing %d categories'%cats, body)
- base = re.sub(submatch, 'categories and %d subreddits'%subs, base)
- base = re.sub(datemtch, 'Last updated %s UTC'%datestr, base)
- if base == body:
- base += '\r\n\r\n-------\r\n\r\n%s'%(pformat%(cats, subs, datestr))
- return base
- def log(msg):
- print('[%s] %s'%(time.ctime(), msg))
- def main():
- reddit = praw.Reddit(client_id = CONFIG_CLIENT_ID,
- client_secret = CONFIG_CLIENT_SECRET,
- username = CONFIG_USERNAME,
- password = CONFIG_PASSWORD,
- user_agent = CONFIG_USER_AGENT)
- while True:
- log('Loading wiki page...')
- wikipage = reddit.subreddit(CONFIG_SUBREDDIT).wiki[CONFIG_WIKIPAGE]
- cats, subs = get_counts(wikipage.content_md)
- ocats, osubs = get_old_counts(wikipage.content_md)
- if cats != ocats or subs != osubs:
- log('Directory has been updated! Editing...')
- new_page = gen_new_page(wikipage.content_md, cats, subs)
- wikipage.edit(new_page, 'Category / sub count updated.')
- log('Directory edited.')
- else:
- log('No changes were detected.')
- log('Sleeping for %d hours.'%(CONFIG_INTERVAL / 3600))
- time.sleep(CONFIG_INTERVAL)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement