Skip to content

Instantly share code, notes, and snippets.

@davidfg4
Forked from s-quark/reddit.py
Created March 2, 2012 13:50
Show Gist options
  • Save davidfg4/1958507 to your computer and use it in GitHub Desktop.
Save davidfg4/1958507 to your computer and use it in GitHub Desktop.
reddit plugin for skybot
import locale
import re
import time
import datetime
from htmlentitydefs import name2codepoint
#Original from https://gist.github.com/1957440, by s_quark
#Changes by davidfg4
from util import hook, http
@hook.regex(r'(?i)http://(?:www\.)?(reddit.com/tb/|redd.it/)([A-Za-z0-9\-]+)')
def reddit(match):
try:
h = http.get_json("http://www.reddit.com/by_id/t3_" + match.group(2) + ".json")
data = h["data"]["children"][0]["data"]
age = time_ago(data["created_utc"])
title = decode(data["title"].replace('\n',''))
domain = decode(data["domain"])
author = decode(data["author"])
score = data["score"]
subreddit = decode(data["subreddit"])
# the longest title allowed by reddit now is 300 characters, however
# there are a few old posts with longer titles.
if len(title) > 300:
title = title[:297] + '...'
ret = "%s (%s) - submitted %s by %s" % (title, domain, age, author)
if not data["is_self"]:
ret = ret + " to /r/%s" % (subreddit)
ret = ret + " (%d points)" % (score)
if data["over_18"]:
if subreddit == "mylittlepony":
ret = ret + " \x034*SPOILERS*\x0f"
else:
ret = ret + " \x034*NSFW*\x0f"
return ret
except http.URLError, e:
pass
def time_ago(timestamp):
now = int(time.time())
delta = datetime.timedelta(seconds=(now - timestamp))
if delta.days > 0:
return "%d days ago" % (delta.days)
hours = delta.seconds // 3600
if hours > 0:
return "%d hours ago" % (hours)
minutes = delta.seconds // 60
if minutes > 0:
return "%d minutes ago" % (minutes)
else:
return "%d seconds ago" % (delta.seconds)
#decoding stuff from https://github.com/sbp/phenny/blob/master/web.py
r_entity = re.compile(r'&([^;\s]+);')
def entity(match):
value = match.group(1).lower()
if value.startswith('#x'):
return unichr(int(value[2:], 16))
elif value.startswith('#'):
return unichr(int(value[1:]))
elif name2codepoint.has_key(value):
return unichr(name2codepoint[value])
return '[' + value + ']'
def decode(html):
return r_entity.sub(entity, html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment