Added random output, switched API URL

This commit is contained in:
Luke Rogers 2014-04-03 18:27:17 +13:00
parent 97a3283eff
commit fb471bee17
3 changed files with 56 additions and 38 deletions

View file

@ -1,47 +1,66 @@
import re
import random
from util import hook, http, text
base_url = 'http://www.urbandictionary.com/iphone/search/define'
base_url = 'http://api.urbandictionary.com/v0'
define_url = base_url + "/define"
random_url = base_url + "/random"
@hook.command('u')
@hook.command
@hook.command('u', autohelp=False)
@hook.command(autohelp=False)
def urban(inp):
"""urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com."""
# clean and split the input
inp = inp.lower().strip()
parts = inp.split()
if inp:
# clean and split the input
inp = inp.lower().strip()
parts = inp.split()
# if the last word is a number, set the ID to that number
if parts[-1].isdigit():
id_num = int(parts[-1])
# remove the ID from the input string
del parts[-1]
inp = " ".join(parts)
# if the last word is a number, set the ID to that number
if parts[-1].isdigit():
id_num = int(parts[-1])
# remove the ID from the input string
del parts[-1]
inp = " ".join(parts)
else:
id_num = 1
# fetch the definitions
page = http.get_json(define_url, term=inp, referer="http://m.urbandictionary.com")
if page['result_type'] == 'no_results':
return 'Not found.'
else:
id_num = 1
# get a random definition!
page = http.get_json(random_url, referer="http://m.urbandictionary.com")
id_num = None
# fetch the definitions
page = http.get_json(base_url, term=inp, referer="http://m.urbandictionary.com")
definitions = page['list']
if page['result_type'] == 'no_results':
return 'Not found.'
if id_num:
# try getting the requested definition
try:
definition = definitions[id_num - 1]['definition'].replace('\r\n', ' ')
definition = re.sub('\s+', ' ', definition).strip() # remove excess spaces
definition = text.truncate_str(definition, 200)
except IndexError:
return 'Not found.'
# try getting the requested definition
try:
definition = definitions[id_num - 1]['definition'].replace('\r\n', ' ')
definition = re.sub('\s+', ' ', definition).strip() # remove excess spaces
definition = text.truncate_str(definition, 200)
except IndexError:
return 'Not found.'
url = definitions[id_num - 1]['permalink']
output = u"[%i/%i] %s :: %s" % \
(id_num, len(definitions), definition, url)
url = definitions[id_num - 1]['permalink']
else:
definition = random.choice(definitions)
output = u"[%i/%i] %s :: %s" % \
(id_num, len(definitions), definition, url)
def_text = definition['definition'].replace('\r\n', ' ')
def_text = re.sub('\s+', ' ', def_text).strip() # remove excess spaces
def_text = text.truncate_str(def_text, 200)
name = definition['word']
url = definition['permalink']
output = u"\x02{}\x02: {} :: {}".format(name, def_text, url)
return output