A Python robot that edits Wikipedia and interacts with people over IRC 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.

358 wiersze
14 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. import logging
  4. import re
  5. from os.path import expanduser
  6. from threading import Lock
  7. import oursql
  8. from classes import BaseTask
  9. import config
  10. import wiki
  11. class Task(BaseTask):
  12. """A task to generate statistics for WikiProject Articles for Creation.
  13. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  14. accessed with oursql. Statistics are updated live while watching the recent
  15. changes IRC feed and saved once an hour, on the hour, to self.pagename.
  16. In the live bot, this is "Template:AFC statistics".
  17. """
  18. name = "afc_statistics"
  19. number = 2
  20. def __init__(self):
  21. self.cfg = cfg = config.tasks.get(self.name, {})
  22. # Set some wiki-related attributes:
  23. self.pagename = cfg.get("page", "Template:AFC statistics")
  24. self.pending_cat = cfg.get("pending", "Pending AfC submissions")
  25. self.ignore_list = cfg.get("ignore_list", [])
  26. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  27. self.summary = self.make_summary(cfg.get("summary", default_summary))
  28. # Templates used in chart generation:
  29. templates = cfg.get("templates", {})
  30. self.tl_header = templates.get("header", "AFC statistics/header")
  31. self.tl_row = templates.get("row", "AFC statistics/row")
  32. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  33. # Connection data for our SQL database:
  34. kwargs = cfg.get("sql", {})
  35. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  36. self.conn_data = kwargs
  37. self.db_access_lock = Lock()
  38. def run(self, **kwargs):
  39. self.site = wiki.get_site()
  40. self.conn = oursql.connect(**self.conn_data)
  41. action = kwargs.get("action")
  42. try:
  43. if action == "save":
  44. self.save()
  45. elif action == "sync":
  46. self.sync()
  47. finally:
  48. self.conn.close()
  49. def save(self, **kwargs):
  50. self.logger.info("Saving chart")
  51. if kwargs.get("fromIRC"):
  52. summary = " ".join((self.summary, "(!earwigbot)"))
  53. else:
  54. if self.shutoff_enabled():
  55. return
  56. summary = self.summary
  57. statistics = self.compile_charts()
  58. page = self.site.get_page(self.pagename)
  59. text = page.get()
  60. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  61. statistics.join(("\\1\n", "\n\\3")), text,
  62. flags=re.DOTALL)
  63. if newtext == text:
  64. self.logger.info("Chart unchanged; not saving")
  65. return # Don't edit the page if we're not adding anything
  66. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  67. "\\1~~~ at ~~~~~\\3", newtext)
  68. page.edit(newtext, summary, minor=True, bot=True)
  69. self.logger.info("Chart saved to [[{0}]]".format(page.title()))
  70. def compile_charts(self):
  71. stats = ""
  72. with self.conn.cursor() as cursor, self.db_access_lock:
  73. cursor.execute("SELECT * FROM chart")
  74. for chart in cursor:
  75. stats += self.compile_chart(chart) + "\n"
  76. return stats[:-1] # Drop the last newline
  77. def compile_chart(self, chart_info):
  78. chart_id, chart_title, special_title = chart_info
  79. chart = "|".join((self.tl_header, chart_title))
  80. if special_title:
  81. chart += "".join(("|", special_title))
  82. chart = "".join(("{{", chart, "}}"))
  83. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  84. with self.conn.cursor(oursql.DictCursor) as cursor:
  85. cursor.execute(query, (chart_id,))
  86. for page in cursor:
  87. chart += "\n" + self.compile_chart_row(page)
  88. chart += "".join(("\n{{", self.tl_footer, "}}"))
  89. return chart
  90. def compile_chart_row(self, page):
  91. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  92. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  93. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  94. page["page_create_time"] = self.format_time(page["page_create_time"])
  95. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  96. if page["page_special_user"]:
  97. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  98. page["page_special_time"] = self.format_time(page["page_special_time"])
  99. if page["page_notes"]:
  100. row += "n=1{page_notes}"
  101. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  102. def format_time(self, timestamp):
  103. return timestamp.strftime("%H:%M, %d %B %Y")
  104. def sync(self, **kwargs):
  105. self.logger.info("Starting sync")
  106. self.report_replag()
  107. with self.conn.cursor() as cursor, self.db_access_lock:
  108. self.update_tracked(cursor)
  109. self.add_untracked(cursor)
  110. self.delete_old(cursor)
  111. self.logger.info("Sync completed")
  112. def report_replag(self):
  113. replag = self.site.get_replag()
  114. if replag < 60:
  115. lvl = logging.DEBUG
  116. elif replag < 720:
  117. lvl = logging.INFO
  118. else:
  119. lvl = logging.WARNING
  120. self.logger.log(lvl, "Server replag is {0}".format(replag))
  121. def update_tracked(self, cursor):
  122. self.logger.debug("Updating tracked submissions")
  123. query1 = "SELECT page_id, page_title, page_modify_oldid FROM page"
  124. query2 = "SELECT page_latest, page_title FROM page WHERE page_id = ?"
  125. cursor.execute(query1)
  126. for pageid, title, oldid in cursor:
  127. msg = "Updating tracked page: [[{0}]] (id: {1}) @ {2}"
  128. self.logger.debug(msg.format(pageid, title, oldid))
  129. result = list(self.site.sql_query(query2, (pageid,)))
  130. try:
  131. real_oldid = result[0][0]
  132. real_title = result[0][1]
  133. except IndexError: # Page doesn't exist!
  134. self.untrack_page(cursor, pageid)
  135. continue
  136. if real_oldid != oldid:
  137. self.update_page(cursor, pageid, real_title)
  138. def add_untracked(self, cursor):
  139. self.logger.debug("Adding untracked pending submissions")
  140. cursor.execute("SELECT page_id FROM page")
  141. tracked = [i[0] for i in cursor.fetchall()]
  142. category = self.site.get_category(self.pending_cat)
  143. pending = category.members(limit=500)
  144. for title, pageid in pending:
  145. if title in self.ignore_list:
  146. continue
  147. if pageid not in tracked:
  148. self.track_page(cursor, pageid, title)
  149. def delete_old(self, cursor):
  150. self.logger.debug("Removing old submissions from chart")
  151. query = """DELETE FROM page, row USING page JOIN row
  152. ON page_id = row_id WHERE row_chart IN (4, 5)
  153. AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  154. cursor.execute(query)
  155. def untrack_page(self, cursor, pageid):
  156. self.logger.debug("Untracking page (id: {0})".format(pageid))
  157. query = """DELETE FROM page, row USING page JOIN row
  158. ON page_id = row_id WHERE page_id = ?"""
  159. cursor.execute(query, (pageid,))
  160. def track_page(self, cursor, pageid, title):
  161. """Update hook for when page is not in our database."""
  162. msg = "Tracking page [[{0}]] (id: {1})".format(title, pageid)
  163. self.logger.debug(msg)
  164. page = self.site.get_page(title)
  165. status, chart = self.get_status_and_chart(page)
  166. if not status:
  167. msg = "Could not find a status for [[{0}]]".format(title)
  168. self.logger.warn(msg)
  169. return
  170. title = page.title()
  171. short = self.get_short_title(title)
  172. size = len(page.get())
  173. notes = self.get_notes(page)
  174. c_user, c_time, c_id = self.get_create(pageid)
  175. m_user, m_time, m_id = self.get_modify(pageid)
  176. s_user, s_time, s_id = self.get_special(page, status)
  177. query1 = "INSERT INTO row VALUES ?"
  178. query2 = "INSERT INTO page VALUES ?"
  179. cursor.execute(query1, ((pageid, chart),))
  180. cursor.execute(query2, ((pageid, status, title, short, size, notes,
  181. c_user, c_time, c_id, m_user, m_time, m_id,
  182. s_user, s_time, s_id),))
  183. def update_page(self, cursor, pageid, title):
  184. """Update hook for when page is in our database."""
  185. msg = "Updating page [[{0}]] (id: {1})".format(title, pageid)
  186. self.logger.debug(msg)
  187. page = self.site.get_page(title)
  188. status, chart = self.get_status_and_chart(page)
  189. if not status:
  190. self.untrack_page(cursor, pageid)
  191. if pageid != page.pageid():
  192. msg = "Page [[{0}]] is not what it should be! (id: {0} != {1})"
  193. self.logger.warn(msg.format(pageid, page.pageid()))
  194. self.report_replag()
  195. self.untrack_page(cursor, pageid)
  196. title = page.title()
  197. size = len(page.get())
  198. notes = self.get_notes(page)
  199. m_user, m_time, m_id = self.get_modify(pageid)
  200. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE page_id = ?"
  201. with self.conn.cursor(oursql.DictCursor) as dict_cursor:
  202. dict_cursor.execute(query, (pageid,))
  203. result = dict_cursor.fetchall()[0]
  204. if title != result["page_title"]:
  205. self.update_page_title(cursor, result, pageid, title)
  206. if m_id != result["page_modify_oldid"]:
  207. self.update_page_modify(cursor, result, pageid, size, m_user, m_time, m_id)
  208. if status != result["page_status"]:
  209. self.update_page_special(cursor, result, pageid, status, chart, page)
  210. if notes != result["page_notes"]:
  211. self.update_page_notes(cursor, result, pageid, notes)
  212. def update_page_title(self, cursor, result, pageid, title):
  213. query = "UPDATE page SET page_title = ?, page_short = ? WHERE page_id = ?"
  214. short = self.get_short_title(title)
  215. cursor.execute(query, (title, short, pageid))
  216. msg = "{0}: title: {1} -> {2}"
  217. self.logger.debug(msg.format(pageid, result["page_title"], title))
  218. def update_page_modify(self, cursor, result, pageid, size, m_user, m_time, m_id):
  219. query = """UPDATE page SET page_size = ?, page_modify_user = ?,
  220. page_modify_time = ?, page_modify_oldid = ?
  221. WHERE page_id = ?"""
  222. cursor.execute(query, (size, m_user, m_time, m_id, pageid))
  223. msg = "{0}: modify: {1} / {2} / {3} -> {4} / {5} / {6}"
  224. msg = msg.format(pageid, result["page_modify_user"],
  225. result["page_modify_time"],
  226. result["page_modify_oldid"], m_user, m_time, m_id)
  227. self.logger.debug(msg)
  228. def update_page_special(self, cursor, result, pageid, status, chart, page):
  229. query1 = """UPDATE page JOIN row ON page_id = row_id
  230. SET page_status = ?, row_chart = ? WHERE page_id = ?"""
  231. query2 = """UPDATE page SET page_special_user = ?,
  232. page_special_time = ?, page_special_oldid = ?
  233. WHERE page_id = ?"""
  234. cursor.execute(query1, (status, chart, pageid))
  235. msg = "{0}: status: {1} ({2}) -> {3} ({4})"
  236. self.logger.debug(msg.format(pageid, result["page_status"],
  237. result["row_chart"], status, chart))
  238. s_user, s_time, s_id = self.get_special(page, status)
  239. if s_id != result["page_special_oldid"]:
  240. cursor.execute(query2, (s_user, s_time, s_id, pageid))
  241. msg = "{0}: special: {1} / {2} / {3} -> {4} / {5} / {6}"
  242. msg = msg.format(pageid, result["page_special_user"],
  243. result["page_special_time"],
  244. result["page_special_oldid"], m_user, m_time, m_id)
  245. self.logger.debug(msg)
  246. def update_page_notes(self, cursor, result, pageid, notes):
  247. query = "UPDATE page SET page_notes = ? WHERE page_id = ?"
  248. cursor.execute(query, (notes, pageid))
  249. msg = "{0}: notes: {1} -> {2}"
  250. self.logger.debug(msg.format(pageid, result["page_notes"], notes))
  251. def get_status_and_chart(self, page):
  252. try:
  253. content = page.get()
  254. except wiki.PageNotFoundError:
  255. msg = "Page [[{0}]] does not exist, but the server said it should!"
  256. self.logger.warn(msg.format(page.title()))
  257. return None, 0
  258. if page.is_redirect():
  259. target = page.get_redirect_target()
  260. if self.site.get_page(target).namespace() == 0:
  261. return "accept", 4
  262. return None, 0
  263. elif re.search("\{\{afc submission\|r\|(.*?)\}\}", content, re.I):
  264. return "review", 3
  265. elif re.search("\{\{afc submission\|h\|(.*?)\}\}", content, re.I):
  266. return "pend", 2
  267. elif re.search("\{\{afc submission\|\|(.*?)\}\}", content, re.I):
  268. return "pend", 1
  269. elif re.search("\{\{afc submission\|t\|(.*?)\}\}", content, re.I):
  270. return None, 0
  271. elif re.search("\{\{afc submission\|d\|(.*?)\}\}", content, re.I):
  272. return "decline", 5
  273. return None, 0
  274. def get_short_title(self, title):
  275. short = re.sub("Wikipedia(\s*talk)?\:Articles\sfor\screation\/", "", title)
  276. if len(short) > 50:
  277. short = "".join((short[:47], "..."))
  278. return short
  279. def get_create(self, pageid):
  280. query = """SELECT rev_user_text, rev_timestamp, rev_id
  281. FROM revision WHERE rev_id =
  282. (SELECT MIN(rev_id) FROM revision WHERE rev_page = ?)"""
  283. result = self.site.sql_query(query, (pageid,))
  284. c_user, c_time, c_id = list(result)[0]
  285. return c_user, datetime.strptime(c_time, "%Y%m%d%H%M%S"), c_id
  286. def get_modify(self, pageid):
  287. query = """SELECT rev_user_text, rev_timestamp, rev_id FROM revision
  288. JOIN page ON rev_id = page_latest WHERE page_id = ?"""
  289. result = self.site.sql_query(query, (pageid,))
  290. m_user, m_time, m_id = list(result)[0]
  291. return m_user, datetime.strptime(m_time, "%Y%m%d%H%M%S"), m_id
  292. def get_special(self, page, status):
  293. return None, None, None
  294. def get_notes(self, page):
  295. return None