2013-08-20 10:55:58 +12:00
import re
2014-04-03 18:27:17 +13:00
import random
2012-08-21 08:02:49 +12:00
2014-02-14 16:36:57 +13:00
from util import hook , http , text
2014-04-03 18:27:17 +13:00
base_url = ' http://api.urbandictionary.com/v0 '
define_url = base_url + " /define "
random_url = base_url + " /random "
2012-04-24 00:07:17 +12:00
2014-04-03 18:27:17 +13:00
@hook.command ( ' u ' , autohelp = False )
@hook.command ( autohelp = False )
2012-04-24 00:07:17 +12:00
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
2014-04-03 18:27:17 +13:00
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 )
else :
id_num = 1
# fetch the definitions
page = http . get_json ( define_url , term = inp , referer = " http://m.urbandictionary.com " )
2012-04-24 00:07:17 +12:00
2014-04-03 18:27:17 +13:00
if page [ ' result_type ' ] == ' no_results ' :
return ' Not found. '
2012-08-21 08:02:49 +12:00
else :
2014-04-03 18:27:17 +13:00
# get a random definition!
page = http . get_json ( random_url , referer = " http://m.urbandictionary.com " )
id_num = None
2012-04-24 00:07:17 +12:00
2014-02-13 15:02:44 +13:00
definitions = page [ ' list ' ]
2012-04-24 00:07:17 +12:00
2014-04-03 18:27:17 +13:00
if id_num :
# try getting the requested definition
try :
2014-04-03 19:44:38 +13:00
definition = definitions [ id_num - 1 ]
def_text = " " . join ( definition [ ' definition ' ] . split ( ) ) # remove excess spaces
def_text = text . truncate_str ( def_text , 200 )
2014-04-03 18:27:17 +13:00
except IndexError :
return ' Not found. '
2012-04-24 00:07:17 +12:00
2014-04-03 19:44:38 +13:00
url = definition [ ' permalink ' ]
2014-04-03 18:27:17 +13:00
output = u " [ %i / %i ] %s :: %s " % \
2014-04-03 19:44:38 +13:00
( id_num , len ( definitions ) , def_text , url )
2014-04-03 18:27:17 +13:00
else :
definition = random . choice ( definitions )
2012-04-24 00:07:17 +12:00
2014-04-03 19:44:38 +13:00
def_text = " " . join ( definition [ ' definition ' ] . split ( ) ) # remove excess spaces
2014-04-03 18:27:17 +13:00
def_text = text . truncate_str ( def_text , 200 )
2013-08-20 10:55:58 +12:00
2014-04-03 18:27:17 +13:00
name = definition [ ' word ' ]
url = definition [ ' permalink ' ]
output = u " \x02 {} \x02 : {} :: {} " . format ( name , def_text , url )
2013-08-20 10:55:58 +12:00
return output