Rewrote fmylife with a cache for instant fmls
This commit is contained in:
parent
921c16cf7c
commit
8d6a2d71d4
1 changed files with 26 additions and 29 deletions
|
@ -1,41 +1,38 @@
|
||||||
# Plugin by Lukeroge
|
# Plugin by Lukeroge
|
||||||
# <lukeroge@gmail.com> <https://github.com/lukeroge/CloudBot/>
|
# <lukeroge@gmail.com> <https://github.com/lukeroge/CloudBot/>
|
||||||
|
|
||||||
import re
|
from util import hook, http
|
||||||
|
|
||||||
from util import hook, http, misc
|
|
||||||
from urllib2 import HTTPError
|
|
||||||
from urlparse import urljoin
|
from urlparse import urljoin
|
||||||
from BeautifulSoup import BeautifulSoup
|
from BeautifulSoup import BeautifulSoup
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
base_url = 'http://www.fmylife.com/'
|
base_url = 'http://www.fmylife.com/'
|
||||||
|
|
||||||
@hook.command(autohelp=False)
|
fml_cache = defaultdict()
|
||||||
def fml(inp):
|
|
||||||
".fml [id] -- Gets a random quote from fmyfife.com. Optionally gets [id]."
|
|
||||||
|
|
||||||
inp = inp.replace("#", "")
|
|
||||||
|
|
||||||
if inp:
|
def refresh_cache():
|
||||||
if not inp.isdigit():
|
""" gets a page of random fmls and puts them into a dictionary """
|
||||||
return "Invalid ID!"
|
|
||||||
try:
|
|
||||||
page = http.get(urljoin(base_url, inp))
|
|
||||||
except (HTTPError, IOError):
|
|
||||||
return "Could not fetch #%s. FML" % inp
|
|
||||||
else:
|
|
||||||
try:
|
|
||||||
page = http.get(urljoin(base_url, 'random'))
|
page = http.get(urljoin(base_url, 'random'))
|
||||||
except (HTTPError, IOError):
|
|
||||||
return "I tried to use .fml, but it was broken. FML"
|
|
||||||
|
|
||||||
soup = BeautifulSoup(page)
|
soup = BeautifulSoup(page)
|
||||||
|
|
||||||
soup.find('div', id='submit').extract()
|
for e in soup.findAll('div', {'class': 'post article'}):
|
||||||
post = soup.body.find('div', 'post')
|
id = int(e['id'])
|
||||||
try:
|
text = e.find('p', text=True)
|
||||||
id = int(post.find('a', 'fmllink')['href'].split('/')[-1])
|
fml_cache[id] = text
|
||||||
except TypeError:
|
|
||||||
return "Could not fetch #%s. FML" % inp
|
# do an initial refresh of the cache
|
||||||
body = misc.strip_html(' '.join(link.renderContents() for link in post('a', 'fmllink')))
|
refresh_cache()
|
||||||
return '(#%d) %s' % (id, body)
|
|
||||||
|
|
||||||
|
@hook.command(autohelp=False)
|
||||||
|
def fml(inp, reply=None):
|
||||||
|
".fml -- Gets a random quote from fmyfife.com."
|
||||||
|
|
||||||
|
# grab the last item in the fml cache and remove it
|
||||||
|
id, text = fml_cache.popitem()
|
||||||
|
# reply with the fml we grabbed
|
||||||
|
reply('(#%d) %s' % (id, text))
|
||||||
|
# refresh fml cache if its getting empty
|
||||||
|
if len(fml_cache) < 3:
|
||||||
|
refresh_cache()
|
||||||
|
|
Reference in a new issue