Created
June 25, 2013 19:45
-
-
Save rbistolfi/5861725 to your computer and use it in GitHub Desktop.
Lalita plugin for ddg definitions
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
# -*- coding: utf8 -*- | |
# Copyright 2009 laliputienses | |
# License: GPL v3 | |
# For further info, see LICENSE file | |
import json | |
import urllib | |
from twisted.web import client | |
from lalita import Plugin | |
TRANSLATION_TABLE = {} | |
class Define(Plugin): | |
url_template = "http://api.duckduckgo.com/?q=%s&format=json&t=lalita" | |
def init(self, config): | |
self.register_translation(self, TRANSLATION_TABLE) | |
self.register(self.events.COMMAND, self.define_command, ['define']) | |
def define_command(self, user, channel, command, *keywords): | |
u"Search word definition in ddg" | |
keyword = " ".join(keywords) | |
return self._define(user, channel, keyword) | |
def _define(self, user, channel, keyword): | |
d = self._api_call(keyword) | |
d.addCallback(self._answer, user, channel) | |
return d | |
def _api_call(self, keyword): | |
keyword = keyword.encode("utf8") | |
keyword = urllib.quote_plus(keyword) | |
url = self.url_template % (keyword,) | |
self.logger.debug("Downloading %s", url) | |
d = client.getPage(url) | |
return d | |
def _answer(self, api_response, user, channel): | |
d = json.loads(api_response) | |
answer = d["Definition"] | |
if not answer: | |
answer = "Not found" | |
self.say(channel, "%s: %s", user, answer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment