Skip to content

Instantly share code, notes, and snippets.

@yekm
Last active August 29, 2015 14:06
Show Gist options
  • Save yekm/59686a4f262ad3ea9571 to your computer and use it in GitHub Desktop.
Save yekm/59686a4f262ad3ea9571 to your computer and use it in GitHub Desktop.
pastebin
#!/usr/bin/env python3
import os, time, datetime, re
import praw
import saxo
subreddit_r = re.compile('[a-z0-9]+')
@saxo.command()
def r(arg):
if not arg:
return "Fetch links from reddit"
if not saxo.env("base"):
return "Sorry, this command requires an IRC instance"
if not subreddit_r.match(arg):
return "Sorry, subreddit name must match " + subreddit_r.pattern
sname = arg
path = os.path.join(saxo.env("base"), "database.sqlite3")
with saxo.database(path) as db:
c = db.connection.cursor()
if not "reddit_stat" in db:
db['reddit_stat'].create(("name", "text unique"), ("value", str))
tname = "reddit_%s" % sname
if not tname in db:
db[tname].create(('url', 'text unique'), ('req_by', str))
url = c.execute("select url from %s where req_by = ''" % tname).fetchone()
if url == None:
rtime = c.execute("select value from reddit_stat where name = ?", [tname]).fetchone()
if rtime != None and rtime[0] == str(datetime.date.today()):
return "No more %s for today" % sname
reddit = praw.Reddit(user_agent='irc_pic_bot')
s = reddit.get_subreddit(sname).get_hot(limit=32)
for x in s:
if x.url.endswith(('.jpg', '.jpeg', '.gif', '.png')):
c.execute("replace into %s values(?, '')" % tname, [x.url])
db.commit()
c.execute("replace into reddit_stat values (?, ?)", [tname, str(datetime.date.today())])
db.commit()
url = c.execute("select url from %s where req_by = ''" % tname).fetchone()
if url == None:
return "No more urls. Maybe reddit is down."
c.execute("replace into %s values (?, ?)" % tname, [url[0], saxo.env("nick")])
db.commit()
return url[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment