PageRenderTime 59ms CodeModel.GetById 54ms app.highlight 4ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins/duckduckgo.py

http://github.com/Reisen/bruh
Python | 75 lines | 44 code | 15 blank | 16 comment | 7 complexity | cd8021234af2588d0ba40147e2382497 MD5 | raw file
 1"""
 2    This module wraps the DDG Instant Answer API. A godamn badass API.  At some
 3    point this might be the default entry point for the .calc command instead
 4    of the google calculator.
 5"""
 6from urllib.parse import quote_plus, unquote_plus, urlencode
 7from urllib.request import urlopen, Request
 8from plugins import mod
 9import json
10
11hook = mod.hook
12
13def handle_exclusive(query):
14    return query['Answer']
15
16
17def handle_article(query):
18    return query['AbstractText']
19
20
21def handle_disambiguation(query):
22    # DDG Figured out a probable result for us.
23    if query['AbstractText']:
24        return query['AbstractText']
25
26    # Or maybe a probable definition.
27    if query['Definition']:
28        return '{} (Source: {})'.format(
29            query['Definition'],
30            query['DefinitionSource'] if query['DefinitionSource'] else query['AbstractSource']
31        )
32
33    # Or maybe DDG figured out NOTHING, in which case lets just hope the first
34    # related topic is sensible.
35    return query['RelatedTopics'][0]['Text']
36
37
38@hook.command(['ddg'])
39def duckduckgo(irc, nick, chan, msg, args):
40    """
41    DuckDuckGo Instant API.
42    .ddg <expression>
43    """
44    if not msg:
45        return "Syntax: .ddg <expression>"
46
47    # Build the request. DuckDuckGo requires an app name parameter for request
48    # attribution, so don't remove this.
49    request = Request(
50        'https://api.duckduckgo.com/?{}'.format(urlencode({
51            'q': msg,
52            'format': 'json',
53            'pretty': 1,
54            'no_redirect': 1,
55            'no_html': 1
56        })),
57        headers = {
58        }
59    )
60
61    try:
62        query = json.loads(urlopen(request, timeout = 7).read().decode('UTF-8'))
63
64        # Dispatch to a function that understands the format type returned.
65        output = {
66            'E': lambda: handle_exclusive(query),
67            'A': lambda: handle_article(query),
68            'D': lambda: handle_disambiguation(query)
69        }[query['Type']]()
70
71        if output:
72            return output
73
74    except Exception as e:
75        return "No decent results found for those terms."