PageRenderTime 16ms CodeModel.GetById 1ms app.highlight 10ms RepoModel.GetById 2ms app.codeStats 0ms

/irc3/plugins/search.py

https://github.com/chassing/irc3
Python | 51 lines | 50 code | 0 blank | 1 comment | 0 complexity | f7de96e86db90f6f07905c9925f00452 MD5 | raw file
 1# -*- coding: utf-8 -*-
 2from irc3.plugins.command import command
 3import irc3
 4__doc__ = '''
 5==============================================
 6:mod:`irc3.plugins.search` Search plugin
 7==============================================
 8
 9.. autoclass:: Search
10'''
11
12
13@irc3.plugin
14class Search:
15
16    requires = [
17        __name__.replace('search', 'command'),
18    ]
19
20    headers = {
21        'User-Agent': 'python-requests/irc3/search',
22        'Cache-Control': 'max-age=0',
23        'Pragma': 'no-cache',
24    }
25
26    def __init__(self, bot):
27        self.bot = bot
28        try:
29            import requests
30            self.session = requests.Session()
31            self.session.headers.update(self.headers)
32        except ImportError:  # pragma: no cover
33            self.session = None
34
35    @command(permission='view')
36    def ddg(self, mask, target, args):
37        """Search using https://duckduckgo.com/api
38
39            %%ddg <query>...
40        """
41        q = ' '.join(args['<query>'])
42        resp = self.session.get('http://api.duckduckgo.com/',
43                                params=dict(q=q, format='json', t='irc3'),
44                                allow_redirects=False)
45        ctype = resp.headers['content-type']
46        if 'json' in ctype or 'javascript' in ctype:
47            if resp.status_code == 200:
48                data = resp.json()
49                return '{AbstractText} - {AbstractURL}'.format(**data)
50            elif resp.status_code == 303:
51                return 'Redirect to: {0}'.format(resp.headers['location'])