func handleMessage(rtm *slack.RTM) { // 会话 session := new(plugin.Session) session.ResetSession() // 注册命令处理器 plugin.BotCommands = append(plugin.BotCommands, new(plugin.Help)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Hello)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Shell)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Time)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Mail)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Service)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Nginx)) plugin.BotCommands = append(plugin.BotCommands, new(plugin.Joke)) user, err := rtm.GetUserInfo(botID) if err != nil { fmt.Println(err) return } botName := user.Profile.FirstName + " " + user.Profile.LastName for { select { case msg := <-rtm.IncomingEvents: fmt.Print("Event Received: ") switch evt := msg.Data.(type) { case *slack.HelloEvent: // Ignore hello case *slack.ConnectedEvent: fmt.Println("Info:", evt.Info) fmt.Println("Connection counter:", evt.ConnectionCount) rtm.SendMessage(rtm.NewOutgoingMessage("Hello world", "#general")) case *slack.MessageEvent: fmt.Printf("Message: %v\n", evt) if evt.Channel == botChannelID && evt.Team == mxTeamID { text, sendToMXBot := checkMessage(evt.Text) if sendToMXBot && len(text) > 0 { go handleCommand(rtm, session, botName, evt.Channel, evt.User, strings.TrimSpace(text)) } } else if evt.Channel == botDMChannelID && evt.Team == mxTeamID { go handleCommand(rtm, session, botName, evt.Channel, evt.User, strings.TrimSpace(evt.Text)) } case *slack.ChannelJoinedEvent: // Ignore case *slack.PresenceChangeEvent: fmt.Printf("Presence Change: %v\n", evt) case *slack.LatencyReport: fmt.Printf("Current latency: %v\n", evt.Value) case *slack.RTMError: fmt.Printf("Error: %s\n", evt.Error()) case *slack.InvalidAuthEvent: fmt.Printf("Invalid credentials") return default: // Ignore other events... } } } }
func flattenSlackMessage(rtm *slack.RTM, text string) string { text = slackLink1Regex.ReplaceAllString(text, "$1") text = slackLink2Regex.ReplaceAllString(text, "$1") text = slackLink3Regex.ReplaceAllString(text, "$1") text = slackActionRegex.ReplaceAllString(text, "@$1") text = slackEmojiRegex.ReplaceAllStringFunc(text, func(text string) string { if emoji, ok := emojis[text[1:len(text)-1]]; ok { return emoji } return text }) text = slackReference1Regex.ReplaceAllString(text, "$1$4") text = slackReference2Regex.ReplaceAllStringFunc(text, func(text string) string { switch text[:2] { case "<#": ch, err := rtm.GetChannelInfo(text[2 : len(text)-1]) if err == nil { return "#" + ch.Name } case "<@": user, err := rtm.GetUserInfo(text[2 : len(text)-1]) if err == nil { return "@" + user.Name } } return text }) text = html.UnescapeString(text) return text }