func run(api *slack.Client) int { rtm := api.NewRTM() go rtm.ManageConnection() for { select { case msg := <-rtm.IncomingEvents: switch ev := msg.Data.(type) { case *slack.HelloEvent: log.Print("Hello Event") case *slack.MessageEvent: log.Printf("Message: %v\n", ev) text := ev.Text r := regexp.MustCompile(`weather`) if r.MatchString(text) { out, err := exec.Command("./bin/weather", "140010").Output() log.Print(string(out)) log.Print(err) rtm.SendMessage(rtm.NewOutgoingMessage(string(out), ev.Channel)) } case *slack.InvalidAuthEvent: log.Print("Invalid credentials") return 1 } } } }
func monitorSlack(api *slack.Client, threadWait *sync.WaitGroup, recipientChan chan eventRecipient) { defer threadWait.Done() defer logging.Log.Notice("Finished monitoring Slack") eventRecipients := make(map[string]chan *slack.MessageEvent) logging.Log.Info("Connecting to RTM") rtm := api.NewRTM() go rtm.ManageConnection() defer func() { logging.Log.Info("Disconnecting from RTM") if discErr := rtm.Disconnect(); discErr != nil { logging.Log.Error("Error while disconnecting from the Slack RTM") } }() logging.Log.Info("Waiting for events") monitorLoop: for { select { case recipient := <-recipientChan: eventRecipients[recipient.channelID] = recipient.eventChan logging.Log.Debugf("Added event recipient for %v", recipient.channelID) case event, chanOpen := <-rtm.IncomingEvents: if !chanOpen { logging.Log.Warning("Incoming events channel is closed") break monitorLoop } switch evData := event.Data.(type) { case *slack.HelloEvent: logging.Log.Info("Slack says \"hello\"") case *slack.ConnectedEvent: //logging.Log.Info("Infos:", evData.Info) logging.Log.Info("Connected to Slack") logging.Log.Infof("Connection counter: %v", evData.ConnectionCount) // Replace #general with your Channel ID //rtm.SendMessage(rtm.NewOutgoingMessage("Hello world", "#general")) case *slack.MessageEvent: //logging.Log.Infof("Message: %v", evData) if evData.SubType != "" { break } if eventChan, hasEventChan := eventRecipients[evData.Channel]; hasEventChan { eventChan <- evData } //case *slack.PresenceChangeEvent: // logging.Log.Infof("Presence Change: %v", evData) case *slack.LatencyReport: logging.Log.Infof("Current latency: %v", evData.Value) case *slack.RTMError: logging.Log.Warningf("RTM Error: %s", evData.Error()) case *slack.InvalidAuthEvent: logging.Log.Error("Invalid credentials") break monitorLoop default: // Ignore other events.. //logging.Log.Infof("Unexpected: %v", event.Data) } } } return }