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.

324 linhas
12 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  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 ast import literal_eval
  23. import re
  24. from earwigbot.commands import Command
  25. from earwigbot.irc import RC
  26. class Stalk(Command):
  27. """Stalk a particular user (!stalk/!unstalk) or page (!watch/!unwatch) for
  28. edits. Prefix regular expressions with "re:" (uses re.match)."""
  29. name = "stalk"
  30. commands = ["stalk", "watch", "unstalk", "unwatch", "stalks", "watches",
  31. "allstalks", "allwatches", "unstalkall", "unwatchall"]
  32. hooks = ["msg", "rc"]
  33. MAX_STALKS_PER_USER = 10
  34. def setup(self):
  35. self._users = {}
  36. self._pages = {}
  37. self._load_stalks()
  38. def check(self, data):
  39. if isinstance(data, RC):
  40. return True
  41. if data.is_command and data.command in self.commands:
  42. return True
  43. return False
  44. def process(self, data):
  45. if isinstance(data, RC):
  46. return self._process_rc(data)
  47. data.is_admin = self.config.irc["permissions"].is_admin(data)
  48. if data.command.startswith("all"):
  49. if data.is_admin:
  50. self.reply(data, self._all_stalks())
  51. else:
  52. self.reply(data, "You must be a bot admin to view all stalked "
  53. "users or watched pages. View your own with "
  54. "\x0306!stalks\x0F.")
  55. return
  56. if data.command.endswith("all"):
  57. if not data.is_admin:
  58. self.reply(data, "You must be a bot admin to unstalk a user "
  59. "or unwatch a page for all users.")
  60. return
  61. if not data.args:
  62. self.reply(data, "You must give a user to unstalk or a page "
  63. "to unwatch. View all active with "
  64. "\x0306!allstalks\x0F.")
  65. return
  66. if not data.args or data.command in ["stalks", "watches"]:
  67. self.reply(data, self._current_stalks(data.nick))
  68. return
  69. target = " ".join(data.args).replace("_", " ")
  70. if target.startswith("[[") and target.endswith("]]"):
  71. target = target[2:-2]
  72. if target.startswith("re:"):
  73. target = "re:" + target[3:].lstrip()
  74. else:
  75. if target.startswith("User:") and "stalk" in data.command:
  76. target = target[5:]
  77. target = target[0].upper() + target[1:]
  78. if data.command in ["stalk", "watch"]:
  79. if data.is_private:
  80. stalkinfo = (data.nick, None)
  81. elif not data.is_admin:
  82. self.reply(data, "You must be a bot admin to stalk users or "
  83. "watch pages publicly. Retry this command in "
  84. "a private message.")
  85. return
  86. else:
  87. stalkinfo = (data.nick, data.chan)
  88. if data.command == "stalk":
  89. self._add_stalk("user", data, target, stalkinfo)
  90. elif data.command == "watch":
  91. self._add_stalk("page", data, target, stalkinfo)
  92. elif data.command == "unstalk":
  93. self._remove_stalk("user", data, target)
  94. elif data.command == "unwatch":
  95. self._remove_stalk("page", data, target)
  96. elif data.command == "unstalkall":
  97. self._remove_all_stalks("user", data, target)
  98. elif data.command == "unwatchall":
  99. self._remove_all_stalks("page", data, target)
  100. def _process_rc(self, rc):
  101. """Process a watcher event."""
  102. def _update_chans(items):
  103. for item in items:
  104. if item[1]:
  105. if item[1] in chans:
  106. chans[item[1]].add(item[0])
  107. else:
  108. chans[item[1]] = {item[0]}
  109. else:
  110. chans[item[0]] = None
  111. def _regex_match(target, tag):
  112. return target.startswith("re:") and re.match(target[3:], tag)
  113. def _process(table, tag):
  114. for target, stalks in table.iteritems():
  115. if target == tag or _regex_match(target, tag):
  116. _update_chans(stalks)
  117. chans = {}
  118. _process(self._users, rc.user)
  119. if rc.is_edit:
  120. _process(self._pages, rc.page)
  121. if not chans:
  122. return
  123. with self.bot.component_lock:
  124. frontend = self.bot.frontend
  125. if frontend and not frontend.is_stopped():
  126. pretty = rc.prettify()
  127. for chan in chans:
  128. if chans[chan]:
  129. nicks = ", ".join(sorted(chans[chan]))
  130. msg = "\x02{0}\x0F: {1}".format(nicks, pretty)
  131. else:
  132. msg = pretty
  133. if len(msg) > 400:
  134. msg = msg[:397] + "..."
  135. frontend.say(chan, msg)
  136. @staticmethod
  137. def _get_stalks_by_nick(nick, table):
  138. """Return a dictionary of stalklist entries by the given nick."""
  139. entries = {}
  140. for target, stalks in table.iteritems():
  141. for info in stalks:
  142. if info[0] == nick:
  143. if target in entries:
  144. entries[target].append(info[1])
  145. else:
  146. entries[target] = [info[1]]
  147. return entries
  148. def _add_stalk(self, stalktype, data, target, stalkinfo):
  149. """Add a stalk entry to the given table."""
  150. if stalktype == "user":
  151. table = self._users
  152. verb = "stalk"
  153. else:
  154. table = self._pages
  155. verb = "watch"
  156. if not data.is_admin:
  157. nstalks = len(self._get_stalks_by_nick(data.nick, table))
  158. if nstalks >= self.MAX_STALKS_PER_USER:
  159. msg = ("Already {0}ing {1} {2}s for you, which is the limit "
  160. "for non-bot admins.")
  161. self.reply(data, msg.format(verb, nstalks, stalktype))
  162. return
  163. if target in table:
  164. if stalkinfo in table[target]:
  165. msg = "Already {0}ing that {1} in here for you."
  166. self.reply(data, msg.format(verb, stalktype))
  167. return
  168. else:
  169. table[target].append(stalkinfo)
  170. else:
  171. table[target] = [stalkinfo]
  172. msg = "Now {0}ing {1} \x0302{2}\x0F. Remove with \x0306!un{0} {2}\x0F."
  173. self.reply(data, msg.format(verb, stalktype, target))
  174. self._save_stalks()
  175. def _remove_stalk(self, stalktype, data, target):
  176. """Remove a stalk entry from the given table."""
  177. if stalktype == "user":
  178. table = self._users
  179. verb = "stalk"
  180. plural = "stalks"
  181. else:
  182. table = self._pages
  183. verb = "watch"
  184. plural = "watches"
  185. to_remove = []
  186. if target in table:
  187. for info in table[target]:
  188. if info[0] == data.nick:
  189. to_remove.append(info)
  190. if not to_remove:
  191. msg = ("I haven't been {0}ing that {1} for you in the first "
  192. "place. View your active {2} with \x0306!{2}\x0F.")
  193. if data.is_admin:
  194. msg += (" As a bot admin, you can clear all active {2} on "
  195. "that {1} with \x0306!un{0}all {3}\x0F.")
  196. self.reply(data, msg.format(verb, stalktype, plural, target))
  197. return
  198. for info in to_remove:
  199. table[target].remove(info)
  200. if not table[target]:
  201. del table[target]
  202. msg = "No longer {0}ing {1} \x0302{2}\x0F for you."
  203. self.reply(data, msg.format(verb, stalktype, target))
  204. self._save_stalks()
  205. def _remove_all_stalks(self, stalktype, data, target):
  206. """Remove all entries for a particular target from the given table."""
  207. if stalktype == "user":
  208. table = self._users
  209. verb = "stalk"
  210. plural = "stalks"
  211. else:
  212. table = self._pages
  213. verb = "watch"
  214. plural = "watches"
  215. try:
  216. del table[target]
  217. except KeyError:
  218. msg = ("I haven't been {0}ing that {1} for anyone in the first "
  219. "place. View all active {2} with \x0306!all{2}\x0F.")
  220. self.reply(data, msg.format(verb, stalktype, plural))
  221. else:
  222. msg = "No longer {0}ing {1} \x0302{2}\x0F for anyone."
  223. self.reply(data, msg.format(verb, stalktype, target))
  224. self._save_stalks()
  225. def _current_stalks(self, nick):
  226. """Return the given user's current stalks."""
  227. def _format_chans(chans):
  228. if None in chans:
  229. chans.remove(None)
  230. if not chans:
  231. return "privately"
  232. if len(chans) == 1:
  233. return "in {0} and privately".format(chans[0])
  234. return "in " + ", ".join(chans) + ", and privately"
  235. return "in " + ", ".join(chans)
  236. def _format_stalks(stalks):
  237. return ", ".join(
  238. "\x0302{0}\x0F ({1})".format(target, _format_chans(chans))
  239. for target, chans in stalks.iteritems())
  240. users = self._get_stalks_by_nick(nick, self._users)
  241. pages = self._get_stalks_by_nick(nick, self._pages)
  242. if users:
  243. uinfo = " Users: {0}.".format(_format_stalks(users))
  244. if pages:
  245. pinfo = " Pages: {0}.".format(_format_stalks(pages))
  246. msg = "Currently stalking {0} user{1} and watching {2} page{3} for you.{4}{5}"
  247. return msg.format(len(users), "s" if len(users) != 1 else "",
  248. len(pages), "s" if len(pages) != 1 else "",
  249. uinfo if users else "", pinfo if pages else "")
  250. def _all_stalks(self):
  251. """Return all existing stalks, for bot admins."""
  252. def _format_info(info):
  253. if info[1]:
  254. return "for {0} in {1}".format(info[0], info[1])
  255. return "for {0} privately".format(info[0])
  256. def _format_data(data):
  257. return ", ".join(_format_info(info) for info in data)
  258. def _format_stalks(stalks):
  259. return ", ".join(
  260. "\x0302{0}\x0F ({1})".format(target, _format_data(data))
  261. for target, data in stalks.iteritems())
  262. users, pages = self._users, self._pages
  263. if users:
  264. uinfo = " Users: {0}.".format(_format_stalks(users))
  265. if pages:
  266. pinfo = " Pages: {0}.".format(_format_stalks(pages))
  267. msg = "Currently stalking {0} user{1} and watching {2} page{3}.{4}{5}"
  268. return msg.format(len(users), "s" if len(users) != 1 else "",
  269. len(pages), "s" if len(pages) != 1 else "",
  270. uinfo if users else "", pinfo if pages else "")
  271. def _load_stalks(self):
  272. """Load saved stalks from the database."""
  273. permdb = self.config.irc["permissions"]
  274. try:
  275. data = permdb.get_attr("command:stalk", "data")
  276. except KeyError:
  277. return
  278. self._users, self._pages = literal_eval(data)
  279. def _save_stalks(self):
  280. """Save stalks to the database."""
  281. permdb = self.config.irc["permissions"]
  282. data = str((self._users, self._pages))
  283. permdb.set_attr("command:stalk", "data", data)