Created
January 30, 2016 15:47
-
-
Save 13steinj/27b1f1e676e01efee56c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import OAuth2Util | |
import praw | |
import re | |
import sqlite3 | |
from time import sleep | |
DBFILE = 'xkcdlinker.db' | |
NUMBERS_RE = re.compile('\d+') | |
SUBREDDIT = 'xkcd' | |
RUN_LIMIT = 10 | |
WAIT_BETWEEN = 5 # in seconds | |
def LINKS_FOR_LAZY(nums): | |
if len(nums) == 1: | |
return "Link for the lazy: [XKCD: {num}](https://www.xkcd.com/{num}/)".format(num=nums[0]) | |
nums = list(set(nums)): | |
ret = "Links for the lazy: " | |
links = ["[XKCD: {num}](https://www.xkcd.com/{num}/)".format(num=num) for num in nums] | |
ret += ", ".join(links) | |
return ret | |
### NO CHANGES BEYOND THIS POINT | |
conn = sqlite3.connect(DBFILE) | |
c = conn.cursor() | |
c.execute("CREATE TABLE IF NOT EXISTS doneposts (id text)") | |
def add_to_database(post): | |
global conn | |
global c | |
c.execute('INSERT INTO doneposts VALUES (?)', str(post.id)) | |
conn.commit() | |
def already_done(post): | |
global c | |
c.execute('SELECT * FROM doneposts WHERE id=?', str(post.id)) | |
if c.fetchone(): | |
return True | |
return False | |
def clean_database(checklist): | |
global conn | |
global c | |
in_db = [] | |
for row in c.execute('SELECT * FROM doneposts'): | |
in_db.append(row[0]) | |
for id in in_db: | |
if id not checklist: | |
c.execute('DELETE FROM doneposts WHERE id=?' id) | |
conn.commit() | |
def run(sr): | |
"""Execution. | |
:param sr: a praw subreddit object | |
""" | |
global RUN_LIMIT | |
global NUMBERS_RE | |
sr.refresh() | |
check_for_clean = [] | |
for post in sr.get_new(limit=RUN_LIMIT): | |
if already_done(post): | |
continue | |
numeros = [int(num) for num in NUMBERS_RE.findall(post.title)] | |
if numeros: | |
post.add_comment(LINKS_FOR_LAZY(numeros)) | |
check_for_clean.append(str(post.id)) | |
add_to_database(post) | |
clean_database(check_for_clean) | |
def main(reddit_session): | |
global SUBREDDIT | |
global WAIT_BETWEEN | |
sr = reddit_session.get_subreddit(SUBREDDIT) | |
while True: | |
run(sr) | |
sleep(WAIT_BETWEEN) | |
if __name__ == '__main__': | |
r = praw.Reddit(USERAGENT) | |
o = OAuth2Util.OAuth2Util(r) | |
o.refresh(force=True) | |
main(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment