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.

106 lines
2.0 KiB

2 years ago
  1. package twitchbot
  2. import (
  3. "bufio"
  4. "net"
  5. "net/textproto"
  6. )
  7. type Client struct {
  8. Token string
  9. Nick string
  10. conn net.Conn
  11. writer *textproto.Writer
  12. reader *textproto.Reader
  13. handlers map[string][]func(*Command) bool
  14. }
  15. func (client *Client) Connect(host string) error {
  16. conn, err := net.Dial("tcp", host)
  17. if err != nil {
  18. return err
  19. }
  20. client.conn = conn
  21. client.writer = textproto.NewWriter(bufio.NewWriter(conn))
  22. client.reader = textproto.NewReader(bufio.NewReader(conn))
  23. return nil
  24. }
  25. func (client *Client) Auth() error {
  26. err := client.writer.PrintfLine("PASS %s", client.Token)
  27. if err != nil {
  28. return err
  29. }
  30. err = client.writer.PrintfLine("NICK %s", client.Nick)
  31. if err != nil {
  32. return err
  33. }
  34. return nil
  35. }
  36. func (client *Client) AddHandler(command string, f func(*Command) bool) {
  37. if client.handlers == nil {
  38. client.handlers = make(map[string][]func(*Command) bool)
  39. }
  40. handlers, ok := client.handlers[command]
  41. if !ok {
  42. client.handlers[command] = []func(*Command) bool{f}
  43. } else {
  44. client.handlers[command] = append(handlers, f)
  45. }
  46. }
  47. func (client *Client) Send(command *Command) error {
  48. err := client.writer.PrintfLine(command.Build())
  49. if err != nil {
  50. return err
  51. }
  52. return nil
  53. }
  54. func (client *Client) CapReq(cap string) error {
  55. err := client.Send(&Command{
  56. Command: "CAP",
  57. Args: []string{"REQ"},
  58. Suffix: cap,
  59. })
  60. if err != nil {
  61. return err
  62. }
  63. return nil
  64. }
  65. func (client *Client) Join(channel string) error {
  66. err := client.Send(&Command{
  67. Command: "JOIN",
  68. Args: []string{channel},
  69. })
  70. if err != nil {
  71. return err
  72. }
  73. return nil
  74. }
  75. func (client *Client) Close() {
  76. err := client.conn.Close()
  77. if err != nil {
  78. return
  79. }
  80. }
  81. func (client *Client) Handle() error {
  82. for {
  83. packet, err := client.reader.ReadLine()
  84. if err != nil {
  85. return err
  86. }
  87. command := ParsePacket(packet)
  88. handlers := client.handlers[command.Command]
  89. for _, handler := range handlers {
  90. if !handler(command) {
  91. return nil
  92. }
  93. }
  94. }
  95. }