func statusToSlack(api *slack.Client, my_name string, channel string, msg string) {
	params := slack.NewPostMessageParameters()
	params.Username = my_name
	params.IconEmoji = ":exclamation:"
	attachment := slack.Attachment{}
	attachment.Color = "#ffaa00"
	attachment.Title = "Alarm Status Update"
	attachment.Text = msg
	params.Attachments = []slack.Attachment{attachment}
	api.PostMessage(channel, "", params)
}
func logToSlack(api *slack.Client, my_name string, channel string, msg string, fields []slack.AttachmentField) {
	params := slack.NewPostMessageParameters()
	params.Username = my_name
	params.IconEmoji = ":page_with_curl:"
	attachment := slack.Attachment{}
	attachment.Color = "#ffaa00"
	attachment.Title = "Log Entry"
	attachment.Text = msg
	attachment.Fields = fields
	params.Attachments = []slack.Attachment{attachment}
	api.PostMessage(channel, "", params)
}
Exemple #3
0
func processShuttleCommand(bot *BaseBot, channel string) {
	// retrieve shuttle bus information from official site
	resp, err := http.Get("http://www.yonsei.ac.kr/_custom/yonsei/_common/shuttle_bus/get_bus_info.jsp")
	if err != nil {
		shuttleErrorMessage(bot, channel)
		return
	}

	buf := new(bytes.Buffer)
	buf.ReadFrom(resp.Body)
	b := buf.Bytes()

	var info BusInfo
	err = json.Unmarshal(b, &info)
	if err != nil {
		shuttleErrorMessage(bot, channel)
		return
	}

	attachments := make([]slack.AttachmentField, len(info.MBus)+len(info.ABus))
	index := 0
	for _, pos := range info.MBus {
		makeShuttlePositionAttachmentField(&attachments[index], before_noon, pos)
		index++
	}
	for _, pos := range info.ABus {
		makeShuttlePositionAttachmentField(&attachments[index], after_noon, pos)
		index++
	}

	attachment := slack.Attachment{
		Color: "#1766ff",
	}
	if len(attachments) == 0 {
		// no info!
		attachment.Text = "현재 운영중인 셔틀버스 정보 없음"
	} else {
		attachment.Text = "셔틀버스 위치"
		attachment.Fields = attachments
	}

	bot.PostMessage(channel, "", slack.PostMessageParameters{
		AsUser:    false,
		IconEmoji: ":bus:",
		Username:  "******",
		Attachments: []slack.Attachment{
			attachment,
		},
	})
}
func motionToSlack(api *slack.Client, my_name string, channel string, image string, count int) {
	_, err := http.Get(image)
	chk(err)

	params := slack.NewPostMessageParameters()
	params.Username = my_name
	params.IconEmoji = ":rotating_light:"
	attachment := slack.Attachment{}
	attachment.Color = "#ff0000"
	attachment.Title = "Motion detected"
	attachment.Text = fmt.Sprintf("Motion events detected: %d", count)
	attachment.ImageURL = image
	params.Attachments = []slack.Attachment{attachment}
	api.PostMessage(channel, "", params)
}
func lightsToSlack(api *slack.Client, my_name string, channel string, image string, level int) {
	_, err := http.Get(image)
	chk(err)

	params := slack.NewPostMessageParameters()
	params.Username = my_name
	params.IconEmoji = ":bulb:"
	attachment := slack.Attachment{}
	attachment.Color = "#00ff00"
	attachment.Title = "Lights detected"
	attachment.Text = fmt.Sprintf("Light level detected: %d", level)
	attachment.ImageURL = image
	params.Attachments = []slack.Attachment{attachment}
	api.PostMessage(channel, "", params)
}
Exemple #6
0
func (s *Slack) onMessage(message *Message) error {
	postMessage := slack.PostMessageParameters{
		Username:  message.Name,
		LinkNames: 1,
	}

	re := regexp.MustCompile("^:.*:$")
	if re.MatchString(message.Icon) {
		postMessage.IconEmoji = message.Icon
	} else {
		postMessage.IconURL = message.Icon
	}

	if message.Attachment != nil {
		attachment := slack.Attachment{
			Fallback:   message.Attachment.Fallback,
			Color:      message.Attachment.Color,
			Pretext:    message.Attachment.Pretext,
			AuthorName: message.Attachment.AuthorName,
			AuthorLink: message.Attachment.AuthorLink,
			AuthorIcon: message.Attachment.AuthorIcon,
			Title:      message.Attachment.Title,
			TitleLink:  message.Attachment.TitleLink,
			Text:       message.Attachment.Text,
			ImageURL:   message.Attachment.ImageURL,
			MarkdownIn: []string{"text", "pretext", "fields"},
		}
		if len(message.Attachment.Fields) > 0 {
			fields := make([]slack.AttachmentField, len(message.Attachment.Fields))
			for i := range fields {
				fields[i].Title = message.Attachment.Fields[i].Title
				fields[i].Value = message.Attachment.Fields[i].Value
				fields[i].Short = message.Attachment.Fields[i].Short
			}
			attachment.Fields = fields
		}
		postMessage.Attachments = []slack.Attachment{attachment}
	}

	_, _, err := s.Client.PostMessage(message.Channel, message.Message, postMessage)
	return err
}
// createMessage generates the message to post to Slack.
func createMessage(p Plugin, user *slack.User) slack.PostMessageParameters {
	var messageOptions MessageOptions
	var color string
	var messageTitle string

	// Determine if the build was a success
	if p.Build.Status == "success" {
		messageOptions = p.Config.Success
		color = "good"
		messageTitle = "Build succeeded"
	} else {
		messageOptions = p.Config.Failure
		color = "danger"
		messageTitle = "Build failed"
	}

	// setup the message
	messageParams := slack.PostMessageParameters{
		Username: messageOptions.Username,
	}

	if strings.HasPrefix(messageOptions.Icon, "http") {
		log.Info("Icon is a URL")
		messageParams.IconURL = messageOptions.Icon
	} else {
		log.Info("Icon is an emoji")
		messageParams.IconEmoji = messageOptions.Icon
	}

	// setup the payload
	payload := templatePayload{
		Build:     p.Build,
		Repo:      p.Repo,
		BuildLast: p.BuildLast,
		User:      user,
	}

	messageText, err := template.Render(messageOptions.Template, &payload)

	if err != nil {
		log.Error("Could not parse template")
	}

	// create the attachment
	attachment := slack.Attachment{
		Color:     color,
		Text:      messageText,
		Title:     messageTitle,
		TitleLink: p.Build.Link,
	}

	// Add image if any are provided
	imageCount := len(messageOptions.ImageAttachments)

	if imageCount > 0 {
		log.WithFields(log.Fields{
			"count": imageCount,
		}).Info("Choosing from images")
		rand.Seed(time.Now().UTC().UnixNano())
		attachment.ImageURL = messageOptions.ImageAttachments[rand.Intn(imageCount)]
	}

	messageParams.Attachments = []slack.Attachment{attachment}

	return messageParams
}
Exemple #8
0
func (c *LogCommand) Run(m *sl.MessageEvent, args ...string) {
	loggers := system.LoggerHookInstance.GetRecords()

	if len(args) == 0 {
		params := sl.NewPostMessageParameters()
		params.Attachments = []sl.Attachment{sl.Attachment{
			Color:  "good",
			Fields: []sl.AttachmentField{},
		}}

		for name := range loggers {
			params.Attachments[0].Fields = append(params.Attachments[0].Fields, sl.AttachmentField{
				Title: name,
			})
		}

		c.SendPostMessage(m.Channel, "Available components", params)
		return
	}

	showItemsCount := system.MaxItems
	if len(args) == 2 {
		var err error
		if showItemsCount, err = strconv.Atoi(args[1]); err != nil {
			c.SendMessage(m.Channel, "Specified number of records to display is not a number")
			return
		}
	}

	component, ok := loggers[args[0]]
	if !ok {
		c.SendMessagef(m.Channel, "Component *%s* does't exists", args[0])
		return
	}

	if len(component) == 0 {
		c.SendMessagef(m.Channel, "Log empty for *%s* component", args[0])
		return
	}

	skip := -1
	if showItemsCount < len(component) {
		skip = len(component) - showItemsCount
	} else {
		showItemsCount = len(component)
	}

	var (
		color      string
		index      int64
		attachment sl.Attachment
	)

	params := sl.NewPostMessageParameters()
	params.Attachments = make([]sl.Attachment, showItemsCount)

	for i, c := range component {
		if i < skip {
			continue
		}

		switch c.Level {
		case logrus.DebugLevel:
			color = "#999999"
		case logrus.InfoLevel:
			color = "#5bc0de"
		case logrus.WarnLevel:
			color = "warning"
		case logrus.ErrorLevel:
			color = "danger"
		case logrus.FatalLevel:
			color = "danger"
		case logrus.PanicLevel:
			color = "danger"
		default:
			color = "good"
		}

		attachment = sl.Attachment{
			Color:  color,
			Title:  c.Time.Format(time.RFC1123Z),
			Text:   c.Message,
			Fields: []sl.AttachmentField{},
		}

		for field, value := range component[i].Data {
			if field == "component" {
				continue
			}

			attachment.Fields = append(attachment.Fields, sl.AttachmentField{
				Title: field,
				Value: fmt.Sprintf("%v", value),
				Short: true,
			})
		}

		params.Attachments[index] = attachment
		index = index + 1
	}

	c.SendPostMessage(m.Channel, fmt.Sprintf("Show last *%d* entries for *%s* component", showItemsCount, args[0]), params)
}
Exemple #9
0
func (s *Client) sendMessage(issue *redmine.Issue, channel string) (err error) {
	params := slackapi.PostMessageParameters{}
	params.IconURL = botLogo
	params.Username = "******"

	fields := make([]slackapi.AttachmentField, 6)
	var idx int = 3

	fields[0] = slackapi.AttachmentField{
		Title: "Project",
		Value: issue.Project.Name,
		Short: true,
	}
	fields[1] = slackapi.AttachmentField{
		Title: "Status",
		Value: issue.Status.Name,
		Short: true,
	}
	fields[2] = slackapi.AttachmentField{
		Title: "Author",
		Value: issue.Author.Name,
		Short: true,
	}
	if issue.AssignedTo != nil {
		fields[idx] = slackapi.AttachmentField{
			Title: "Assigned To",
			Value: issue.AssignedTo.Name,
			Short: true,
		}
		idx += 1
	}
	if issue.Category != nil {
		fields[idx] = slackapi.AttachmentField{
			Title: "Category",
			Value: issue.Category.Name,
			Short: true,
		}
		idx += 1
	}
	if issue.Version != nil {
		fields[idx] = slackapi.AttachmentField{
			Title: "Version",
			Value: issue.Version.Name,
			Short: true,
		}
	}

	var title string
	if issue.Tracker != nil {
		title = fmt.Sprintf("%s #%d: %s", issue.Tracker.Name, issue.Id, issue.Subject)
	} else {
		title = fmt.Sprintf("#%d: %s", issue.Id, issue.Subject)
	}

	attachment := slackapi.Attachment{
		Title:     title,
		TitleLink: s.redmine.GetIssueUrl(issue),
		Fields:    fields,
	}

	if s.redmine.IssueIsClosed(issue) {
		attachment.Color = "good"
	} else if s.redmine.IssueInHighPriority(issue) {
		attachment.Color = "danger"
	}

	params.Attachments = []slackapi.Attachment{attachment}

	_, _, err = s.slack.PostMessage(channel, "", params)

	return err
}
func main() {

	slack_token := os.Getenv("SLACK_TOKEN")
	slack_group := os.Getenv("SLACK_GROUP")
	card_no := os.Getenv("CARD_NO")
	if slack_token == "" || slack_group == "" || card_no == "" {
		log.Fatal("SLACK_TOKEN=xxxx-1111111111-1111111111-11111111111-111111 SLACK_GROUP=GXXXXXXXX CARD_NO=1111222233334444 ./go-ubot-oddday-checker (version: " + version.Version + ")")
	}

	res, err := goreq.Request{Uri: UBOT_ODDDAY_URL}.Do()
	if err != nil {
		log.Fatal(err)
	}
	doc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		log.Fatal(err)
	}

	tbCode, found := doc.Find("#tbCode").Attr("value")
	if !found {
		log.Error("Cannot find tbCode.")
		return
	}

	viewstate, found := doc.Find("#__VIEWSTATE").Attr("value")
	if !found {
		log.Error("Cannot find viewstate.")
		return
	}

	eventvalidation, found := doc.Find("#__EVENTVALIDATION").Attr("value")
	if !found {
		log.Error("Cannot find eventvalidation.")
		return
	}

	form := url.Values{}
	form.Add("__EVENTTARGET", "")
	form.Add("__EVENTARGUMENT", "")
	form.Add("__VIEWSTATE", viewstate)
	form.Add("tbCode", tbCode)
	form.Add("__CALLBACKID", "__Page")
	form.Add("__CALLBACKPARAM", "QRY%%"+card_no+"%%"+tbCode+"%%"+tbCode+"%%")
	form.Add("__EVENTVALIDATION", eventvalidation)

	res, err = goreq.Request{
		Method:      "POST",
		Uri:         UBOT_ODDDAY_URL,
		UserAgent:   "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0",
		ContentType: "application/x-www-form-urlencoded",
		Body:        form.Encode(),
	}.WithHeader("Referer", UBOT_ODDDAY_URL).Do()
	if err != nil {
		log.Fatal(err)
	}
	body, _ := res.Body.ToString()

	// Parse the HTML into nodes
	rp := regexp.MustCompile(`LOGINOK@@[^@]+@@([^@]+)@@[^@]+`)
	m := rp.FindStringSubmatch(body)
	if m == nil {
		log.Fatalf("Cannot find expected response: %s", body)
	}

	log.Debugf("Response: %s", m[1])

	doc, err = goquery.NewDocumentFromReader(strings.NewReader(m[1]))
	if err != nil {
		log.Fatal(err)
	}

	api := slack.New(slack_token)
	mParams := slack.PostMessageParameters{}
	attachment := slack.Attachment{}

	doc.Find("tr").Each(func(i int, s *goquery.Selection) {
		sel := s.Find("td")
		month := strings.TrimSpace(sel.Nodes[0].FirstChild.Data)
		count := strings.TrimSpace(sel.Nodes[1].FirstChild.Data)
		money := strings.TrimSpace(sel.Nodes[2].FirstChild.Data)
		log.Debugf("%s,%s,%s", month, count, money)
		field := slack.AttachmentField{
			Title: month,
			Value: count + " (" + money + ")",
		}
		attachment.Fields = append(attachment.Fields, field)
	})

	// Query all logs in past 1 month
	hParams := slack.NewHistoryParameters()
	hParams.Oldest = fmt.Sprint(time.Now().AddDate(0, -1, 0).Unix())
	history, err := api.GetGroupHistory(slack_group, hParams)
	if err != nil {
		log.Fatal(err)
	}
	for _, msg := range history.Messages {
		if msg.Text == TITLE {
			for _, _attachement := range msg.Attachments {
				// Compare attachment
				if reflect.DeepEqual(_attachement, attachment) {
					log.Debug("Found exist in slack. Skip.")
					return
				}
			}
		}
	}

	// Notify new message
	mParams.Attachments = []slack.Attachment{attachment}
	_, _, err = api.PostMessage(slack_group, TITLE, mParams)
	if err != nil {
		log.Fatal(err)
	}
}