This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/disabled_stuff/urban.py

67 lines
1.9 KiB
Python
Raw Normal View History

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