PageRenderTime 213ms CodeModel.GetById 111ms app.highlight 5ms RepoModel.GetById 96ms app.codeStats 0ms

/plugins/ddg.py

https://bitbucket.org/dwfreed/guppy
Python | 55 lines | 29 code | 4 blank | 22 comment | 2 complexity | 977c147a837af7c8c9a96dcf6f7328b9 MD5 | raw file
 1#    guppy Copyright (C) 2010-2011 guppy team members.
 2#
 3#    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
 4#    This is free software, and you are welcome to redistribute it
 5#    under certain conditions; type `show c' for details.
 6#  This program is free software; you can redistribute it and/or modify
 7#  it under the terms of the GNU General Public License as published by
 8#  the Free Software Foundation; either version 2 of the License, or
 9#  (at your option) any later version.
10#  
11#  This program is distributed in the hope that it will be useful,
12#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14#  GNU General Public License for more details.
15#  
16#  You should have received a copy of the GNU General Public License
17#  along with this program; if not, write to the Free Software
18#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19#  MA 02110-1301, USA.
20
21# ddg module
22# --gry
23
24import urllib.request
25from urllib.error import HTTPError,URLError
26import socket
27import json
28
29@plugin
30class ddg(object):
31    """DuckDuckGo search tools. Currently just 0-click info."""
32    def __init__(self, server):
33        self.server = server
34        self.commands = ["ddg"]
35        self.server.handle("command", self.handle_command, self.commands)
36    
37    def handle_command(self, channel, user, cmd, args):
38        if len(args) < 1:
39            self.server.doMessage(channel, user+": DuckDuckGo.com Zero-Click infoboxes search. Syntax: ddg <query>.")
40            return
41        try:
42            request = "+".join(args)
43            sock = urllib.request.urlopen("http://api.duckduckgo.com/?q=%s&o=json" % request)
44            data = sock.read()
45            sock.close()
46            data = data.decode('utf-8')
47            jl = json.loads(data)
48            if str(jl["AbstractText"]) != "":
49                self.server.doMessage(channel, user+": "+"%s %s)"%(str(jl["AbstractURL"]),str(jl["AbstractText"][0:200])))
50            elif str(jl["Definition"]) != "":
51                self.server.doMessage(channel, user+": "+"%s %s"%(str(jl["DefinitionURL"]),str(jl["Definition"])))
52        except Exception as e:
53            self.server.doMessage(channel, user+": "+str(e))
54
55