Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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