A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Não pode escolher mais do que 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.

146 linhas
4.8 KiB

  1. # -*- coding: utf-8 -*-
  2. import re
  3. from os.path import expanduser
  4. from time import strftime, strptime
  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. def run(self, **kwargs):
  34. self.site = wiki.get_site()
  35. action = kwargs.get("action")
  36. if not action:
  37. return
  38. if action == "save":
  39. self.save()
  40. return
  41. page = kwargs.get("page")
  42. if page:
  43. methods = {
  44. "edit": self.process_edit,
  45. "move": self.process_move,
  46. "delete": self.process_delete,
  47. "restore": self.process_restore,
  48. }
  49. method = methods.get(action)
  50. if method:
  51. method(page)
  52. def save(self):
  53. self.check_integrity()
  54. if self.shutoff_enabled():
  55. return
  56. statistics = self.compile_charts()
  57. page = self.site.get_page(self.pagename)
  58. text = page.get()
  59. newtext = re.sub("(<!-- stat begin -->)(.*?)(<!-- stat end -->)",
  60. statistics.join(("\\1", "\\3")), text,
  61. flags=re.DOTALL)
  62. if newtext == text:
  63. return # Don't edit the page if we're not adding anything
  64. newtext = re.sub("(<!-- sig begin -->)(.*?)(<!-- sig end -->)",
  65. "\\1~~~ at ~~~~~\\3", newtext)
  66. page.edit(newtext, self.summary, minor=True, bot=True)
  67. def compile_charts(self):
  68. stats = ""
  69. with self.conn.cursor() as cursor:
  70. cursor.execute("SELECT * FROM chart")
  71. charts = cursor.fetchall()
  72. for chart_info in charts:
  73. stats += self.compile_chart(chart_info) + "\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. if special_title:
  78. chart = "{{{0}|{1}|{2}}}".format(self.tl_header, chart_title, special_title)
  79. else:
  80. chart = "{{{0}|{1}}}".format(self.tl_header, chart_title)
  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 += "\n{{{0}}}".format(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"] = format_timestamp(page["page_create_time"])
  93. page["page_modify_time"] = format_timestamp(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"] = format_timestamp(page["page_special_time"])
  97. if page["page_notes"]:
  98. row += "n=1{page_notes}"
  99. row += "}}"
  100. return row.format(self.tl_row, **page)
  101. def format_timestamp(self, ts):
  102. return strftime("%H:%M, %d %B %Y", strptime(ts, "%Y-%m-%d %H:%M:%S"))
  103. def check_integrity(self):
  104. pass
  105. def process_edit(self, page):
  106. pass
  107. def process_move(self, page):
  108. pass
  109. def process_delete(self, page):
  110. pass
  111. def process_restore(self, page):
  112. pass