A modular Twitch bot made in Go
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.

84 lines
1.6 KiB

2 years ago
  1. package twitchbot
  2. import (
  3. "strings"
  4. )
  5. type Command struct {
  6. Tags map[string]string
  7. Prefix string
  8. Command string
  9. Args []string
  10. Suffix string
  11. }
  12. func (c *Command) String() string {
  13. return "Prefix: " + c.Prefix + " Command: " + c.Command + " Args: " + strings.Join(c.Args, " ") + " Suffix: " + c.Suffix
  14. }
  15. func ReadString(reader *strings.Reader, until byte) string {
  16. result := strings.Builder{}
  17. char, ok := reader.ReadByte()
  18. for ok == nil {
  19. if char == until {
  20. break
  21. }
  22. result.WriteByte(char)
  23. char, ok = reader.ReadByte()
  24. }
  25. return result.String()
  26. }
  27. func ReadTags(reader *strings.Reader) map[string]string {
  28. result := make(map[string]string)
  29. for {
  30. tag := ReadString(reader, '=')
  31. if tag == "" {
  32. break
  33. }
  34. value := ReadString(reader, ';')
  35. result[tag] = value
  36. }
  37. return result
  38. }
  39. func ParsePacket(packet string) *Command {
  40. reader := strings.NewReader(packet)
  41. command := Command{}
  42. args := make([]string, 15)
  43. arg := 0
  44. char, ok := reader.ReadByte()
  45. for ok == nil {
  46. if char == ':' && command.Prefix == "" && command.Command == "" {
  47. command.Prefix = ReadString(reader, ' ')
  48. } else if char == '@' && command.Tags == nil {
  49. command.Tags = ReadTags(strings.NewReader(ReadString(reader, ' ')))
  50. } else if command.Command == "" {
  51. _, err := reader.Seek(-1, 1)
  52. if err != nil {
  53. continue
  54. }
  55. command.Command = ReadString(reader, ' ')
  56. } else if char == ':' {
  57. command.Suffix = ReadString(reader, '\r')
  58. } else {
  59. _, err := reader.Seek(-1, 1)
  60. if err != nil {
  61. continue
  62. }
  63. args[arg] = ReadString(reader, ' ')
  64. arg++
  65. }
  66. char, ok = reader.ReadByte()
  67. }
  68. command.Args = args
  69. return &command
  70. }