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.

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