Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.39 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "strings"
  6. )
  7.  
  8. // Command is a chat command for the bot.
  9. type Command struct {
  10.     Name     string `json:"name"`
  11.     Response string `json:"response"`
  12. }
  13.  
  14. func main() {
  15.     commands := make(map[string]*Command)
  16.  
  17.     // add a command to test against
  18.     commands["music"] = &Command{
  19.         Name:     "music",
  20.         Response: "play that funky music!",
  21.     }
  22.  
  23.     // faking what the message would be from twitch chat.
  24.     message := "!music"
  25.  
  26.     // check the message
  27.     if response, ok := Check(commands, message); ok {
  28.         // send the response
  29.         fmt.Printf("%s\n\r", response)
  30.     } else {
  31.         // no command was found in the message.
  32.         fmt.Println("No command found.")
  33.     }
  34. }
  35.  
  36. // Check validates a message for a command and returns a response.
  37. func Check(commands map[string]*Command, message string) (string, bool) {
  38.     // take the first word from the message
  39.     firstWord := strings.Split(message, " ")[0]
  40.  
  41.     // check if the word starts with an exclamation mark
  42.     // and has at least one other character
  43.     if strings.HasPrefix(firstWord, "!") && len(message) > 1 {
  44.         // remove the exclamation mark from the word
  45.         word := firstWord[1:]
  46.  
  47.         // perform an ok check on the map to see if it exists, and return
  48.         // the response for it
  49.         if cmd, ok := commands[word]; ok {
  50.             return cmd.Response, true
  51.         }
  52.     }
  53.  
  54.     // we didn't find a command, so return no response and false.
  55.     return "", false
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement