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.

239 lines
8.3 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. import re
  23. __all__ = ["Data"]
  24. class Data(object):
  25. """Store data from an individual line received on IRC."""
  26. def __init__(self, my_nick, line, msgtype):
  27. self._my_nick = my_nick.lower()
  28. self._line = line
  29. self._msgtype = msgtype
  30. self._is_private = self._is_command = False
  31. self._msg = self._command = self._trigger = None
  32. self._args = []
  33. self._kwargs = {}
  34. self._parse()
  35. def __repr__(self):
  36. """Return the canonical string representation of the Data."""
  37. res = "Data(my_nick={0!r}, line={1!r})"
  38. return res.format(self.my_nick, self.line)
  39. def __str__(self):
  40. """Return a nice string representation of the Data."""
  41. return "<Data of {0!r}>".format(" ".join(self.line))
  42. def _parse(self):
  43. """Parse a line from IRC into its components as instance attributes."""
  44. sender = re.findall(r":(.*?)!(.*?)@(.*?)\Z", self.line[0])[0]
  45. self._nick, self._ident, self._host = sender
  46. self._reply_nick = self._nick
  47. self._chan = self.line[2]
  48. if self._msgtype in ["PRIVMSG", "NOTICE"]:
  49. if self.chan.lower() == self.my_nick:
  50. # This is a privmsg to us, so set 'chan' as the nick of the
  51. # sender instead of the 'channel', which is ourselves:
  52. self._chan = self._nick
  53. self._is_private = True
  54. self._msg = " ".join(self.line[3:])[1:]
  55. if self._msgtype == "PRIVMSG":
  56. self._parse_args()
  57. self._parse_kwargs()
  58. def _parse_args(self):
  59. """Parse command arguments from the message.
  60. self.msg is converted into the string self.command and the argument
  61. list self.args if the message starts with a "trigger" ("!", ".", or the
  62. bot's name); self.is_command will be set to True, and self.trigger will
  63. store the trigger string. Otherwise, is_command will be set to False.
  64. """
  65. self._args = self.msg.strip().split()
  66. try:
  67. command_uc = self.args.pop(0)
  68. self._command = command_uc.lower()
  69. except IndexError:
  70. return
  71. # e.g. "!command>user arg1 arg2"
  72. if ">" in self.command:
  73. command_uc, self._reply_nick = command_uc.split(">", 1)
  74. self._command = command_uc.lower()
  75. if self.command.startswith("!") or self.command.startswith("."):
  76. # e.g. "!command arg1 arg2"
  77. self._is_command = True
  78. self._trigger = self.command[0]
  79. self._command = self.command[1:] # Strip the "!" or "."
  80. elif re.match(r"{0}\W*?$".format(re.escape(self.my_nick)),
  81. self.command, re.U):
  82. # e.g. "EarwigBot, command arg1 arg2"
  83. self._is_command = True
  84. self._trigger = self.my_nick
  85. try:
  86. self._command = self.args.pop(0).lower()
  87. except IndexError:
  88. self._command = ""
  89. else:
  90. try:
  91. if self.msg[-1] == "." and self.msg[-2] != ".":
  92. if self.args:
  93. self.args[-1] = self.args[-1][:-1]
  94. else:
  95. self._command = self.command[:-1]
  96. except IndexError:
  97. pass
  98. # e.g. "!command >user arg1 arg2"
  99. if self.args and self.args[0].startswith(">"):
  100. self._reply_nick = self.args.pop(0)[1:]
  101. def _parse_kwargs(self):
  102. """Parse keyword arguments embedded in self.args.
  103. Parse a command given as "!command key1=value1 key2=value2..." into a
  104. dict, self.kwargs, like {'key1': 'value2', 'key2': 'value2'...}.
  105. """
  106. for arg in self.args:
  107. try:
  108. key, value = re.findall(r"^(.*?)\=(.*?)$", arg)[0]
  109. except IndexError:
  110. continue
  111. if key and value:
  112. self.kwargs[key] = value
  113. @property
  114. def my_nick(self):
  115. """Our nickname, *not* the nickname of the sender."""
  116. return self._my_nick
  117. @property
  118. def line(self):
  119. """The full message received on IRC, including escape characters."""
  120. return self._line
  121. @property
  122. def chan(self):
  123. """Channel the message was sent from.
  124. This will be equal to :py:attr:`nick` if the message is a private
  125. message.
  126. """
  127. return self._chan
  128. @property
  129. def nick(self):
  130. """Nickname of the sender."""
  131. return self._nick
  132. @property
  133. def ident(self):
  134. """`Ident <http://en.wikipedia.org/wiki/Ident>`_ of the sender."""
  135. return self._ident
  136. @property
  137. def host(self):
  138. """Hostname of the sender."""
  139. return self._host
  140. @property
  141. def reply_nick(self):
  142. """Nickname of the person to reply to. Sender by default."""
  143. return self._reply_nick
  144. @property
  145. def msg(self):
  146. """Text of the sent message, if it is a message, else ``None``."""
  147. return self._msg
  148. @property
  149. def is_private(self):
  150. """``True`` if this message was sent to us *only*, else ``False``."""
  151. return self._is_private
  152. @property
  153. def is_command(self):
  154. """Boolean telling whether or not this message is a bot command.
  155. A message is considered a command if and only if it begins with the
  156. character ``"!"``, ``"."``, or the bot's name followed by optional
  157. punctuation and a space (so ``EarwigBot: do something``, ``EarwigBot,
  158. do something``, and ``EarwigBot do something`` are all valid).
  159. """
  160. return self._is_command
  161. @property
  162. def command(self):
  163. """If the message is a command, this is the name of the command used.
  164. See :py:attr:`is_command <self.is_command>` for when a message is
  165. considered a command. If it's not a command, this will be set to
  166. ``None``.
  167. """
  168. return self._command
  169. @property
  170. def trigger(self):
  171. """If this message is a command, this is what triggered it.
  172. It can be either "!" (``"!help"``), "." (``".help"``), or the bot's
  173. name (``"EarwigBot: help"``). Otherwise, it will be ``None``."""
  174. return self._trigger
  175. @property
  176. def args(self):
  177. """List of all arguments given to this command.
  178. For example, the message ``"!command arg1 arg2 arg3=val3"`` will
  179. produce the args ``["arg1", "arg2", "arg3=val3"]``. This is empty if
  180. the message was not a command or if it doesn't have arguments.
  181. """
  182. return self._args
  183. @property
  184. def kwargs(self):
  185. """Dictionary of keyword arguments given to this command.
  186. For example, the message ``"!command arg1=val1 arg2=val2"`` will
  187. produce the kwargs ``{"arg1": "val1", "arg2": "val2"}``. This is empty
  188. if the message was not a command or if it doesn't have keyword
  189. arguments.
  190. """
  191. return self._kwargs
  192. def serialize(self):
  193. """Serialize this object into a tuple and return it."""
  194. return (self._my_nick, self._line, self._msgtype)
  195. @classmethod
  196. def unserialize(cls, data):
  197. """Return a new Data object built from a serialized tuple."""
  198. return cls(*data)