phenny/modules/urbandict.py

50 lines
1.4 KiB
Python
Raw Normal View History

2011-12-26 22:16:06 -05:00
#!/usr/bin/python3
"""
urbandict.py - urban dictionary module
author: mutantmonkey <mutantmonkey@mutantmonkey.in>
"""
2012-06-02 00:34:50 -04:00
import urllib.request
2011-12-26 22:16:06 -05:00
from urllib.error import HTTPError
from tools import GrumbleError
2011-12-26 22:16:06 -05:00
import web
import json
def urbandict(phenny, input):
""".urb <word> - Search Urban Dictionary for a definition."""
word = input.group(2)
if not word:
2012-05-14 16:49:41 -04:00
phenny.say(urbandict.__doc__.strip())
2011-12-26 22:16:06 -05:00
return
2012-06-02 00:34:50 -04:00
# create opener
opener = urllib.request.build_opener()
opener.addheaders = [
('User-agent', web.Grab().version),
('Referer', "http://m.urbandictionary.com"),
]
2011-12-26 22:16:06 -05:00
try:
2012-06-02 00:34:50 -04:00
req = opener.open("http://api.urbandictionary.com/v0/define?term={0}"
.format(web.quote(word)))
data = req.read().decode('utf-8')
data = json.loads(data)
2011-12-26 22:16:06 -05:00
except (HTTPError, IOError, ValueError):
raise GrumbleError(
"Urban Dictionary slemped out on me. Try again in a minute.")
2011-12-26 22:16:06 -05:00
if data['result_type'] == 'no_results':
phenny.say("No results found for {0}".format(word))
return
2011-12-26 22:16:06 -05:00
result = data['list'][0]
2012-06-02 00:34:50 -04:00
url = 'http://www.urbandictionary.com/define.php?term={0}'.format(web.quote(word))
2011-12-26 22:16:06 -05:00
response = "{0} - {1}".format(result['definition'].strip()[:256], url)
2011-12-26 22:16:06 -05:00
phenny.say(response)
urbandict.rule = (['urb'], r'(.*)')
if __name__ == '__main__':
print(__doc__.strip())