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.

212 lines
7.1 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2016 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 re import sub as re_sub
  25. from socket import error
  26. from io import StringIO
  27. from urllib.parse import quote, urlencode
  28. from urllib.error import URLError
  29. from earwigbot import importer
  30. from earwigbot.exceptions import SearchQueryError
  31. lxml = importer.new("lxml")
  32. __all__ = ["BingSearchEngine", "GoogleSearchEngine", "YandexSearchEngine", "SEARCH_ENGINES"]
  33. class _BaseSearchEngine:
  34. """Base class for a simple search engine interface."""
  35. name = "Base"
  36. def __init__(self, cred, opener):
  37. """Store credentials (*cred*) and *opener* for searching later on."""
  38. self.cred = cred
  39. self.opener = opener
  40. self.count = 5
  41. def __repr__(self):
  42. """Return the canonical string representation of the search engine."""
  43. return "{0}()".format(self.__class__.__name__)
  44. def __str__(self):
  45. """Return a nice string representation of the search engine."""
  46. return "<{0}>".format(self.__class__.__name__)
  47. def _open(self, *args):
  48. """Open a URL (like urlopen) and try to return its contents."""
  49. try:
  50. response = self.opener.open(*args)
  51. result = response.read()
  52. except (URLError, error) as exc:
  53. err = SearchQueryError("{0} Error: {1}".format(self.name, exc))
  54. err.cause = exc
  55. raise err
  56. if response.headers.get("Content-Encoding") == "gzip":
  57. stream = StringIO(result)
  58. gzipper = GzipFile(fileobj=stream)
  59. result = gzipper.read()
  60. code = response.getcode()
  61. if code != 200:
  62. err = "{0} Error: got response code '{1}':\n{2}'"
  63. raise SearchQueryError(err.format(self.name, code, result))
  64. return result
  65. @staticmethod
  66. def requirements():
  67. """Return a list of packages required by this search engine."""
  68. return []
  69. def search(self, query):
  70. """Use this engine to search for *query*.
  71. Not implemented in this base class; overridden in subclasses.
  72. """
  73. raise NotImplementedError()
  74. class BingSearchEngine(_BaseSearchEngine):
  75. """A search engine interface with Bing Search (via Azure Marketplace)."""
  76. name = "Bing"
  77. def __init__(self, cred, opener):
  78. super().__init__(cred, opener)
  79. key = self.cred["key"]
  80. auth = (key + ":" + key).encode("base64").replace("\n", "")
  81. self.opener.addheaders.append(("Authorization", "Basic " + auth))
  82. def search(self, query):
  83. """Do a Bing web search for *query*.
  84. Returns a list of URLs ranked by relevance (as determined by Bing).
  85. Raises :py:exc:`~earwigbot.exceptions.SearchQueryError` on errors.
  86. """
  87. service = "SearchWeb" if self.cred["type"] == "searchweb" else "Search"
  88. url = "https://api.datamarket.azure.com/Bing/{0}/Web?".format(service)
  89. params = {
  90. "$format": "json",
  91. "$top": str(self.count),
  92. "Query": "'\"" + query.replace('"', "").encode("utf8") + "\"'",
  93. "Market": "'en-US'",
  94. "Adult": "'Off'",
  95. "Options": "'DisableLocationDetection'",
  96. "WebSearchOptions": "'DisableHostCollapsing+DisableQueryAlterations'"
  97. }
  98. result = self._open(url + urlencode(params))
  99. try:
  100. res = loads(result)
  101. except ValueError:
  102. err = "Bing Error: JSON could not be decoded"
  103. raise SearchQueryError(err)
  104. try:
  105. results = res["d"]["results"]
  106. except KeyError:
  107. return []
  108. return [result["Url"] for result in results]
  109. class GoogleSearchEngine(_BaseSearchEngine):
  110. """A search engine interface with Google Search."""
  111. name = "Google"
  112. def search(self, query):
  113. """Do a Google web search for *query*.
  114. Returns a list of URLs ranked by relevance (as determined by Google).
  115. Raises :py:exc:`~earwigbot.exceptions.SearchQueryError` on errors.
  116. """
  117. domain = self.cred.get("proxy", "www.googleapis.com")
  118. url = "https://{0}/customsearch/v1?".format(domain)
  119. params = {
  120. "cx": self.cred["id"],
  121. "key": self.cred["key"],
  122. "q": '"' + query.replace('"', "").encode("utf8") + '"',
  123. "alt": "json",
  124. "num": str(self.count),
  125. "safe": "off",
  126. "fields": "items(link)"
  127. }
  128. result = self._open(url + urlencode(params))
  129. try:
  130. res = loads(result)
  131. except ValueError:
  132. err = "Google Error: JSON could not be decoded"
  133. raise SearchQueryError(err)
  134. try:
  135. return [item["link"] for item in res["items"]]
  136. except KeyError:
  137. return []
  138. class YandexSearchEngine(_BaseSearchEngine):
  139. """A search engine interface with Yandex Search."""
  140. name = "Yandex"
  141. @staticmethod
  142. def requirements():
  143. return ["lxml.etree"]
  144. def search(self, query):
  145. """Do a Yandex web search for *query*.
  146. Returns a list of URLs ranked by relevance (as determined by Yandex).
  147. Raises :py:exc:`~earwigbot.exceptions.SearchQueryError` on errors.
  148. """
  149. domain = self.cred.get("proxy", "yandex.com")
  150. url = "https://{0}/search/xml?".format(domain)
  151. query = re_sub(r"[^a-zA-Z0-9 ]", "", query).encode("utf8")
  152. params = {
  153. "user": self.cred["user"],
  154. "key": self.cred["key"],
  155. "query": '"' + query + '"',
  156. "l10n": "en",
  157. "filter": "none",
  158. "maxpassages": "1",
  159. "groupby": "mode=flat.groups-on-page={0}".format(self.count)
  160. }
  161. result = self._open(url + urlencode(params))
  162. try:
  163. data = lxml.etree.fromstring(result)
  164. return [elem.text for elem in data.xpath(".//url")]
  165. except lxml.etree.Error as exc:
  166. raise SearchQueryError("Yandex XML parse error: " + str(exc))
  167. SEARCH_ENGINES = {
  168. "Bing": BingSearchEngine,
  169. "Google": GoogleSearchEngine,
  170. "Yandex": YandexSearchEngine
  171. }