A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

132 linhas
5.2 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by Ben Kurtovic <ben.kurtovic@verizon.net>
  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 os.path import expanduser
  23. from threading import Lock
  24. import oursql
  25. from earwigbot import wiki
  26. from earwigbot.classes import BaseTask
  27. from earwigbot.config import config
  28. class Task(BaseTask):
  29. """A task to check newly-edited [[WP:AFC]] submissions for copyright
  30. violations."""
  31. name = "afc_copyvios"
  32. number = 1
  33. def __init__(self):
  34. config.decrypt(config.tasks, self.name, "search", "credentials", "key")
  35. config.decrypt(config.tasks, self.name, "search", "credentials", "secret")
  36. cfg = config.tasks.get(self.name, {})
  37. self.template = cfg.get("template", "AfC suspected copyvio")
  38. self.ignore_list = cfg.get("ignoreList", [])
  39. self.min_confidence = cfg.get("minConfidence", 0.75)
  40. self.max_queries = cfg.get("maxQueries", 10)
  41. default_summary = "Tagging suspected [[WP:COPYVIO|copyright violation]] of {url}"
  42. self.summary = self.make_summary(cfg.get("summary", default_summary))
  43. # Search API data:
  44. search = cfg.get("search", {})
  45. self.engine = search.get("engine")
  46. self.credentials = search.get("credentials", {})
  47. # Connection data for our SQL database:
  48. kwargs = cfg.get("sql", {})
  49. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  50. self.conn_data = kwargs
  51. self.db_access_lock = Lock()
  52. def run(self, **kwargs):
  53. """Entry point for the bot task.
  54. Takes a page title in kwargs and checks it for copyvios, adding
  55. {{self.template}} at the top if a copyvio has been detected. A page is
  56. only checked once (processed pages are stored by page_id in an SQL
  57. database).
  58. """
  59. if self.shutoff_enabled():
  60. return
  61. title = kwargs["page"]
  62. page = wiki.get_site().get_page(title)
  63. with self.db_access_lock:
  64. self.conn = oursql.connect(**self.conn_data)
  65. self.process(page)
  66. def process(self, page):
  67. """Detect copyvios in 'page' and add a note if any are found."""
  68. title = page.title()
  69. if title in self.ignore_list:
  70. msg = "Skipping page in ignore list: [[{0}]]"
  71. self.logger.info(msg.format(title))
  72. return
  73. pageid = page.pageid()
  74. if self.has_been_processed(pageid):
  75. msg = "Skipping check on already processed page [[{0}]]"
  76. self.logger.info(msg.format(title))
  77. return
  78. self.logger.info("Checking [[{0}]]".format(title))
  79. result = page.copyvio_check(self.engine, self.credentials,
  80. self.min_confidence, self.max_queries)
  81. url = result.url
  82. confidence = "{0}%".format(round(result.confidence * 100, 2))
  83. if result.violation:
  84. content = page.get()
  85. template = "\{\{{0}|url={1}|confidence={2}\}\}"
  86. template = template.format(self.template, url, confidence)
  87. newtext = "\n".join((template, content))
  88. if "{url}" in self.summary:
  89. page.edit(newtext, self.summary.format(url=url))
  90. else:
  91. page.edit(newtext, self.summary)
  92. msg = "Found violation: [[{0}]] -> {1} ({2} confidence)"
  93. self.logger.warn(msg.format(title, url, confidence))
  94. else:
  95. msg = "No violations detected (best: {1} at {2} confidence)"
  96. self.logger.debug(msg.format(url, confidence))
  97. self.log_processed(pageid)
  98. def has_been_processed(self, pageid):
  99. """Returns True if pageid was processed before, otherwise False."""
  100. query = "SELECT 1 FROM processed WHERE page_id = ?"
  101. with self.conn.cursor() as cursor:
  102. cursor.execute(query, (pageid,))
  103. results = cursor.fetchall()
  104. if results:
  105. return True
  106. return False
  107. def log_processed(self, pageid):
  108. """Adds pageid to our database of processed pages.
  109. Raises an exception if the page has already been processed.
  110. """
  111. query = "INSERT INTO processed VALUES (?)"
  112. with self.conn.cursor() as cursor:
  113. cursor.execute(query, (pageid,))