Created
February 12, 2015 02:19
-
-
Save endofline/4861169a8efa3bd9805c to your computer and use it in GitHub Desktop.
urban dictionary plugin for hangoutsbot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Simple interface to urbandictionary.com | |
# | |
# Author: Roman Bogorodskiy <bogorodskiy@gmail.com> | |
import sys | |
from urllib.request import urlopen | |
from urllib.parse import quote as urlquote | |
from html.parser import HTMLParser | |
class TermType(object): | |
pass | |
class TermTypeRandom(TermType): | |
pass | |
class UrbanDictParser(HTMLParser): | |
def __init__(self, *args, **kwargs): | |
HTMLParser.__init__(self, *args, **kwargs) | |
self._section = None | |
self.translations = [] | |
def handle_starttag(self, tag, attrs): | |
attrs_dict = dict(attrs) | |
if not tag in ("div", "a"): | |
return | |
div_class = attrs_dict.get('class') | |
if div_class in ('word', 'meaning', 'example'): | |
self._section = div_class | |
if div_class == 'word': # NOTE: assume 'word' is the first section | |
self.translations.append( | |
{'word': '', 'def': '', 'example': ''}) | |
def handle_endtag(self, tag): | |
if tag == 'div': | |
#NOTE: assume there is no nested <div> in the known sections | |
self._section = None | |
def handle_data(self, data): | |
if not self._section: | |
return | |
if self._section == 'meaning': | |
self._section = 'def' | |
elif self._section == 'word': | |
data = data.strip() | |
self.translations[-1][self._section] += normalize_newlines(data) | |
def normalize_newlines(text): | |
return text.replace('\r\n', '\n').replace('\r', '\n') | |
def urbandict(bot, event, *args): | |
term = " ".join(args) | |
if not term: | |
url = "http://www.urbandictionary.com/random.php" | |
else: | |
url = "http://www.urbandictionary.com/define.php?term=%s" % \ | |
urlquote(term) | |
f = urlopen(url) | |
data = f.read().decode('utf-8') | |
urbanDictParser = UrbanDictParser() | |
urbanDictParser.feed(data) | |
if len(urbanDictParser.translations) > 0: | |
html_text = "" | |
the_definition = urbanDictParser.translations[0] | |
html_text += '<b>"' + the_definition["word"] + '"</b><br /><br />' | |
if "def" in the_definition: | |
html_text += "<b>definition:</b> " + the_definition["def"] + "<br />" | |
if "example" in the_definition: | |
html_text += "<b>example:</b> " + the_definition["example"].replace("\n", "<br />") + "<br />" | |
bot.send_message_parsed(event.conv, html_text) | |
def _initialise(Handlers, bot=None): | |
Handlers.register_user_command(["urbandict"]) | |
return [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment