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