A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

163 rindas
5.6 KiB

  1. # -*- coding: utf-8 -*-
  2. import re
  3. from os.path import expanduser
  4. from threading import Lock
  5. import oursql
  6. from classes import BaseTask
  7. import config
  8. import wiki
  9. class Task(BaseTask):
  10. """A task to generate statistics for WikiProject Articles for Creation.
  11. Statistics are stored in a MySQL database ("u_earwig_afc_statistics")
  12. accessed with oursql. Statistics are updated live while watching the recent
  13. changes IRC feed and saved once an hour, on the hour, to self.pagename.
  14. In the live bot, this is "Template:AFC statistics".
  15. """
  16. name = "afc_statistics"
  17. number = 2
  18. def __init__(self):
  19. self.cfg = cfg = config.tasks.get(self.name, {})
  20. # Set some wiki-related attributes:
  21. self.pagename = cfg.get("page", "Template:AFC statistics")
  22. default_summary = "Updating statistics for [[WP:WPAFC|WikiProject Articles for creation]]."
  23. self.summary = self.make_summary(cfg.get("summary", default_summary))
  24. # Templates used in chart generation:
  25. templates = cfg.get("templates", {})
  26. self.tl_header = templates.get("header", "AFC statistics/header")
  27. self.tl_row = templates.get("row", "AFC statistics/row")
  28. self.tl_footer = templates.get("footer", "AFC statistics/footer")
  29. # Establish a connection with our SQL database:
  30. kwargs = cfg.get("sql", {})
  31. kwargs["read_default_file"] = expanduser("~/.my.cnf")
  32. self.conn = oursql.connect(**kwargs)
  33. self.db_access_lock = Lock()
  34. def run(self, **kwargs):
  35. self.site = wiki.get_site()
  36. action = kwargs.get("action")
  37. if not action:
  38. return
  39. methods = {
  40. "save": self.save,
  41. "sync", self.sync,
  42. "edit": self.process_edit,
  43. "move": self.process_move,
  44. "delete": self.process_delete,
  45. "restore": self.process_restore,
  46. }
  47. method = methods.get(action)
  48. if method:
  49. method(**kwargs)
  50. def save(self, **kwargs):
  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. return # Don't edit the page if we're not adding anything
  65. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  66. "\\1~~~ at ~~~~~\\3", newtext)
  67. page.edit(newtext, summary, minor=True, bot=True)
  68. def compile_charts(self):
  69. stats = ""
  70. with self.conn.cursor() as cursor, self.db_access_lock:
  71. cursor.execute("SELECT * FROM chart")
  72. for chart in cursor:
  73. stats += self.compile_chart(chart) + "\n"
  74. return stats[:-1] # Drop the last newline
  75. def compile_chart(self, chart_info):
  76. chart_id, chart_title, special_title = chart_info
  77. chart = "|".join((self.tl_header, chart_title))
  78. if special_title:
  79. chart += "".join(("|", special_title))
  80. chart = "".join(("{{", chart, "}}"))
  81. query = "SELECT * FROM page JOIN row ON page_id = row_id WHERE row_chart = ?"
  82. with self.conn.cursor(oursql.DictCursor) as cursor:
  83. cursor.execute(query, (chart_id,))
  84. for page in cursor:
  85. chart += "\n" + self.compile_chart_row(page)
  86. chart += "".join(("\n{{", self.tl_footer, "}}"))
  87. return chart
  88. def compile_chart_row(self, page):
  89. row = "{0}|s={page_status}|t={page_title}|h={page_short}|z={page_size}|"
  90. row += "cr={page_create_user}|cd={page_create_time}|ci={page_create_oldid}|"
  91. row += "mr={page_modify_user}|md={page_modify_time}|mi={page_modify_oldid}|"
  92. page["page_create_time"] = self.format_time(page["page_create_time"])
  93. page["page_modify_time"] = self.format_time(page["page_modify_time"])
  94. if page["page_special_user"]:
  95. row += "sr={page_special_user}|sd={page_special_time}|si={page_special_oldid}|"
  96. page["page_special_time"] = self.format_time(page["page_special_time"])
  97. if page["page_notes"]:
  98. row += "n=1{page_notes}"
  99. return "".join(("{{", row.format(self.tl_row, **page), "}}"))
  100. def format_time(self, timestamp):
  101. return timestamp.strftime("%H:%M, %d %B %Y")
  102. def sync(self, **kwargs):
  103. with self.conn.cursor() as cursor, self.db_access_lock:
  104. self.sync_deleted(cursor) # Remove deleted subs
  105. self.sync_oldids(cursor) # Make sure all subs are up to date
  106. self.sync_pending(cursor) # Add missed pending subs
  107. self.sync_old(cursor) # Remove old declined and accepted subs
  108. def sync_deleted(self, cursor):
  109. pass
  110. def sync_oldids(self, cursor):
  111. pass
  112. def sync_pending(self, cursor):
  113. pass
  114. def sync_old(self, cursor):
  115. query = """DELETE FROM page, row USING page JOIN row ON page_id = row_id
  116. WHERE row_chart IN (4, 5) AND ADDTIME(page_special_time, '36:00:00') < NOW()"""
  117. cursor.execute(query)
  118. def process_edit(self, page, **kwargs):
  119. pass
  120. def process_move(self, page, **kwargs):
  121. pass
  122. def process_delete(self, page, **kwargs):
  123. pass
  124. def process_restore(self, page, **kwargs):
  125. pass