A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

169 righe
6.6 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by Ben Kurtovic <ben.kurtovic@verizon.net>
  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. import threading
  23. import re
  24. from earwigbot.commands import BaseCommand
  25. from earwigbot.config import config
  26. from earwigbot.irc import KwargParseException
  27. from earwigbot.tasks import task_manager
  28. class Command(BaseCommand):
  29. """Manage wiki tasks from IRC, and check on thread status."""
  30. name = "threads"
  31. def check(self, data):
  32. commands = ["tasks", "task", "threads", "tasklist"]
  33. if data.is_command and data.command in commands:
  34. return True
  35. return False
  36. def process(self, data):
  37. self.data = data
  38. if data.host not in config.irc["permissions"]["owners"]:
  39. msg = "you must be a bot owner to use this command."
  40. self.connection.reply(data, msg)
  41. return
  42. if not data.args:
  43. if data.command == "tasklist":
  44. self.do_list()
  45. else:
  46. msg = "no arguments provided. Maybe you wanted '!{0} list', '!{0} start', or '!{0} listall'?"
  47. self.connection.reply(data, msg.format(data.command))
  48. return
  49. if data.args[0] == "list":
  50. self.do_list()
  51. elif data.args[0] == "start":
  52. self.do_start()
  53. elif data.args[0] in ["listall", "all"]:
  54. self.do_listall()
  55. else: # They asked us to do something we don't know
  56. msg = "unknown argument: \x0303{0}\x0301.".format(data.args[0])
  57. self.connection.reply(data, msg)
  58. def do_list(self):
  59. """With !tasks list (or abbreviation !tasklist), list all running
  60. threads. This includes the main threads, like the irc frontend and the
  61. watcher, and task threads."""
  62. threads = threading.enumerate()
  63. normal_threads = []
  64. task_threads = []
  65. for thread in threads:
  66. tname = thread.name
  67. if tname == "MainThread":
  68. tname = self.get_main_thread_name()
  69. t = "\x0302{0}\x0301 (as main thread, id {1})"
  70. normal_threads.append(t.format(tname, thread.ident))
  71. elif tname in ["irc-frontend", "irc-watcher", "wiki-scheduler"]:
  72. t = "\x0302{0}\x0301 (id {1})"
  73. normal_threads.append(t.format(tname, thread.ident))
  74. elif tname.startswith("reminder"):
  75. tname = tname.replace("reminder ", "")
  76. t = "\x0302reminder\x0301 (until {0})"
  77. normal_threads.append(t.format(tname))
  78. else:
  79. tname, start_time = re.findall("^(.*?) \((.*?)\)$", tname)[0]
  80. t = "\x0302{0}\x0301 (id {1}, since {2})"
  81. task_threads.append(t.format(tname, thread.ident, start_time))
  82. if task_threads:
  83. msg = "\x02{0}\x0F threads active: {1}, and \x02{2}\x0F task threads: {3}."
  84. msg = msg.format(len(threads), ', '.join(normal_threads),
  85. len(task_threads), ', '.join(task_threads))
  86. else:
  87. msg = "\x02{0}\x0F threads active: {1}, and \x020\x0F task threads."
  88. msg = msg.format(len(threads), ', '.join(normal_threads))
  89. self.connection.reply(self.data, msg)
  90. def do_listall(self):
  91. """With !tasks listall or !tasks all, list all loaded tasks, and report
  92. whether they are currently running or idle."""
  93. all_tasks = task_manager.get_all().keys()
  94. threads = threading.enumerate()
  95. tasklist = []
  96. all_tasks.sort()
  97. for task in all_tasks:
  98. threadlist = [t for t in threads if t.name.startswith(task)]
  99. ids = [str(t.ident) for t in threadlist]
  100. if not ids:
  101. tasklist.append("\x0302{0}\x0301 (idle)".format(task))
  102. elif len(ids) == 1:
  103. t = "\x0302{0}\x0301 (\x02active\x0F as id {1})"
  104. tasklist.append(t.format(task, ids[0]))
  105. else:
  106. t = "\x0302{0}\x0301 (\x02active\x0F as ids {1})"
  107. tasklist.append(t.format(task, ', '.join(ids)))
  108. tasklist = ", ".join(tasklist)
  109. msg = "{0} tasks loaded: {1}.".format(len(all_tasks), tasklist)
  110. self.connection.reply(self.data, msg)
  111. def do_start(self):
  112. """With !tasks start, start any loaded task by name with or without
  113. kwargs."""
  114. data = self.data
  115. try:
  116. task_name = data.args[1]
  117. except IndexError: # No task name given
  118. self.connection.reply(data, "what task do you want me to start?")
  119. return
  120. try:
  121. data.parse_kwargs()
  122. except KwargParseException, arg:
  123. msg = "error parsing argument: \x0303{0}\x0301.".format(arg)
  124. self.connection.reply(data, msg)
  125. return
  126. if task_name not in task_manager.get_all().keys():
  127. # This task does not exist or hasn't been loaded:
  128. msg = "task could not be found; either tasks/{0}.py doesn't exist, or it wasn't loaded correctly."
  129. self.connection.reply(data, msg.format(task_name))
  130. return
  131. data.kwargs["fromIRC"] = True
  132. task_manager.start(task_name, **data.kwargs)
  133. msg = "task \x0302{0}\x0301 started.".format(task_name)
  134. self.connection.reply(data, msg)
  135. def get_main_thread_name(self):
  136. """Return the "proper" name of the MainThread."""
  137. if "irc_frontend" in config.components:
  138. return "irc-frontend"
  139. elif "wiki_schedule" in config.components:
  140. return "wiki-scheduler"
  141. else:
  142. return "irc-watcher"