-
Notifications
You must be signed in to change notification settings - Fork 0
/
urbandict.py
56 lines (46 loc) · 1.95 KB
/
urbandict.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
import json
import urllib.request
import urllib.parse
from errbot import botcmd
from errbot import BotPlugin
class UrbanDictionary(BotPlugin):
api_url = 'https://api.urbandictionary.com/v0'
search_url_template = api_url + '/define?term={0}'
random_term_url = api_url + '/random'
@botcmd
def ud(self, msg, args):
"""Looks up a term on urban dictionary"""
if not args:
# Get random definitions if no term is provided
definitions = self.get_json(self.random_term_url)
else:
# Otherwise, get the definitions of the search term
escaped_term = urllib.parse.quote(args)
search_url = self.search_url_template.format(escaped_term)
definitions = self.get_json(search_url)
if not definitions['list']:
return 'No such term: {0}!'.format(args)
best_definition = definitions['list'][0]
card_fields = self.format_definition_card(best_definition)
self.send_card(in_reply_to=msg, **card_fields)
@staticmethod
def get_json(url):
"""Fetch a URL returning JSON, and return it as a dict."""
with urllib.request.urlopen(url) as api_response:
api_response_text = api_response.read().decode('utf8')
return json.loads(api_response_text)
@staticmethod
def format_definition_card(definition):
"""Formats a definition JSON from Urban Dictionary into a dictionary
containing the keyword arguments for `BotPlugin.send_card()`.
"""
definition_text = definition['definition'].replace('[', '').replace(']', '')
return {
'title': definition['word'],
'body': '\n\n'.join([definition_text, definition['example']]),
'link': definition['permalink'],
'fields': (
('thumbs_up', definition.get('thumbs_up', 0)),
('thumbs_down', definition.get('thumbs_down', 0)),
)
}