PageRenderTime 67ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/ddg/__init__.py

https://github.com/arthaud/pipobot-modules
Python | 67 lines | 62 code | 3 blank | 2 comment | 4 complexity | 8c67fe7ce29e627092aa8126fdfc03a0 MD5 | raw file
  1. #!/usr/bin/env python
  2. #-*- coding: utf8 -*-
  3. import BeautifulSoup
  4. import urllib
  5. import simplejson
  6. import duckduckgo
  7. from pipobot.lib.modules import SyncModule, defaultcmd
  8. from pipobot.lib.utils import xhtml2text
  9. MAX_RESULT = 5
  10. def ddg_request(msg):
  11. rep = duckduckgo.query(msg)
  12. if rep.type == "answer":
  13. return "%s - %s" % (rep.abstract.text, rep.abstract.url)
  14. elif rep.type == "nothing" or rep.type == "exclusive":
  15. if rep.answer.text != "":
  16. return rep.answer.text
  17. elif rep.type == "disambiguation":
  18. res = []
  19. for result in rep.related:
  20. if hasattr(result, "text"):
  21. res.append("%s - %s" % (result.text, result.url))
  22. else:
  23. res.append("%s - %s" % (result.topics[0].text,
  24. result.topics[0].url))
  25. return "\n".join(res[:MAX_RESULT])
  26. # If the API does not have return any usefull result, we do a real search in ddg
  27. return html_request(msg)
  28. def html_request(msg):
  29. site = urllib.urlopen('http://duckduckgo.com/html/?q=%s' % msg)
  30. data = site.read()
  31. soup = BeautifulSoup.BeautifulSoup(data)
  32. site.close()
  33. links = soup.findAll('div', {'class': "links_main links_deep"})
  34. results = ""
  35. for link in links[:MAX_RESULT]:
  36. url = link.find("a").get("href")
  37. contents = link.find("a").contents
  38. title = ""
  39. for data in contents:
  40. if isinstance(data, BeautifulSoup.Tag):
  41. title += " %s" % data.getString()
  42. else:
  43. title += " %s" % str(xhtml2text(data))
  44. results += "%s - %s\n" % (title.strip(), url)
  45. return results.strip()
  46. class CmdDDG(SyncModule):
  47. def __init__(self, bot):
  48. desc = u"!ddg mot-clé : recherche dans duckduckgo"
  49. SyncModule.__init__(self,
  50. bot,
  51. desc=desc,
  52. name="ddg")
  53. @defaultcmd
  54. def answer(self, sender, message):
  55. if message == '':
  56. return self.desc
  57. else:
  58. return ddg_request(message)