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.

437 lines
19 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 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. from collections import OrderedDict
  23. from getpass import getpass
  24. from hashlib import sha256
  25. from os import chmod, mkdir, path
  26. import re
  27. import stat
  28. import sys
  29. from textwrap import fill, wrap
  30. try:
  31. from Crypto.Cipher import Blowfish
  32. except ImportError:
  33. Blowfish = None
  34. try:
  35. import bcrypt
  36. except ImportError:
  37. bcrypt = None
  38. try:
  39. import yaml
  40. except ImportError:
  41. yaml = None
  42. from earwigbot import exceptions
  43. from earwigbot.config.ordered_yaml import OrderedDumper
  44. __all__ = ["ConfigScript"]
  45. RULES_TEMPLATE = """# -*- coding: utf-8 -*-
  46. def process(bot, rc):
  47. \"\"\"Given a Bot() object and an RC() object, return a list of channels
  48. to report this event to. Also, start any wiki bot tasks within this
  49. function if necessary.\"\"\"
  50. pass
  51. """
  52. class ConfigScript(object):
  53. """A script to guide a user through the creation of a new config file."""
  54. WIDTH = 79
  55. PROMPT = "\x1b[32m> \x1b[0m"
  56. BCRYPT_ROUNDS = 12
  57. def __init__(self, config):
  58. self.config = config
  59. self.data = OrderedDict([
  60. ("metadata", OrderedDict()),
  61. ("components", OrderedDict()),
  62. ("wiki", OrderedDict()),
  63. ("irc", OrderedDict()),
  64. ("commands", OrderedDict()),
  65. ("tasks", OrderedDict()),
  66. ("schedule", [])
  67. ])
  68. self._cipher = None
  69. self._wmf = False
  70. self._proj = None
  71. self._lang = None
  72. def _print(self, text):
  73. print fill(re.sub("\s\s+", " ", text), self.WIDTH)
  74. def _print_no_nl(self, text):
  75. sys.stdout.write(fill(re.sub("\s\s+", " ", text), self.WIDTH))
  76. sys.stdout.flush()
  77. def _pause(self):
  78. raw_input(self.PROMPT + "Press enter to continue: ")
  79. def _ask(self, text, default=None):
  80. text = self.PROMPT + text
  81. if default:
  82. text += " \x1b[33m[{0}]\x1b[0m".format(default)
  83. lines = wrap(re.sub("\s\s+", " ", text), self.WIDTH)
  84. if len(lines) > 1:
  85. print "\n".join(lines[:-1])
  86. return raw_input(lines[-1] + " ") or default
  87. def _ask_bool(self, text, default=True):
  88. text = self.PROMPT + text
  89. if default:
  90. text += " \x1b[33m[Y/n]\x1b[0m"
  91. else:
  92. text += " \x1b[33m[y/N]\x1b[0m"
  93. lines = wrap(re.sub("\s\s+", " ", text), self.WIDTH)
  94. if len(lines) > 1:
  95. print "\n".join(lines[:-1])
  96. while True:
  97. answer = raw_input(lines[-1] + " ").lower()
  98. if not answer:
  99. return default
  100. if answer.startswith("y"):
  101. return True
  102. if answer.startswith("n"):
  103. return False
  104. def _ask_pass(self, text):
  105. password = getpass(self.PROMPT + text + " ")
  106. if self._cipher:
  107. mod = len(password) % 8
  108. if mod:
  109. password = password.ljust(len(password) + (8 - mod), "\x00")
  110. return self._cipher.encrypt(password).encode("hex")
  111. else:
  112. return password
  113. def _ask_list(self, text):
  114. print fill(re.sub("\s\s+", " ", self.PROMPT + text), self.WIDTH)
  115. print "[one item per line; blank line to end]:"
  116. result = []
  117. while True:
  118. line = raw_input(self.PROMPT)
  119. if line:
  120. result.append(line)
  121. else:
  122. return result
  123. def _set_metadata(self):
  124. print
  125. self.data["metadata"] = OrderedDict([("version", 1)])
  126. self._print("""I can encrypt passwords stored in your config file in
  127. addition to preventing other users on your system from
  128. reading the file. Encryption is recommended is the bot
  129. is to run on a public computer like the Toolserver, but
  130. otherwise the need to enter a key everytime you start
  131. the bot may be annoying.""")
  132. if self._ask_bool("Encrypt stored passwords?"):
  133. self.data["metadata"]["encryptPasswords"] = True
  134. key = getpass(self.PROMPT + "Enter an encryption key: ")
  135. msg = "Running {0} rounds of bcrypt...".format(self.BCRYPT_ROUNDS)
  136. self._print_no_nl(msg)
  137. signature = bcrypt.hashpw(key, bcrypt.gensalt(self.BCRYPT_ROUNDS))
  138. self.data["metadata"]["signature"] = signature
  139. self._cipher = Blowfish.new(sha256(key).digest())
  140. print " done."
  141. else:
  142. self.data["metadata"]["encryptPasswords"] = False
  143. print
  144. self._print("""The bot can temporarily store its logs in the logs/
  145. subdirectory. Error logs are kept for a month whereas
  146. normal logs are kept for a week. If you disable this,
  147. the bot will still print logs to stdout.""")
  148. logging = self._ask_bool("Enable logging?")
  149. self.data["metadata"]["enableLogging"] = logging
  150. def _set_components(self):
  151. print
  152. self._print("""The bot contains three separate components that can run
  153. independently of each other.""")
  154. self._print("""- The IRC front-end runs on a normal IRC server, like
  155. freenode, and expects users to interact with it through
  156. commands.""")
  157. self._print("""- The IRC watcher runs on a wiki recent-changes server,
  158. like irc.wikimedia.org, and listens for edits. Users
  159. cannot interact with this component. It can detect
  160. specific events and report them to "feed" channels on
  161. the front-end, or start bot tasks.""")
  162. self._print("""- The wiki task scheduler runs wiki-editing bot tasks in
  163. separate threads at user-defined times through a
  164. cron-like interface. Tasks which are not scheduled can
  165. be started by the IRC watcher manually through the IRC
  166. front-end.""")
  167. frontend = self._ask_bool("Enable the IRC front-end?")
  168. watcher = self._ask_bool("Enable the IRC watcher?")
  169. scheduler = self._ask_bool("Enable the wiki task scheduler?")
  170. self.data["components"]["irc_frontend"] = frontend
  171. self.data["components"]["irc_watcher"] = watcher
  172. self.data["components"]["wiki_scheduler"] = scheduler
  173. def _login(self, kwargs):
  174. self.config.wiki._load(self.data["wiki"])
  175. self._print_no_nl("Trying to connect to the site...")
  176. try:
  177. site = self.config.bot.wiki.add_site(**kwargs)
  178. except exceptions.APIError as exc:
  179. print " API error!"
  180. print "\x1b[31m" + exc.message + "\x1b[0m"
  181. question = "Would you like to re-enter the site information?"
  182. if self._ask_bool(question):
  183. return self._set_wiki()
  184. question = "This will cancel the setup process. Are you sure?"
  185. if self._ask_bool(question, default=False):
  186. raise exceptions.NoConfigError()
  187. return self._set_wiki()
  188. except exceptions.LoginError as exc:
  189. print " login error!"
  190. print "\x1b[31m" + exc.message + "\x1b[0m"
  191. question = "Would you like to re-enter your login information?"
  192. if self._ask_bool(question):
  193. self.data["wiki"]["username"] = self._ask("Bot username:")
  194. self.data["wiki"]["password"] = self._ask_pass("Bot password:")
  195. return self._login(kwargs)
  196. question = "Would you like to re-enter the site information?"
  197. if self._ask_bool(question):
  198. return self._set_wiki()
  199. self._print("""Moving on. You can modify the login information
  200. stored in the bot's config in the future.""")
  201. password = self.data["wiki"]["password"]
  202. self.data["wiki"]["password"] = None # Clear so we don't login
  203. self.config.wiki._load(self.data["wiki"])
  204. self._print_no_nl("Trying to connect to the site...")
  205. site = self.config.bot.wiki.add_site(**kwargs)
  206. print " success."
  207. self.data["wiki"]["password"] = password # Reset original value
  208. else:
  209. print " success."
  210. return site
  211. def _set_wiki(self):
  212. print
  213. self._wmf = self._ask_bool("""Will this bot run on Wikimedia Foundation
  214. wikis, like Wikipedia?""")
  215. if self._wmf:
  216. msg = "Site project (e.g. 'wikipedia', 'wiktionary', 'wikimedia'):"
  217. self._proj = project = self._ask(msg, default="wikipedia").lower()
  218. msg = "Site language code (e.g. 'en', 'fr', 'commons'):"
  219. self._lang = lang = self._ask(msg, default="en").lower()
  220. kwargs = {"project": project, "lang": lang}
  221. else:
  222. msg = "Site base URL, without the script path and trailing slash;"
  223. msg += " can be protocol-insensitive (e.g. '//en.wikipedia.org'):"
  224. url = self._ask(msg)
  225. script = self._ask("Site script path:", default="/w")
  226. kwargs = {"base_url": url, "script_path": script}
  227. self.data["wiki"]["username"] = self._ask("Bot username:")
  228. self.data["wiki"]["password"] = self._ask_pass("Bot password:")
  229. self.data["wiki"]["userAgent"] = "EarwigBot/$1 (Python/$2; https://github.com/earwig/earwigbot)"
  230. self.data["wiki"]["summary"] = "([[WP:BOT|Bot]]): $2"
  231. self.data["wiki"]["useHTTPS"] = True
  232. self.data["wiki"]["assert"] = "user"
  233. self.data["wiki"]["maxlag"] = 10
  234. self.data["wiki"]["waitTime"] = 3
  235. self.data["wiki"]["defaultSite"] = self._login(kwargs).name
  236. self.data["wiki"]["sql"] = {}
  237. if self._wmf:
  238. msg = "Will this bot run from the Wikimedia Toolserver?"
  239. toolserver = self._ask_bool(msg, default=False)
  240. if toolserver:
  241. args = [("host", "$1-p.rrdb.toolserver.org"), ("db", "$1_p")]
  242. self.data["wiki"]["sql"] = OrderedDict(args)
  243. self.data["wiki"]["shutoff"] = {}
  244. msg = "Would you like to enable an automatic shutoff page for the bot?"
  245. if self._ask_bool(msg):
  246. print
  247. self._print("""The page title can contain two wildcards: $1 will be
  248. substituted with the bot's username, and $2 with the
  249. current task number. This can be used to implement a
  250. separate shutoff page for each task.""")
  251. page = self._ask("Page title:", default="User:$1/Shutoff")
  252. disabled = self._ask("Page content when *not* shut off:", "run")
  253. args = [("page", page), ("disabled", disabled)]
  254. self.data["wiki"]["shutoff"] = OrderedDict(args)
  255. self.data["wiki"]["search"] = {}
  256. def _set_irc(self):
  257. if self.data["components"]["irc_frontend"]:
  258. print
  259. frontend = self.data["irc"]["frontend"] = OrderedDict()
  260. msg = "Hostname of the frontend's IRC server, without 'irc://':"
  261. frontend["host"] = self._ask(msg, "irc.freenode.net")
  262. frontend["port"] = self._ask("Frontend port:", 6667)
  263. frontend["nick"] = self._ask("Frontend bot's nickname:")
  264. frontend["ident"] = self._ask("Frontend bot's ident:",
  265. frontend["nick"].lower())
  266. question = "Frontend bot's real name (gecos):"
  267. frontend["realname"] = self._ask(question)
  268. if self._ask_bool("Should the bot identify to NickServ?"):
  269. ns_user = self._ask("NickServ username:", frontend["nick"])
  270. ns_pass = self._ask_pass("Nickserv password:")
  271. frontend["nickservUsername"] = ns_user
  272. frontend["nickservPassword"] = ns_pass
  273. chan_question = "Frontend channels to join by default:"
  274. frontend["channels"] = self._ask_list(chan_question)
  275. print
  276. self._print("""The bot keeps a database of its admins (users who
  277. can use certain sensitive commands) and owners
  278. (users who can quit the bot and modify its access
  279. list), identified by nick, ident, and/or hostname.
  280. Hostname is most secure since it cannot be easily
  281. spoofed. If you have a cloak, it will probably look
  282. like 'wikipedia/Username' or
  283. 'unaffiliated/nickname'.""")
  284. host = self._ask("Your hostname on the IRC frontend:")
  285. if host:
  286. permdb = self.config._permissions
  287. permdb.load()
  288. permdb.add_owner(host=host)
  289. permdb.add_admin(host=host)
  290. else:
  291. frontend = {}
  292. if self.data["components"]["irc_watcher"]:
  293. print
  294. watcher = self.data["irc"]["watcher"] = OrderedDict()
  295. if self._wmf:
  296. watcher["host"] = "irc.wikimedia.org"
  297. watcher["port"] = 6667
  298. else:
  299. msg = "Hostname of the watcher's IRC server, without 'irc://':"
  300. watcher["host"] = self._ask(msg)
  301. watcher["port"] = self._ask("Watcher port:", 6667)
  302. nick = self._ask("Watcher bot's nickname:", frontend.get("nick"))
  303. ident = self._ask("Watcher bot's ident:", watcher["nick"].lower())
  304. watcher["nick"] = nick
  305. watcher["ident"] = ident
  306. question = "Watcher bot's real name (gecos):"
  307. watcher["realname"] = self._ask(question, frontend.get("realname"))
  308. watcher_ns = "Should the bot identify to NickServ?"
  309. if not self._wmf and self._ask_bool(watcher_ns):
  310. ns_user = self._ask("NickServ username:", watcher["nick"])
  311. ns_pass = self._ask_pass("Nickserv password:")
  312. watcher["nickservUsername"] = ns_user
  313. watcher["nickservPassword"] = ns_pass
  314. if self._wmf:
  315. chan = "#{0}.{1}".format(self._lang, self._proj)
  316. watcher["channels"] = [chan]
  317. else:
  318. chan_question = "Watcher channels to join by default:"
  319. watcher["channels"] = self._ask_list(chan_question)
  320. print
  321. self._print("""I am now creating a blank 'rules.py' file, which
  322. will determine how the bot handles messages received
  323. from the IRC watcher. It contains a process()
  324. function that takes a Bot object allowing you to
  325. start tasks and an RC object that holds the message
  326. from the watcher. See the documentation for
  327. details.""")
  328. with open(path.join(self.config.root_dir, "rules.py"), "w") as fp:
  329. fp.write(RULES_TEMPLATE)
  330. self._pause()
  331. self.data["irc"]["version"] = "EarwigBot - $1 - Python/$2 https://github.com/earwig/earwigbot"
  332. def _set_commands(self):
  333. print
  334. msg = """Would you like to disable the default IRC commands? You can
  335. fine-tune which commands are disabled later on."""
  336. if (not self.data["components"]["irc_frontend"] or
  337. self._ask_bool(msg, default=False)):
  338. self.data["commands"]["disable"] = True
  339. self._print("""I am now creating the 'commands/' directory, where you
  340. can place custom IRC commands and plugins. Creating your
  341. own commands is described in the documentation.""")
  342. mkdir(path.join(self.config.root_dir, "commands"))
  343. self._pause()
  344. def _set_tasks(self):
  345. print
  346. self._print("""I am now creating the 'tasks/' directory, where you can
  347. place custom bot tasks and plugins. Creating your own
  348. tasks is described in the documentation.""")
  349. mkdir(path.join(self.config.root_dir, "tasks"))
  350. self._pause()
  351. def _set_schedule(self):
  352. self._print("""The final section of your config file, 'schedule', is a
  353. list of bot tasks to be started by the wiki scheduler.
  354. Each entry contains cron-like time quantifiers and a
  355. list of tasks. For example, the following starts the
  356. 'foobot' task every hour on the half-hour:""")
  357. print "schedule:"
  358. print " - minute: 30"
  359. print " tasks:"
  360. print " - foobot"
  361. self._print("""The following starts the 'barbot' task with the keyword
  362. arguments 'action="baz"' every Monday at 05:00 UTC:""")
  363. print " - week_day: 1"
  364. print " hour: 5"
  365. print " tasks:"
  366. print ' - ["barbot", {"action": "baz"}]'
  367. self._print("""The full list of quantifiers is minute, hour, month_day,
  368. month, and week_day. See the documentation for more
  369. details.""")
  370. self._pause()
  371. def _save(self):
  372. with open(self.config.path, "w") as strm:
  373. yaml.dump(self.data, strm, OrderedDumper, default_flow_style=False)
  374. def make_new(self):
  375. """Make a new config file based on the user's input."""
  376. try:
  377. open(self.config.path, "w").close()
  378. chmod(self.config.path, stat.S_IRUSR|stat.S_IWUSR)
  379. except IOError:
  380. print "I can't seem to write to the config file:"
  381. raise
  382. self._set_metadata()
  383. self._set_components()
  384. self._set_wiki()
  385. components = self.data["components"]
  386. if components["irc_frontend"] or components["irc_watcher"]:
  387. self._set_irc()
  388. self._set_commands()
  389. self._set_tasks()
  390. if components["wiki_scheduler"]:
  391. self._set_schedule()
  392. print
  393. self._print("""I am now saving config.yml with your settings. YAML is a
  394. relatively straightforward format and you should be able
  395. to update these settings in the future when necessary.
  396. I will start the bot at your signal. Feel free to
  397. contact me at wikipedia.earwig@gmail.com if you have any
  398. questions.""")
  399. self._save()
  400. if not self._ask_bool("Start the bot now?"):
  401. exit()