A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

168 lines
6.5 KiB

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