nemubot/modules/reddit.py

95 lines
3.0 KiB
Python
Raw Normal View History

# coding=utf-8
2014-08-27 23:39:31 +00:00
"""Get information about subreddit"""
import json
import re
import urllib
2014-08-13 13:53:55 +00:00
nemubotversion = 3.4
from hooks import hook
from more import Response
2014-11-13 01:51:49 +00:00
def help_full():
return "!subreddit /subreddit/: Display information on the subreddit."
LAST_SUBS = dict()
2014-11-13 01:51:49 +00:00
@hook("cmd_hook", "subreddit")
def cmd_subreddit(msg):
global LAST_SUBS
if len(msg.cmds) <= 1:
if msg.channel in LAST_SUBS and len(LAST_SUBS[msg.channel]) > 0:
subs = [LAST_SUBS[msg.channel].pop()]
else:
2014-11-13 01:51:49 +00:00
raise IRCException("Which subreddit? Need inspiration? "
"type !horny or !bored")
else:
subs = msg.cmds[1:]
all_res = list()
2014-05-01 22:27:42 +00:00
for osub in subs:
sub = re.match(r"^/?(?:(\w)/)?(\w+)/?$", osub)
if sub is not None:
if sub.group(1) is not None and sub.group(1) != "":
where = sub.group(1)
else:
where = "r"
try:
2014-11-13 01:51:49 +00:00
req = urllib.request.Request(
"http://www.reddit.com/%s/%s/about.json" %
(where, sub.group(2)),
headers={'User-Agent': "nemubot v3"})
raw = urllib.request.urlopen(req, timeout=10)
except urllib.error.HTTPError as e:
2014-11-13 01:51:49 +00:00
raise IRCException("HTTP error occurs: %s %s" %
(e.code, e.reason))
sbr = json.loads(raw.read().decode())
if "title" in sbr["data"]:
2014-11-13 01:51:49 +00:00
res = Response(channel=msg.channel,
nomore="No more information")
res.append_message(
("[NSFW] " if sbr["data"]["over18"] else "") +
sbr["data"]["url"] + " " + sbr["data"]["title"] + ": " +
sbr["data"]["public_description" if sbr["data"]["public_description"] != "" else "description"].replace("\n", " ") +
" %s subscriber(s)" % sbr["data"]["subscribers"])
if sbr["data"]["public_description"] != "":
2014-11-13 01:51:49 +00:00
res.append_message(
sbr["data"]["description"].replace("\n", " "))
all_res.append(res)
else:
2014-11-13 01:51:49 +00:00
all_res.append(Response("/%s/%s doesn't exist" %
(where, sub.group(2)),
channel=msg.channel))
2014-05-01 22:27:42 +00:00
else:
2014-11-13 01:51:49 +00:00
all_res.append(Response("%s is not a valid subreddit" % osub,
channel=msg.channel, nick=msg.nick))
return all_res
2014-11-13 01:51:49 +00:00
@hook("msg_default")
def parselisten(msg):
2014-09-03 17:06:26 +00:00
parseresponse(msg)
return None
2014-11-13 01:51:49 +00:00
2014-09-03 17:06:26 +00:00
@hook("all_post")
def parseresponse(msg):
global LAST_SUBS
try:
urls = re.findall("www.reddit.com(/\w/\w+/?)", msg.text)
for url in urls:
if msg.channel not in LAST_SUBS:
LAST_SUBS[msg.channel] = list()
LAST_SUBS[msg.channel].append(url)
except:
pass
return msg