This repository has been archived by the owner on Oct 23, 2019. It is now read-only.
forked from edwardslabs/CloudBot
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathurban.py
86 lines (65 loc) · 2.44 KB
/
urban.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import random
import requests
from cloudbot import hook
from cloudbot.util import formatting
base_url = 'http://api.urbandictionary.com/v0'
define_url = base_url + "/define"
random_url = base_url + "/random"
@hook.command("urban", "u", autohelp=False)
def urban(text, reply):
"""<phrase> [id] - Looks up <phrase> on urbandictionary.com."""
headers = {
"Referer": "http://m.urbandictionary.com"
}
if text:
# clean and split the input
text = text.lower().strip()
parts = text.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]
text = " ".join(parts)
else:
id_num = 1
# fetch the definitions
try:
params = {"term": text}
request = requests.get(define_url, params=params, headers=headers)
request.raise_for_status()
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
reply("Could not get definition: {}".format(e))
raise
page = request.json()
else:
# get a random definition!
try:
request = requests.get(random_url, headers=headers)
request.raise_for_status()
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError) as e:
reply("Could not get definition: {}".format(e))
raise
page = request.json()
id_num = None
definitions = page['list']
if not definitions:
return 'Not found.'
if id_num:
# try getting the requested definition
try:
definition = definitions[id_num - 1]
def_text = " ".join(definition['definition'].split()) # remove excess spaces
def_text = formatting.truncate(def_text, 200)
except IndexError:
return 'Not found.'
url = definition['permalink']
output = "[{}/{}] {} - {}".format(id_num, len(definitions), def_text, url)
else:
definition = random.choice(definitions)
def_text = " ".join(definition['definition'].split()) # remove excess spaces
def_text = formatting.truncate(def_text, 200)
name = definition['word']
url = definition['permalink']
output = "\x02{}\x02: {} - {}".format(name, def_text, url)
return output