A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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