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.

242 lines
8.4 KiB

  1. # Copyright (C) 2009-2016 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. import re
  21. __all__ = ["Data"]
  22. class Data:
  23. """Store data from an individual line received on IRC."""
  24. def __init__(self, my_nick, line, msgtype):
  25. self._my_nick = my_nick.lower()
  26. self._line = line
  27. self._msgtype = msgtype
  28. self._is_private = self._is_command = False
  29. self._msg = self._command = self._trigger = None
  30. self._args = []
  31. self._kwargs = {}
  32. self._parse()
  33. def __repr__(self):
  34. """Return the canonical string representation of the Data."""
  35. res = "Data(my_nick={0!r}, line={1!r})"
  36. return res.format(self.my_nick, self.line)
  37. def __str__(self):
  38. """Return a nice string representation of the Data."""
  39. return "<Data of {!r}>".format(" ".join(self.line))
  40. def _parse(self):
  41. """Parse a line from IRC into its components as instance attributes."""
  42. self._chan = self.line[2]
  43. try:
  44. sender = re.findall(r":(.*?)!(.*?)@(.*?)\Z", self.line[0])[0]
  45. except IndexError:
  46. self._host = self.line[0][1:]
  47. self._nick = self._ident = self._reply_nick = "*"
  48. return
  49. self._nick, self._ident, self._host = sender
  50. self._reply_nick = self._nick
  51. if self._msgtype in ["PRIVMSG", "NOTICE"]:
  52. if self.chan.lower() == self.my_nick:
  53. # This is a privmsg to us, so set 'chan' as the nick of the
  54. # sender instead of the 'channel', which is ourselves:
  55. self._chan = self._nick
  56. self._is_private = True
  57. self._msg = " ".join(self.line[3:])[1:]
  58. if self._msgtype == "PRIVMSG":
  59. self._parse_args()
  60. self._parse_kwargs()
  61. def _parse_args(self):
  62. """Parse command arguments from the message.
  63. self.msg is converted into the string self.command and the argument
  64. list self.args if the message starts with a "trigger" ("!", ".", or the
  65. bot's name); self.is_command will be set to True, and self.trigger will
  66. store the trigger string. Otherwise, is_command will be set to False.
  67. """
  68. self._args = self.msg.strip().split()
  69. try:
  70. command_uc = self.args.pop(0)
  71. self._command = command_uc.lower()
  72. except IndexError:
  73. return
  74. # e.g. "!command>user arg1 arg2"
  75. if ">" in self.command:
  76. command_uc, self._reply_nick = command_uc.split(">", 1)
  77. self._command = command_uc.lower()
  78. if self.command.startswith("!") or self.command.startswith("."):
  79. # e.g. "!command arg1 arg2"
  80. self._is_command = True
  81. self._trigger = self.command[0]
  82. self._command = self.command[1:] # Strip the "!" or "."
  83. elif re.match(rf"{re.escape(self.my_nick)}\W*?$", self.command, re.U):
  84. # e.g. "EarwigBot, command arg1 arg2"
  85. self._is_command = True
  86. self._trigger = self.my_nick
  87. try:
  88. self._command = self.args.pop(0).lower()
  89. except IndexError:
  90. self._command = ""
  91. else:
  92. try:
  93. if self.msg[-1] == "." and self.msg[-2] != ".":
  94. if self.args:
  95. self.args[-1] = self.args[-1][:-1]
  96. else:
  97. self._command = self.command[:-1]
  98. except IndexError:
  99. pass
  100. # e.g. "!command >user arg1 arg2"
  101. if self.args and self.args[0].startswith(">"):
  102. self._reply_nick = self.args.pop(0)[1:]
  103. def _parse_kwargs(self):
  104. """Parse keyword arguments embedded in self.args.
  105. Parse a command given as "!command key1=value1 key2=value2..." into a
  106. dict, self.kwargs, like {'key1': 'value2', 'key2': 'value2'...}.
  107. """
  108. for arg in self.args:
  109. try:
  110. key, value = re.findall(r"^(.*?)\=(.*?)$", arg)[0]
  111. except IndexError:
  112. continue
  113. if key and value:
  114. self.kwargs[key] = value
  115. @property
  116. def my_nick(self):
  117. """Our nickname, *not* the nickname of the sender."""
  118. return self._my_nick
  119. @property
  120. def line(self):
  121. """The full message received on IRC, including escape characters."""
  122. return self._line
  123. @property
  124. def chan(self):
  125. """Channel the message was sent from.
  126. This will be equal to :py:attr:`nick` if the message is a private
  127. message.
  128. """
  129. return self._chan
  130. @property
  131. def nick(self):
  132. """Nickname of the sender."""
  133. return self._nick
  134. @property
  135. def ident(self):
  136. """`Ident <https://en.wikipedia.org/wiki/Ident_protocol>`_ of the sender."""
  137. return self._ident
  138. @property
  139. def host(self):
  140. """Hostname of the sender."""
  141. return self._host
  142. @property
  143. def reply_nick(self):
  144. """Nickname of the person to reply to. Sender by default."""
  145. return self._reply_nick
  146. @property
  147. def msg(self):
  148. """Text of the sent message, if it is a message, else ``None``."""
  149. return self._msg
  150. @property
  151. def is_private(self):
  152. """``True`` if this message was sent to us *only*, else ``False``."""
  153. return self._is_private
  154. @property
  155. def is_command(self):
  156. """Boolean telling whether or not this message is a bot command.
  157. A message is considered a command if and only if it begins with the
  158. character ``"!"``, ``"."``, or the bot's name followed by optional
  159. punctuation and a space (so ``EarwigBot: do something``, ``EarwigBot,
  160. do something``, and ``EarwigBot do something`` are all valid).
  161. """
  162. return self._is_command
  163. @property
  164. def command(self):
  165. """If the message is a command, this is the name of the command used.
  166. See :py:attr:`is_command <self.is_command>` for when a message is
  167. considered a command. If it's not a command, this will be set to
  168. ``None``.
  169. """
  170. return self._command
  171. @property
  172. def trigger(self):
  173. """If this message is a command, this is what triggered it.
  174. It can be either "!" (``"!help"``), "." (``".help"``), or the bot's
  175. name (``"EarwigBot: help"``). Otherwise, it will be ``None``."""
  176. return self._trigger
  177. @property
  178. def args(self):
  179. """List of all arguments given to this command.
  180. For example, the message ``"!command arg1 arg2 arg3=val3"`` will
  181. produce the args ``["arg1", "arg2", "arg3=val3"]``. This is empty if
  182. the message was not a command or if it doesn't have arguments.
  183. """
  184. return self._args
  185. @property
  186. def kwargs(self):
  187. """Dictionary of keyword arguments given to this command.
  188. For example, the message ``"!command arg1=val1 arg2=val2"`` will
  189. produce the kwargs ``{"arg1": "val1", "arg2": "val2"}``. This is empty
  190. if the message was not a command or if it doesn't have keyword
  191. arguments.
  192. """
  193. return self._kwargs
  194. def serialize(self):
  195. """Serialize this object into a tuple and return it."""
  196. return (self._my_nick, self._line, self._msgtype)
  197. @classmethod
  198. def unserialize(cls, data):
  199. """Return a new Data object built from a serialized tuple."""
  200. return cls(*data)