PageRenderTime 2ms CodeModel.GetById 67ms app.highlight 6ms RepoModel.GetById 45ms app.codeStats 0ms

/modules/duckduckgo.py

https://bitbucket.org/pbui/bobbit
Python | 58 lines | 47 code | 8 blank | 3 comment | 1 complexity | f38a1137065c7216a1024db21d0c8177 MD5 | raw file
 1from __common__ import shorten_url, format_responses
 2
 3import requests
 4
 5# Constants
 6
 7MODULE_NAME   = 'DuckDuckGo Instance Answer Search'
 8MODULE_ENABLE = True
 9MODULE_TYPE   = 'command'
10
11DUCKDUCKGO_URL = u'http://api.duckduckgo.com'
12DUCKDUCKGO_RE  = r'^!(ddg|duckduckgo)\s+'
13
14# DuckDuckGo Instance Answer function
15# https://duckduckgo.com/api
16
17def duckduckgo(bot, nick, query, channel):
18    query    = query[len(query.split()[0]) + 1:].strip()
19    params   = {'q': query, 'format': 'json', 'no_html': 1, 'no_redirect': 1}
20    results  = requests.get(DUCKDUCKGO_URL, params=params, timeout=bot.conn.requests_timeout)
21    response = u'No results'
22
23    try:
24        result = results.json()
25
26        if query.startswith('!'):
27            title    = query[len(query.split()[0]) + 1:].strip()
28            content  = ''
29            url      = result['Redirect']
30        else:
31            title    = result['Heading']
32            content  = result['AbstractText']
33            url      = result['AbstractURL']
34
35        if not title:
36            raise KeyError
37
38        if not content:
39            response = u'{title} @ {url}'.format(**locals())
40        else:
41            response = u'{title} - {content} @ {url}'.format(**locals())
42
43        shorturl = shorten_url(url)
44        if url != shorturl:
45            response = u'{response} || {shorturl}'.format(**locals())
46    except (KeyError, IndexError):
47        response = u'No results'
48
49    return format_responses([response], nick, channel)
50
51# Registration hook
52
53def register_patterns(bot):
54    return (
55        (DUCKDUCKGO_RE, lambda nick, message, channel: duckduckgo(bot, nick, message, channel)),
56    )
57
58# vim: set sts=4 sw=4 ts=8 expandtab ft=python: