message.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from __future__ import print_function
  2. class Tag(object):
  3. """
  4. An IRC message tag ircv3.net/specs/core/message-tags-3.2.html
  5. """
  6. @staticmethod
  7. def parse(item):
  8. r"""
  9. >>> Tag.parse('x') == {'key': 'x', 'value': None}
  10. True
  11. >>> Tag.parse('x=yes') == {'key': 'x', 'value': 'yes'}
  12. True
  13. >>> Tag.parse('x=3')['value']
  14. '3'
  15. >>> Tag.parse('x=red fox\\:green eggs')['value']
  16. 'red fox;green eggs'
  17. >>> Tag.parse('x=red fox:green eggs')['value']
  18. 'red fox:green eggs'
  19. >>> Tag.parse('x=a\\nb\\nc')['value']
  20. 'a\nb\nc'
  21. """
  22. key, sep, value = item.partition('=')
  23. value = value.replace('\\:', ';')
  24. value = value.replace('\\s', ' ')
  25. value = value.replace('\\n', '\n')
  26. value = value.replace('\\r', '\r')
  27. value = value.replace('\\\\', '\\')
  28. value = value or None
  29. return {
  30. 'key': key,
  31. 'value': value,
  32. }
  33. @classmethod
  34. def from_group(cls, group):
  35. """
  36. Construct tags from the regex group
  37. """
  38. if not group:
  39. return
  40. tag_items = group.split(";")
  41. return list(map(cls.parse, tag_items))
  42. class Arguments(list):
  43. @staticmethod
  44. def from_group(group):
  45. """
  46. Construct arguments from the regex group
  47. >>> Arguments.from_group('foo')
  48. ['foo']
  49. >>> Arguments.from_group(None)
  50. []
  51. >>> Arguments.from_group('')
  52. []
  53. >>> Arguments.from_group('foo bar')
  54. ['foo', 'bar']
  55. >>> Arguments.from_group('foo bar :baz')
  56. ['foo', 'bar', 'baz']
  57. >>> Arguments.from_group('foo bar :baz bing')
  58. ['foo', 'bar', 'baz bing']
  59. """
  60. if not group:
  61. return []
  62. main, sep, ext = group.partition(" :")
  63. arguments = main.split()
  64. if sep:
  65. arguments.append(ext)
  66. return arguments