bobbit /modules/duckduckgo.py

Language Python Lines 59
MD5 Hash f38a1137065c7216a1024db21d0c8177 Estimated Cost $872 (why?)
Repository https://bitbucket.org/pbui/bobbit View Raw File View Project SPDX
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from __common__ import shorten_url, format_responses

import requests

# Constants

MODULE_NAME   = 'DuckDuckGo Instance Answer Search'
MODULE_ENABLE = True
MODULE_TYPE   = 'command'

DUCKDUCKGO_URL = u'http://api.duckduckgo.com'
DUCKDUCKGO_RE  = r'^!(ddg|duckduckgo)\s+'

# DuckDuckGo Instance Answer function
# https://duckduckgo.com/api

def duckduckgo(bot, nick, query, channel):
    query    = query[len(query.split()[0]) + 1:].strip()
    params   = {'q': query, 'format': 'json', 'no_html': 1, 'no_redirect': 1}
    results  = requests.get(DUCKDUCKGO_URL, params=params, timeout=bot.conn.requests_timeout)
    response = u'No results'

    try:
        result = results.json()

        if query.startswith('!'):
            title    = query[len(query.split()[0]) + 1:].strip()
            content  = ''
            url      = result['Redirect']
        else:
            title    = result['Heading']
            content  = result['AbstractText']
            url      = result['AbstractURL']

        if not title:
            raise KeyError

        if not content:
            response = u'{title} @ {url}'.format(**locals())
        else:
            response = u'{title} - {content} @ {url}'.format(**locals())

        shorturl = shorten_url(url)
        if url != shorturl:
            response = u'{response} || {shorturl}'.format(**locals())
    except (KeyError, IndexError):
        response = u'No results'

    return format_responses([response], nick, channel)

# Registration hook

def register_patterns(bot):
    return (
        (DUCKDUCKGO_RE, lambda nick, message, channel: duckduckgo(bot, nick, message, channel)),
    )

# vim: set sts=4 sw=4 ts=8 expandtab ft=python:
Back to Top