PageRenderTime 2ms CodeModel.GetById 3ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/ddg/__init__.py

https://github.com/arthaud/pipobot-modules
Python | 67 lines | 62 code | 3 blank | 2 comment | 3 complexity | 8c67fe7ce29e627092aa8126fdfc03a0 MD5 | raw file
 1#!/usr/bin/env python
 2#-*- coding: utf8 -*-
 3import BeautifulSoup
 4import urllib
 5import simplejson
 6import duckduckgo
 7from pipobot.lib.modules import SyncModule, defaultcmd
 8from pipobot.lib.utils import xhtml2text
 9
10MAX_RESULT = 5
11
12
13def ddg_request(msg):
14    rep = duckduckgo.query(msg)
15    if rep.type == "answer":
16        return "%s - %s" % (rep.abstract.text, rep.abstract.url)
17    elif rep.type == "nothing" or rep.type == "exclusive":
18        if rep.answer.text != "":
19            return rep.answer.text
20    elif rep.type == "disambiguation":
21        res = []
22        for result in rep.related:
23            if hasattr(result, "text"):
24                res.append("%s - %s" % (result.text, result.url))
25            else:
26                res.append("%s - %s" % (result.topics[0].text,
27                                        result.topics[0].url))
28        return "\n".join(res[:MAX_RESULT])
29    # If the API does not have return any usefull result, we do a real search in ddg
30    return html_request(msg)
31
32
33def html_request(msg):
34    site = urllib.urlopen('http://duckduckgo.com/html/?q=%s' % msg)
35    data = site.read()
36    soup = BeautifulSoup.BeautifulSoup(data)
37    site.close()
38
39    links = soup.findAll('div', {'class': "links_main links_deep"})
40    results = ""
41    for link in links[:MAX_RESULT]:
42        url = link.find("a").get("href")
43        contents = link.find("a").contents
44        title = ""
45        for data in contents:
46            if isinstance(data, BeautifulSoup.Tag):
47                title += " %s" % data.getString()
48            else:
49                title += " %s" % str(xhtml2text(data))
50        results += "%s - %s\n" % (title.strip(), url)
51
52    return results.strip()
53
54class CmdDDG(SyncModule):
55    def __init__(self, bot):
56        desc = u"!ddg mot-clé : recherche dans duckduckgo"
57        SyncModule.__init__(self,
58                            bot,
59                            desc=desc,
60                            name="ddg")
61
62    @defaultcmd
63    def answer(self, sender, message):
64        if message == '':
65            return self.desc
66        else:
67            return ddg_request(message)