# ddg module
# --gry

import urllib
import socket
import json

@plugin
class ddg(object):
    def __init__(self, server):
        self.server = server
        self.commands = ["ddg"]
        self.server.handle("command", self.handle_command, self.commands)
    
    def handle_command(self, channel, user, cmd, args):
        if cmd == "ddg":
            if len(args) < 1:
                self.server.doMessage(channel, user+": DuckDuckGo.com Zero-Click infoboxes search. Syntax: ddg <query>.")
                return
            try:
                request = "+".join(args)
                sock = urllib.urlopen("http://api.duckduckgo.com/?q=%s&o=json"%request)
                data = sock.read()
                sock.close()
                if json.loads(data)["AbstractText"] != "":
                    self.server.doMessage(channel, user+": "+"%s %s)"%(json.loads(data)["AbstractURL"].encode('utf-8'),json.loads(data)["AbstractText"].encode('utf-8')[0:200]))
                elif json.loads(data)["Definition"] != "":
                    self.server.doMessage(channel, user+": "+"%s %s"%(json.loads(data)["DefinitionURL"].encode('utf-8'),json.loads(data)["Definition"].encode('utf-8')))
            except Exception, e:
                self.server.doMessage(channel, user+": "+str(e))