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 #2
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,
		},
	})
}
Exemple #3
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
}
Exemple #4
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)
}
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)
	}
}