A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

120 lines
4.5 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from gzip import GzipFile
  23. from json import loads
  24. from socket import error
  25. from StringIO import StringIO
  26. from urllib import quote
  27. from urllib2 import URLError
  28. from earwigbot import importer
  29. from earwigbot.exceptions import SearchQueryError
  30. oauth = importer.new("oauth2")
  31. __all__ = ["BaseSearchEngine", "YahooBOSSSearchEngine"]
  32. class BaseSearchEngine(object):
  33. """Base class for a simple search engine interface."""
  34. name = "Base"
  35. def __init__(self, cred, opener):
  36. """Store credentials (*cred*) and *opener* for searching later on."""
  37. self.cred = cred
  38. self.opener = opener
  39. def __repr__(self):
  40. """Return the canonical string representation of the search engine."""
  41. return "{0}()".format(self.__class__.__name__)
  42. def __str__(self):
  43. """Return a nice string representation of the search engine."""
  44. return "<{0}>".format(self.__class__.__name__)
  45. def search(self, query):
  46. """Use this engine to search for *query*.
  47. Not implemented in this base class; overridden in subclasses.
  48. """
  49. raise NotImplementedError()
  50. class YahooBOSSSearchEngine(BaseSearchEngine):
  51. """A search engine interface with Yahoo! BOSS."""
  52. name = "Yahoo! BOSS"
  53. @staticmethod
  54. def _build_url(base, params):
  55. """Works like urllib.urlencode(), but uses %20 for spaces over +."""
  56. enc = lambda s: quote(s.encode("utf8"), safe="")
  57. args = ["=".join((enc(k), enc(v))) for k, v in params.iteritems()]
  58. return base + "?" + "&".join(args)
  59. def search(self, query):
  60. """Do a Yahoo! BOSS web search for *query*.
  61. Returns a list of URLs, no more than five, ranked by relevance
  62. (as determined by Yahoo).
  63. Raises :py:exc:`~earwigbot.exceptions.SearchQueryError` on errors.
  64. """
  65. key, secret = self.cred["key"], self.cred["secret"]
  66. consumer = oauth.Consumer(key=key, secret=secret)
  67. url = "http://yboss.yahooapis.com/ysearch/web"
  68. params = {
  69. "oauth_version": oauth.OAUTH_VERSION,
  70. "oauth_nonce": oauth.generate_nonce(),
  71. "oauth_timestamp": oauth.Request.make_timestamp(),
  72. "oauth_consumer_key": consumer.key,
  73. "q": '"' + query.encode("utf8") + '"', "count": "5",
  74. "type": "html,text,pdf", "format": "json",
  75. }
  76. req = oauth.Request(method="GET", url=url, parameters=params)
  77. req.sign_request(oauth.SignatureMethod_HMAC_SHA1(), consumer, None)
  78. try:
  79. response = self.opener.open(self._build_url(url, req))
  80. result = response.read()
  81. except (URLError, error) as exc:
  82. raise SearchQueryError("Yahoo! BOSS Error: " + str(exc))
  83. if response.headers.get("Content-Encoding") == "gzip":
  84. stream = StringIO(result)
  85. gzipper = GzipFile(fileobj=stream)
  86. result = gzipper.read()
  87. if response.getcode() != 200:
  88. e = "Yahoo! BOSS Error: got response code '{0}':\n{1}'"
  89. raise SearchQueryError(e.format(response.getcode(), result))
  90. try:
  91. res = loads(result)
  92. except ValueError:
  93. e = "Yahoo! BOSS Error: JSON could not be decoded"
  94. raise SearchQueryError(e)
  95. try:
  96. results = res["bossresponse"]["web"]["results"]
  97. except KeyError:
  98. return []
  99. return [result["url"] for result in results]