Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

235 wiersze
8.4 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 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 collections import namedtuple
  23. from datetime import datetime
  24. from difflib import ndiff
  25. from Queue import Queue
  26. import re
  27. from threading import Thread
  28. from earwigbot.commands import Command
  29. from earwigbot.exceptions import APIError
  30. from earwigbot.irc import RC
  31. from earwigbot.wiki import constants
  32. _Diff = namedtuple("_Diff", ["added", "removed"])
  33. class RCMonitor(Command):
  34. """Monitors the recent changes feed for certain edits and reports them to a
  35. dedicated channel."""
  36. name = "rc_monitor"
  37. hooks = ["msg", "rc"]
  38. def setup(self):
  39. try:
  40. self._channel = self.config.commands[self.name]["channel"]
  41. except KeyError:
  42. self._channel = None
  43. log = ('Cannot use without a report channel set as '
  44. 'config.commands["{0}"]["channel"]')
  45. self.logger.warn(log.format(self.name))
  46. self._stats = {
  47. "start": datetime.utcnow(),
  48. "edits": 0,
  49. "hits": 0,
  50. "max_backlog": 0
  51. }
  52. self._levels = {}
  53. self._issues = {}
  54. self._descriptions = {}
  55. self._redirects = {}
  56. self._queue = Queue()
  57. self._thread = Thread(target=self._callback, name="rc_monitor")
  58. self._thread.daemon = True
  59. self._thread.running = True
  60. self._prepare_reports()
  61. self._thread.start()
  62. def check(self, data):
  63. if not self._channel:
  64. return
  65. return isinstance(data, RC) or (
  66. data.is_command and data.command == self.name)
  67. def process(self, data):
  68. if isinstance(data, RC):
  69. newlen = self._queue.qsize() + 1
  70. self._queue.put(data)
  71. if newlen > self._stats["max_backlog"]:
  72. self._stats["max_backlog"] = newlen
  73. return
  74. if not self.config.irc["permissions"].is_admin(data):
  75. self.reply(data, "You must be a bot admin to use this command.")
  76. return
  77. since = self._stats["start"].strftime("%H:%M:%S, %d %B %Y")
  78. seconds = (datetime.utcnow() - self._stats["start"]).total_seconds()
  79. rate = self._stats["edits"] / seconds
  80. msg = ("\x02{edits:,}\x0F edits checked since {since} "
  81. "(\x02{rate:.2f}\x0F edits/sec); \x02{hits:,}\x0F hits; "
  82. "\x02{qsize:,}\x0F-edit backlog (\x02{max_backlog:,}\x0F max).")
  83. self.reply(data, msg.format(
  84. since=since, rate=rate, qsize=self._queue.qsize(), **self._stats))
  85. def unload(self):
  86. self._thread.running = False
  87. self._queue.put(None)
  88. def _prepare_reports(self):
  89. """Set up internal tables for storing report information."""
  90. routine = 1
  91. alert = 2
  92. urgent = 3
  93. self._levels = {
  94. routine: "routine",
  95. alert: "alert",
  96. urgent: "URGENT"
  97. }
  98. self._issues = {
  99. "g10": alert
  100. }
  101. self._descriptions = {
  102. "g10": "CSD G10 nomination"
  103. }
  104. def _get_diff(self, oldrev, newrev):
  105. """Return the difference between two revisions.
  106. A diff is a 2-tuple: (list of lines added, list of lines removed).
  107. """
  108. site = self.bot.wiki.get_site()
  109. try:
  110. result = site.api_query(
  111. action="query", prop="revisions", rvprop="ids|content",
  112. revids=oldrev + "|" + newrev)
  113. except APIError:
  114. return None
  115. try:
  116. pages = result["query"]["pages"].values()
  117. except IndexError:
  118. return None
  119. if len(pages) != 1:
  120. return None
  121. revs = pages[0]["revisions"]
  122. try:
  123. oldtext = [rv["*"] for rv in revs if rv["revid"] == int(oldrev)][0]
  124. newtext = [rv["*"] for rv in revs if rv["revid"] == int(newrev)][0]
  125. except (IndexError, KeyError):
  126. return None
  127. lines = list(ndiff(oldtext.splitlines(), newtext.splitlines()))
  128. added = [line[2:] for line in lines if line[:2] == "+ "]
  129. removed = [line[2:] for line in lines if line[:2] == "- "]
  130. return _Diff(added, removed)
  131. def _fetch_redirects(self, template):
  132. """Return a list of valid names for a given template."""
  133. site = self.bot.wiki.get_site()
  134. try:
  135. result = site.api_query(
  136. action="query", list="backlinks", blfilterredir="redirects",
  137. blnamespace=constants.NS_TEMPLATE, bllimit=50,
  138. bltitle="Template:" + template)
  139. except APIError:
  140. return []
  141. redirs = {link["title"].split(":", 1)[1].lower()
  142. for link in result["query"]["backlinks"]}
  143. redirs.add(template)
  144. return redirs
  145. def _fast_template_search(self, template):
  146. """Return a compiled regular expression for matching templates."""
  147. if template not in self._redirects:
  148. redirects = self._fetch_redirects(template)
  149. if not redirects:
  150. return None
  151. self._redirects[template] = redirects
  152. search = "|".join("(template:)?" + re.escape(tmpl).replace(" ", "[ _]")
  153. for tmpl in self._redirects[template])
  154. return re.compile(r"\{\{\s*" + search + r"\s*(\||\}\})", re.U|re.I)
  155. def _evaluate_csd(self, diff):
  156. """Evaluate a diff for CSD tagging."""
  157. regex = self._fast_template_search("db-g10")
  158. if not regex:
  159. return []
  160. if any(regex.search(line) for line in diff.added):
  161. return ["g10"]
  162. return []
  163. def _evaluate(self, event):
  164. """Return heuristic information about the given RC event."""
  165. oldrev = re.search(r"(?:\?|&)oldid=(.*?)(?:&|$)", event.url)
  166. newrev = re.search(r"(?:\?|&)diff=(.*?)(?:&|$)", event.url)
  167. if not oldrev or not newrev:
  168. return []
  169. diff = self._get_diff(oldrev.group(1), newrev.group(1))
  170. if not diff:
  171. return []
  172. issues = []
  173. issues.extend(self._evaluate_csd(diff))
  174. issues.sort(key=lambda issue: self._issues[issue], reverse=True)
  175. return issues
  176. def _format(self, rc, report):
  177. """Format a RC event for the report channel."""
  178. level = self._levels[max(self._issues[issue] for issue in report)]
  179. descr = ", ".join(self._descriptions[issue] for issue in report)
  180. notify = " ".join("!rcm-" + issue for issue in report)
  181. cmnt = rc.comment if len(rc.comment) <= 50 else rc.comment[:47] + "..."
  182. msg = ("[\x02{level}\x0F] ({descr}) [\x02{notify}\x0F]\x0306 * "
  183. "\x0314[[\x0307{title}\x0314]]\x0306 * \x0303{user}\x0306 * "
  184. "\x0302{url}\x0306 * \x0310{comment}")
  185. return msg.format(
  186. level=level, descr=descr, notify=notify, title=rc.page,
  187. user=rc.user, url=rc.url, comment=cmnt)
  188. def _handle_event(self, event):
  189. """Process a recent change event."""
  190. if not event.is_edit or "B" in event.flags:
  191. return
  192. report = self._evaluate(event)
  193. self._stats["edits"] += 1
  194. if report:
  195. self.say(self._channel, self._format(event, report))
  196. self._stats["hits"] += 1
  197. def _callback(self):
  198. """Internal callback for the RC monitor thread."""
  199. while self._thread.running:
  200. event = self._queue.get()
  201. if not self._thread.running:
  202. break
  203. self._handle_event(event)