Exemple #1
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...
			}
		}
	}
}
Exemple #2
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)
				}
			}
		}
	}
}
Exemple #3
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))
	}
}
Exemple #4
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)
				}
			}
		}
	}
}
Exemple #5
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))
	}
}
Exemple #6
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))
		}
	}()
}
Exemple #7
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)
}
Exemple #8
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))
		}
	}
}
Exemple #9
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)
	}
}
Exemple #10
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)
			}
		}
	}
}