Example #1
0
func get_channel(rtm *slack.RTM, lookfor string) (string, error) {
	has_hash := strings.HasPrefix(strings.Trim(lookfor, " "), "#")
	if has_hash {
		lookfor = strings.TrimPrefix(strings.Trim(lookfor, " "), "#")
	}
	t := time.Now()
	ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")

	// Try public channels first
	l, err := rtm.GetChannels(false)
	if err != nil {
		fmt.Printf("[%s] ERROR Channel list error: %s\n", ts, err)
	}
	for _, v := range l {
		if v.Name == lookfor {
			return v.ID, nil
		}
	}

	// Now private channels, or groups in slack terms
	g, err := rtm.GetGroups(false)
	if err != nil {
		fmt.Printf("[%s] ERROR Channel list error: %s\n", ts, err)
	}
	for _, v := range g {
		if v.Name == lookfor {
			return v.ID, nil
		}
	}

	return "", errors.New("No channel found with this name")
}
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
}
Example #3
0
func (c *Counter) checkOrIncr(rtm *slack.RTM, wg sync.WaitGroup,
	memmap map[string]string) {
	defer wg.Done()
	ticker := time.NewTicker(time.Second * 10)

	for {
		select {
		case msg := <-c.messages:
			createNewTopic(c, msg.Text, rtm)
			m := askToMeditate(c, msg.Text)
			if m != "" {
				rtm.SendMessage(rtm.NewOutgoingMessage(m,
					c.channelId))
			}
			// If we receive a message on the channel, we increment
			// the counter.
			c.Increment(msg, memmap)
		case <-ticker.C:
			// We perform this check only if the monk is not meditating.
			if d := c.MeditationEnd(); d < 0 {
				count := c.Count()
				if count >= *maxmsg {
					go sendMessage(c, rtm)
				}
			}
		}
	}
}
Example #4
0
func checkError(err error, rtm *slack.RTM, botName, channel string) {
	if err != nil {
		var reply string
		if debug_mode {
			reply = fmt.Sprintf("Opps! %s遇到了点麻烦:\n%s", botName, err.Error())
		} else {
			reply = fmt.Sprintf("Opps! %s遇到了点麻烦,正在紧张处理中...", botName)
		}
		rtm.SendMessage(rtm.NewOutgoingMessage(reply, channel))
	}
}
Example #5
0
func lookupChannelByName(api *slack.RTM, name string) *slack.Channel {
	channels, err := api.GetChannels(true)
	if err != nil {
		log.Fatal(err)
	}
	for _, channel := range channels {
		if channel.Name == name {
			return &channel
		}
	}
	return nil
}
Example #6
0
func talk(rtm *slack.RTM, o Opts) {
	t := time.Now()
	ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
Loop:
	for {
		t = time.Now()
		ts = t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.HelloEvent:
				if o.debug {
					fmt.Printf("[%s] INFO Received hello: %v\n", ts, ev)
				}

			case *slack.ConnectedEvent:
				if o.debug {
					fmt.Printf("[%s] INFO Event information: %s\n", ts, ev.Info)
				}
				rtm.SendMessage(rtm.NewOutgoingMessage("Hello, Dave", o.slack_channel))

			case *slack.MessageEvent:
				if o.debug {
					fmt.Printf("[%s] INFO Message event information: %v\n", ts, ev)
				}

			case *slack.PresenceChangeEvent:
				if o.debug {
					fmt.Printf("[%s] INFO Presence change: %v\n", ts, ev)
				}

			case *slack.LatencyReport:
				if o.debug {
					fmt.Printf("[%s] INFO Current latency: %v\n", ts, ev.Value)
				}

			case *slack.RTMError:
				fmt.Printf("[%s] ERROR Slack RTM Error: %s\n", ts, ev.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("[%s] ERROR Invalid credentials\n", ts)
				break Loop

			default:
				if o.debug {
					fmt.Printf("[%s] INFO Unexpected event: %v\n", ts, msg.Data)
				}
			}
		}
	}
}
Example #7
0
func logTransmitter(rtm *slack.RTM) {
	channel := lookupChannelByName(rtm, "logs")
	if channel == nil {
		log.Fatal("You must create #logs and invite me")
	}
	if !channel.IsMember {
		log.Fatal("You must invite me in to #logs")
	}

	for ev := range services.Subscriber.FilteredChannel("log") {
		message := fmt.Sprintf("[%s] %s", ev.StringField("source"), ev.StringField("message"))
		rtm.SendMessage(rtm.NewOutgoingMessage(message, channel.ID))
	}
}
Example #8
0
func respond(rtm *slack.RTM, msg *slack.MessageEvent, prefix string) {
	var response string
	text := msg.Text
	text = strings.TrimPrefix(text, prefix)
	text = strings.TrimSpace(text)
	text = strings.ToLower(text)
	switch text {
	case "help":
		response = fmt.Sprintf("Available questionnaires: \n\n%s", qbot.Questionnaires.AvailableQuestionnaires())
	case "status":
		response = "status is.. YOU ARE AWESOME!"
	case "":
	default:
		response = fmt.Sprintf("I didn't understand your request. Available questionnaires: \n\n%s", qbot.Questionnaires.AvailableQuestionnaires())
	}
	omsg := rtm.NewOutgoingMessage(response, msg.Channel)
	rtm.SendMessage(omsg)
}
Example #9
0
func get_channel(rtm *slack.RTM, lookfor string) (string, error) {
	has_hash := strings.HasPrefix(strings.Trim(lookfor, " "), "#")
	if has_hash {
		lookfor = strings.TrimPrefix(strings.Trim(lookfor, " "), "#")
	}
	l, err := rtm.GetChannels(false)
	if err != nil {
		t := time.Now()
		ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
		fmt.Printf("[%s] ERROR Channel list error: %s\n", ts, err)
		os.Exit(1)
	}
	for _, v := range l {
		if v.Name == lookfor {
			return v.ID, nil
		}
	}
	return "", errors.New("No channel found with this name")
}
Example #10
0
func handleCommand(rtm *slack.RTM, session *plugin.Session, botName, channel, sender, text string) {
	// 处理会话
	if session.Status != plugin.S_INIT {
		msg := plugin.NewMessage(rtm, session, botName, text, channel)
		checkError(session.Handler.Respond(msg), rtm, botName, channel)
	} else {
		found := false
		for _, v := range plugin.BotCommands {
			if v.Matches(text) {
				found = true
				msg := plugin.NewMessage(rtm, session, botName, text, channel)
				checkError(v.Respond(msg), rtm, botName, channel)
				break
			}
		}
		if !found {
			// echo received text
			rtm.SendMessage(rtm.NewOutgoingMessage(text, channel))
		}
	}
}
Example #11
0
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...
			}
		}
	}
}
Example #12
0
func post(rtm *slack.RTM, channel string, message Message, debug bool) {
	t := time.Now()
	ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
	params := slack.PostMessageParameters{
		Username: "******",
	}
	attachment := slack.Attachment{
		Pretext: message.Subject,
		Text:    message.Detail,
	}
	params.Attachments = []slack.Attachment{attachment}

	title := fmt.Sprintf("Alert *%s* with Severity %d (Magnitude: %d, Floater: %.4f)", message.Subject, message.Severity, message.Magnitude, message.Floater)
	channelID, timestamp, err := rtm.PostMessage(channel, title, params)
	if err != nil {
		fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
		return
	}
	if debug {
		fmt.Printf("[%s] INFO Message %+v successfully sent to channel %s at %s", ts, message, channelID, timestamp)
	}
}
Example #13
0
func do(cmd string, rtm *slack.RTM, channel string) {
	// send docker output to slack
	go func() {
		out, err := exec.Command("sh", "-c", cmd).Output()

		if err != nil {
			rtm.SendMessage(rtm.NewOutgoingMessage(err.Error(), channel))
		} else {
			var lines []string
			lines = append(lines, "```")
			lines = append(lines, string(out[:]))
			lines = append(lines, "```")

			rtm.SendMessage(rtm.NewOutgoingMessage(strings.Join(lines, "\n"), channel))
		}
	}()
}
Example #14
0
func (g group) getHistory(rtm *slack.RTM, params slack.HistoryParameters) (*slack.History, error) {
	return rtm.GetGroupHistory(g.getID(), params)
}
Example #15
0
func (c channel) getHistory(rtm *slack.RTM, params slack.HistoryParameters) (*slack.History, error) {
	return rtm.GetChannelHistory(c.getID(), params)
}
Example #16
0
func pull(rtm *slack.RTM, o Opts) {
	/*
		Using a FIFO queue
	*/
	t := time.Now()
	ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
	rc, err := cluster.NewCluster(o.redis_connection)

	if err != nil {
		fmt.Printf("[%s] ERROR Redis connection error: %s\n", ts, err)
		os.Exit(1)
	}
	r := rc.Cmd("SELECT", o.redis_db)

	for {
		t = time.Now()
		ts = t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
		r = rc.Cmd("RPOP", o.redis_list)

		switch r.Type {
		case redis.ErrorReply:
			fmt.Printf("[%s] ERROR ErrorReply received: %s\n", ts, r.Err.Error())
		case redis.NilReply:
			if o.debug {
				fmt.Printf("[%s] INFO NilReply reply received\n", ts)
			}
		case redis.StatusReply:
			if o.debug {
				fmt.Printf("[%s] INFO StatusReply reply received: not processing\n", ts)
			}
		case redis.BulkReply:
			// Send to Slack
			data, err := r.Bytes()
			if err != nil {
				fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
			} else {
				if o.json {
					type Message struct {
						Name   string
						Source string
						Detail string
					}
					var message Message
					err := json.Unmarshal(data, &message)
					if err != nil {
						fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
					}
					params := slack.PostMessageParameters{
						Username: "******",
					}
					attachment := slack.Attachment{
						Pretext: message.Source,
						Text:    message.Detail,
					}
					params.Attachments = []slack.Attachment{attachment}

					channelID, timestamp, err := rtm.PostMessage(o.slack_channel, string(message.Name), params)
					if err != nil {
						fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
						return
					}
					if o.debug {
						fmt.Printf("[%s] INFO Message %+v successfully sent to channel %s at %s", ts, message, channelID, timestamp)
					}
				} else {
					if o.debug {
						fmt.Printf("[%s] INFO BulkReply reply received: %s\n", ts, data)
					}
					rtm.SendMessage(rtm.NewOutgoingMessage(string(data), o.slack_channel))
				}
			}
		case redis.MultiReply:
			if o.debug {
				fmt.Printf("[%s] INFO MultiReply reply received: not processing\n", ts)
			}
		case redis.IntegerReply:
			if o.debug {
				fmt.Printf("[%s] INFO IntegerReply reply received: not processing\n", ts)
			}
		default:
			if o.debug {
				fmt.Printf("[%s] INFO Unknown reply received: not processing\n", ts)
			}
		}

		time.Sleep(time.Duration(o.watch_interval) * time.Millisecond)
	}
}
Example #17
0
func slacker(rtm *slack.RTM) {
	go rtm.ManageConnection()

	greeted := false
	userId := ""
Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch event := msg.Data.(type) {
			case *slack.ConnectedEvent:
				// say hello in the first channel we're in
				if len(event.Info.Channels) > 0 {
					if !greeted {
						channel := event.Info.Channels[0]
						rtm.SendMessage(rtm.NewOutgoingMessage("gohome bot reporting for duty!", channel.ID))
					}
					greeted = true
				}
				// remember our id
				userId = event.Info.User.ID

			case *slack.MessageEvent:
				if event.User == userId || event.BotID != "" {
					// ignore messages from self or bots
					continue
				}
				// send the message as a query
				log.Println("Querying:", event.Text)
				ch := services.QueryChannel(event.Text, time.Duration(5)*time.Second)

				gotResponse := false
				for ev := range ch {
					// send back responses
					message := ev.StringField("message")
					if message == "" {
						message = ev.String()
					}
					rtm.SendMessage(rtm.NewOutgoingMessage(message, event.Channel))
					gotResponse = true
				}

				if !gotResponse {
					rtm.SendMessage(rtm.NewOutgoingMessage("Sorry, nothing answered!", event.Channel))
				}

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", event.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop

			default:
				// Ignore other events..
				// case *slack.HelloEvent:
				// case *slack.PresenceChangeEvent:
				// case *slack.LatencyReport:
				// fmt.Printf("Unexpected: %v\n", msg.Data)
			}
		}
	}
}