├── .gitignore ├── doc.go ├── LICENSE ├── README.md └── bot.go /.gitignore: -------------------------------------------------------------------------------- 1 | # exclude binaries 2 | bot 3 | *.json 4 | 5 | # confidential 6 | private/ -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /** 2 | * doc.go 3 | * 4 | * Copyright (c) 2017 Forest Hoffman. All Rights Reserved. 5 | * License: MIT License (see the included LICENSE file) 6 | */ 7 | 8 | /* 9 | The bot package provides a set of functions that control a basic Twitch.tv chat bot. The 10 | package also exposes an interface which can be used to create a custom chat bot. 11 | 12 | Basic usage: 13 | 14 | ``` 15 | package main 16 | 17 | import ( 18 | "github.com/foresthoffman/bot" 19 | "time" 20 | ) 21 | 22 | func main() { 23 | 24 | // Replace the channel name, bot name, and the path to the private directory with your respective 25 | // values. 26 | myBot := bot.BasicBot{ 27 | Channel: "twitch", 28 | MsgRate: time.Duration(20/30) * time.Millisecond, 29 | Name: "TwitchBot", 30 | Port: "6667", 31 | PrivatePath: "../private/oauth.json", 32 | Server: "irc.chat.twitch.tv", 33 | } 34 | myBot.Start() 35 | } 36 | ``` 37 | */ 38 | package bot 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Forest Hoffman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Bot 2 | 3 | The bot package provides a set of functions that control a basic Twitch.tv chat bot. The package also exposes an interface which can be used to create a custom chat bot. See the following series for a step-by-step tutorial on [Building a Twitch.tv Chat Bot](https://dev.to/foresthoffman/building-a-twitchtv-chat-bot-with-go---part-1-i3k) with this package. 4 | 5 | ### Installation 6 | 7 | Run `go get github.com/foresthoffman/bot` 8 | 9 | ### Importing 10 | 11 | Import this package by including `github.com/foresthoffman/bot` in your import block. 12 | 13 | e.g. 14 | 15 | ```go 16 | package main 17 | 18 | import( 19 | ... 20 | "github.com/foresthoffman/bot" 21 | ) 22 | ``` 23 | 24 | ### Usage 25 | 26 | Basic usage: 27 | 28 | ```go 29 | package main 30 | 31 | import ( 32 | "github.com/foresthoffman/bot" 33 | "time" 34 | ) 35 | 36 | func main() { 37 | 38 | // Replace the channel name, bot name, and the path to the private directory with your respective 39 | // values. 40 | myBot := bot.BasicBot{ 41 | Channel: "twitch", 42 | MsgRate: time.Duration(20/30) * time.Millisecond, 43 | Name: "TwitchBot", 44 | Port: "6667", 45 | PrivatePath: "../private/oauth.json", 46 | Server: "irc.chat.twitch.tv", 47 | } 48 | myBot.Start() 49 | } 50 | ``` 51 | 52 | _That's all, enjoy!_ 53 | -------------------------------------------------------------------------------- /bot.go: -------------------------------------------------------------------------------- 1 | /** 2 | * bot.go 3 | * 4 | * Copyright (c) 2017 Forest Hoffman. All Rights Reserved. 5 | * License: MIT License (see the included LICENSE file) 6 | */ 7 | 8 | package bot 9 | 10 | import ( 11 | "bufio" 12 | "encoding/json" 13 | "errors" 14 | "fmt" 15 | "io" 16 | "io/ioutil" 17 | "net" 18 | "net/textproto" 19 | "regexp" 20 | "strings" 21 | "time" 22 | 23 | rgb "github.com/foresthoffman/rgblog" 24 | ) 25 | 26 | const PSTFormat = "Jan 2 15:04:05 PST" 27 | 28 | // Regex for parsing PRIVMSG strings. 29 | // 30 | // First matched group is the user's name and the second matched group is the content of the 31 | // user's message. 32 | var MsgRegex *regexp.Regexp = regexp.MustCompile(`^:(\w+)!\w+@\w+\.tmi\.twitch\.tv (PRIVMSG) #\w+(?: :(.*))?$`) 33 | 34 | // Regex for parsing user commands, from already parsed PRIVMSG strings. 35 | // 36 | // First matched group is the command name and the second matched group is the argument for the 37 | // command. 38 | var CmdRegex *regexp.Regexp = regexp.MustCompile(`^!(\w+)\s?(\w+)?`) 39 | 40 | type OAuthCred struct { 41 | 42 | // The bot account's OAuth password. 43 | Password string `json:"password,omitempty"` 44 | 45 | // The developer application client ID. Used for API calls to Twitch. 46 | ClientID string `json:"client_id,omitempty"` 47 | } 48 | 49 | type Bot interface { 50 | 51 | // Opens a connection to the Twitch.tv IRC chat server. 52 | Connect() 53 | 54 | // Closes a connection to the Twitch.tv IRC chat server. 55 | Disconnect() 56 | 57 | // Listens to chat messages and PING request from the IRC server. 58 | HandleChat() error 59 | 60 | // Joins a specific chat channel. 61 | JoinChannel() 62 | 63 | // Parses credentials needed for authentication. 64 | ReadCredentials() error 65 | 66 | // Sends a message to the connected channel. 67 | Say(msg string) error 68 | 69 | // Attempts to keep the bot connected and handling chat. 70 | Start() 71 | } 72 | 73 | type BasicBot struct { 74 | 75 | // The channel that the bot is supposed to join. Note: The name MUST be lowercase, regardless 76 | // of how the username is displayed on Twitch.tv. 77 | Channel string 78 | 79 | // A reference to the bot's connection to the server. 80 | conn net.Conn 81 | 82 | // The credentials necessary for authentication. 83 | Credentials *OAuthCred 84 | 85 | // A forced delay between bot responses. This prevents the bot from breaking the message limit 86 | // rules. A 20/30 millisecond delay is enough for a non-modded bot. If you decrease the delay 87 | // make sure you're still within the limit! 88 | // 89 | // Message Rate Guidelines: https://dev.twitch.tv/docs/irc#irc-command-and-message-limits 90 | MsgRate time.Duration 91 | 92 | // The name that the bot will use in the chat that it's attempting to join. 93 | Name string 94 | 95 | // The port of the IRC server. 96 | Port string 97 | 98 | // A path to a limited-access directory containing the bot's OAuth credentials. 99 | PrivatePath string 100 | 101 | // The domain of the IRC server. 102 | Server string 103 | 104 | // The time at which the bot achieved a connection to the server. 105 | startTime time.Time 106 | } 107 | 108 | // Connects the bot to the Twitch IRC server. The bot will continue to try to connect until it 109 | // succeeds or is forcefully shutdown. 110 | func (bb *BasicBot) Connect() { 111 | var err error 112 | rgb.YPrintf("[%s] Connecting to %s...\n", timeStamp(), bb.Server) 113 | 114 | // makes connection to Twitch IRC server 115 | bb.conn, err = net.Dial("tcp", bb.Server+":"+bb.Port) 116 | if nil != err { 117 | rgb.YPrintf("[%s] Cannot connect to %s, retrying.\n", timeStamp(), bb.Server) 118 | bb.Connect() 119 | return 120 | } 121 | rgb.YPrintf("[%s] Connected to %s!\n", timeStamp(), bb.Server) 122 | bb.startTime = time.Now() 123 | } 124 | 125 | // Officially disconnects the bot from the Twitch IRC server. 126 | func (bb *BasicBot) Disconnect() { 127 | bb.conn.Close() 128 | upTime := time.Now().Sub(bb.startTime).Seconds() 129 | rgb.YPrintf("[%s] Closed connection from %s! | Live for: %fs\n", timeStamp(), bb.Server, upTime) 130 | } 131 | 132 | // Listens for and logs messages from chat. Responds to commands from the channel owner. The bot 133 | // continues until it gets disconnected, told to shutdown, or forcefully shutdown. 134 | func (bb *BasicBot) HandleChat() error { 135 | rgb.YPrintf("[%s] Watching #%s...\n", timeStamp(), bb.Channel) 136 | 137 | // reads from connection 138 | tp := textproto.NewReader(bufio.NewReader(bb.conn)) 139 | 140 | // listens for chat messages 141 | for { 142 | line, err := tp.ReadLine() 143 | if nil != err { 144 | 145 | // officially disconnects the bot from the server 146 | bb.Disconnect() 147 | 148 | return errors.New("bb.Bot.HandleChat: Failed to read line from channel. Disconnected.") 149 | } 150 | 151 | // logs the response from the IRC server 152 | rgb.YPrintf("[%s] %s\n", timeStamp(), line) 153 | 154 | if "PING :tmi.twitch.tv" == line { 155 | 156 | // respond to PING message with a PONG message, to maintain the connection 157 | bb.conn.Write([]byte("PONG :tmi.twitch.tv\r\n")) 158 | continue 159 | } else { 160 | 161 | // handle a PRIVMSG message 162 | matches := MsgRegex.FindStringSubmatch(line) 163 | if nil != matches { 164 | userName := matches[1] 165 | msgType := matches[2] 166 | 167 | switch msgType { 168 | case "PRIVMSG": 169 | msg := matches[3] 170 | rgb.GPrintf("[%s] %s: %s\n", timeStamp(), userName, msg) 171 | 172 | // parse commands from user message 173 | cmdMatches := CmdRegex.FindStringSubmatch(msg) 174 | if nil != cmdMatches { 175 | cmd := cmdMatches[1] 176 | 177 | // channel-owner specific commands 178 | if userName == bb.Channel { 179 | switch cmd { 180 | case "tbdown": 181 | rgb.CPrintf( 182 | "[%s] Shutdown command received. Shutting down now...\n", 183 | timeStamp(), 184 | ) 185 | 186 | bb.Disconnect() 187 | return nil 188 | default: 189 | // do nothing 190 | } 191 | } 192 | } 193 | default: 194 | // do nothing 195 | } 196 | } 197 | } 198 | time.Sleep(bb.MsgRate) 199 | } 200 | } 201 | 202 | // Makes the bot join its pre-specified channel. 203 | func (bb *BasicBot) JoinChannel() { 204 | rgb.YPrintf("[%s] Joining #%s...\n", timeStamp(), bb.Channel) 205 | bb.conn.Write([]byte("PASS " + bb.Credentials.Password + "\r\n")) 206 | bb.conn.Write([]byte("NICK " + bb.Name + "\r\n")) 207 | bb.conn.Write([]byte("JOIN #" + bb.Channel + "\r\n")) 208 | 209 | rgb.YPrintf("[%s] Joined #%s as @%s!\n", timeStamp(), bb.Channel, bb.Name) 210 | } 211 | 212 | // Reads from the private credentials file and stores the data in the bot's Credentials field. 213 | func (bb *BasicBot) ReadCredentials() error { 214 | 215 | // reads from the file 216 | credFile, err := ioutil.ReadFile(bb.PrivatePath) 217 | if nil != err { 218 | return err 219 | } 220 | 221 | bb.Credentials = &OAuthCred{} 222 | 223 | // parses the file contents 224 | dec := json.NewDecoder(strings.NewReader(string(credFile))) 225 | if err = dec.Decode(bb.Credentials); nil != err && io.EOF != err { 226 | return err 227 | } 228 | 229 | return nil 230 | } 231 | 232 | // Makes the bot send a message to the chat channel. 233 | func (bb *BasicBot) Say(msg string) error { 234 | if "" == msg { 235 | return errors.New("BasicBot.Say: msg was empty.") 236 | } 237 | 238 | // check if message is too large for IRC 239 | if len(msg) > 512 { 240 | return errors.New("BasicBot.Say: msg exceeded 512 bytes") 241 | } 242 | 243 | _, err := bb.conn.Write([]byte(fmt.Sprintf("PRIVMSG #%s :%s\r\n", bb.Channel, msg))) 244 | if nil != err { 245 | return err 246 | } 247 | return nil 248 | } 249 | 250 | // Starts a loop where the bot will attempt to connect to the Twitch IRC server, then connect to the 251 | // pre-specified channel, and then handle the chat. It will attempt to reconnect until it is told to 252 | // shut down, or is forcefully shutdown. 253 | func (bb *BasicBot) Start() { 254 | err := bb.ReadCredentials() 255 | if nil != err { 256 | fmt.Println(err) 257 | fmt.Println("Aborting...") 258 | return 259 | } 260 | 261 | for { 262 | bb.Connect() 263 | bb.JoinChannel() 264 | err = bb.HandleChat() 265 | if nil != err { 266 | 267 | // attempts to reconnect upon unexpected chat error 268 | time.Sleep(1000 * time.Millisecond) 269 | fmt.Println(err) 270 | fmt.Println("Starting bot again...") 271 | } else { 272 | return 273 | } 274 | } 275 | } 276 | 277 | func timeStamp() string { 278 | return TimeStamp(PSTFormat) 279 | } 280 | 281 | func TimeStamp(format string) string { 282 | return time.Now().Format(format) 283 | } 284 | --------------------------------------------------------------------------------