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/plugins/urban.py

47 lines
1.2 KiB
Python
Raw Normal View History

2013-09-04 12:30:04 +02:00
from util import hook, http, text
2013-08-20 00:55:58 +02:00
import re
2012-08-20 22:02:49 +02:00
base_url = 'http://www.urbandictionary.com/iphone/search/define'
2012-04-23 14:07:17 +02:00
@hook.command('u')
@hook.command
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
# 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-20 22:02:49 +02:00
else:
id = 1
2012-04-23 14:07:17 +02:00
# fetch the definitions
2012-08-20 22:02:49 +02:00
page = http.get_json(base_url, term=input, referer="http://m.urbandictionary.com")
2012-04-23 14:07:17 +02:00
defs = page['list']
2013-08-20 00:55:58 +02:00
print page
2012-04-23 14:07:17 +02:00
if page['result_type'] == 'no_results':
return 'Not found.'
# try getting the requested definition
try:
2013-08-20 00:55:58 +02:00
definition = defs[id - 1]['definition'].replace('\r\n', ' ')
definition = re.sub('\s+', ' ', definition).strip() # remove excess spaces
2013-09-04 12:30:04 +02:00
definition = text.truncate_str(definition, 200)
2012-04-23 14:07:17 +02:00
except IndexError:
return 'Not found.'
2013-08-20 00:55:58 +02:00
url = defs[id - 1]['permalink']
output = u"[%i/%i] %s :: %s" % \
2013-09-04 12:30:04 +02:00
(id, len(defs), definition, url)
2013-08-20 00:55:58 +02:00
return output