switch to requests for HTTP queries

This commit is contained in:
mutantmonkey
2013-06-08 22:27:24 -07:00
parent 259c222623
commit 5cb88f3cf8
23 changed files with 131 additions and 161 deletions

View File

@@ -4,12 +4,11 @@ urbandict.py - urban dictionary module
author: mutantmonkey <mutantmonkey@mutantmonkey.in>
"""
import urllib.request
from urllib.error import HTTPError
from tools import GrumbleError
import web
import json
def urbandict(phenny, input):
""".urb <word> - Search Urban Dictionary for a definition."""
@@ -19,27 +18,28 @@ def urbandict(phenny, input):
return
# create opener
opener = urllib.request.build_opener()
opener.addheaders = [
('User-agent', web.Grab().version),
('Referer', "http://m.urbandictionary.com"),
]
#opener = urllib.request.build_opener()
#opener.addheaders = [
# ('User-agent', web.Grab().version),
# ('Referer', "http://m.urbandictionary.com"),
#]
try:
req = opener.open("http://api.urbandictionary.com/v0/define?term={0}"
.format(web.quote(word)))
data = req.read().decode('utf-8')
data = web.get(
"http://api.urbandictionary.com/v0/define?term={0}".format(
web.quote(word)))
data = json.loads(data)
except (HTTPError, IOError, ValueError):
except:
raise GrumbleError(
"Urban Dictionary slemped out on me. Try again in a minute.")
"Urban Dictionary slemped out on me. Try again in a minute.")
if data['result_type'] == 'no_results':
phenny.say("No results found for {0}".format(word))
return
result = data['list'][0]
url = 'http://www.urbandictionary.com/define.php?term={0}'.format(web.quote(word))
url = 'http://www.urbandictionary.com/define.php?term={0}'.format(
web.quote(word))
response = "{0} - {1}".format(result['definition'].strip()[:256], url)
phenny.say(response)