2013-09-04 18:30:04 +08:00
from util import hook , http , text
2013-08-20 10:55:58 +12:00
import re
2012-08-21 08:02:49 +12:00
base_url = ' http://www.urbandictionary.com/iphone/search/define '
2012-04-24 00:07:17 +12:00
@hook.command ( ' u ' )
@hook.command
def urban ( inp ) :
2013-09-04 18:30:04 +08:00
""" urban <phrase> [id] -- Looks up <phrase> on urbandictionary.com. """
2012-04-24 00:07:17 +12:00
# clean and split the input
input = inp . lower ( ) . strip ( )
parts = input . split ( )
# if the last word is a number, set the ID to that number
if parts [ - 1 ] . isdigit ( ) :
id = int ( parts [ - 1 ] )
# remove the ID from the input string
del parts [ - 1 ]
input = " " . join ( parts )
2012-08-21 08:02:49 +12:00
else :
id = 1
2012-04-24 00:07:17 +12:00
# fetch the definitions
2012-08-21 08:02:49 +12:00
page = http . get_json ( base_url , term = input , referer = " http://m.urbandictionary.com " )
2012-04-24 00:07:17 +12:00
defs = page [ ' list ' ]
2013-08-20 10:55:58 +12:00
print page
2012-04-24 00:07:17 +12:00
if page [ ' result_type ' ] == ' no_results ' :
return ' Not found. '
# try getting the requested definition
try :
2013-08-20 10:55:58 +12:00
definition = defs [ id - 1 ] [ ' definition ' ] . replace ( ' \r \n ' , ' ' )
definition = re . sub ( ' \ s+ ' , ' ' , definition ) . strip ( ) # remove excess spaces
2013-09-04 18:30:04 +08:00
definition = text . truncate_str ( definition , 200 )
2012-04-24 00:07:17 +12:00
except IndexError :
return ' Not found. '
2013-08-20 10:55:58 +12:00
url = defs [ id - 1 ] [ ' permalink ' ]
output = u " [ %i / %i ] %s :: %s " % \
2013-09-04 18:30:04 +08:00
( id , len ( defs ) , definition , url )
2013-08-20 10:55:58 +12:00
return output