A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

62 строки
1.9 KiB

  1. # -*- coding: utf-8 -*-
  2. import re
  3. class KwargParseException(Exception):
  4. """Couldn't parse a certain keyword argument in self.args, probably because
  5. it was given incorrectly: e.g., no value (abc), just a value (=xyz), just
  6. an equal sign (=), instead of the correct (abc=xyz)."""
  7. pass
  8. class Data(object):
  9. """Store data from an individual line received on IRC."""
  10. def __init__(self, line):
  11. self.line = line
  12. self.chan = str()
  13. self.nick = str()
  14. self.ident = str()
  15. self.host = str()
  16. self.msg = str()
  17. def parse_args(self):
  18. """Parse command args from self.msg into self.command and self.args."""
  19. args = self.msg.strip().split(" ")
  20. while "" in args:
  21. args.remove("")
  22. # Isolate command arguments:
  23. self.args = args[1:]
  24. self.is_command = False # is this message a command?
  25. try:
  26. self.command = args[0]
  27. except IndexError:
  28. self.command = None
  29. try:
  30. if self.command.startswith('!') or self.command.startswith('.'):
  31. self.is_command = True
  32. self.command = self.command[1:] # Strip the '!' or '.'
  33. self.command = self.command.lower()
  34. except AttributeError:
  35. pass
  36. def parse_kwargs(self):
  37. """Parse keyword arguments embedded in self.args.
  38. Parse a command given as "!command key1=value1 key2=value2..." into a
  39. dict, self.kwargs, like {'key1': 'value2', 'key2': 'value2'...}.
  40. """
  41. self.kwargs = {}
  42. for arg in self.args[2:]:
  43. try:
  44. key, value = re.findall("^(.*?)\=(.*?)$", arg)[0]
  45. except IndexError:
  46. raise KwargParseException(arg)
  47. if key and value:
  48. self.kwargs[key] = value
  49. else:
  50. raise KwargParseException(arg)