PageRenderTime 144ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/ddg.py

https://bitbucket.org/dwfreed/guppy
Python | 55 lines | 29 code | 4 blank | 22 comment | 3 complexity | 977c147a837af7c8c9a96dcf6f7328b9 MD5 | raw file
  1. # guppy Copyright (C) 2010-2011 guppy team members.
  2. #
  3. # This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
  4. # This is free software, and you are welcome to redistribute it
  5. # under certain conditions; type `show c' for details.
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. # MA 02110-1301, USA.
  20. # ddg module
  21. # --gry
  22. import urllib.request
  23. from urllib.error import HTTPError,URLError
  24. import socket
  25. import json
  26. @plugin
  27. class ddg(object):
  28. """DuckDuckGo search tools. Currently just 0-click info."""
  29. def __init__(self, server):
  30. self.server = server
  31. self.commands = ["ddg"]
  32. self.server.handle("command", self.handle_command, self.commands)
  33. def handle_command(self, channel, user, cmd, args):
  34. if len(args) < 1:
  35. self.server.doMessage(channel, user+": DuckDuckGo.com Zero-Click infoboxes search. Syntax: ddg <query>.")
  36. return
  37. try:
  38. request = "+".join(args)
  39. sock = urllib.request.urlopen("http://api.duckduckgo.com/?q=%s&o=json" % request)
  40. data = sock.read()
  41. sock.close()
  42. data = data.decode('utf-8')
  43. jl = json.loads(data)
  44. if str(jl["AbstractText"]) != "":
  45. self.server.doMessage(channel, user+": "+"%s %s)"%(str(jl["AbstractURL"]),str(jl["AbstractText"][0:200])))
  46. elif str(jl["Definition"]) != "":
  47. self.server.doMessage(channel, user+": "+"%s %s"%(str(jl["DefinitionURL"]),str(jl["Definition"])))
  48. except Exception as e:
  49. self.server.doMessage(channel, user+": "+str(e))