Example #1
0
func main() {
	// prepare host:port to listen to
	bind := fmt.Sprintf("%s:%s", "", "8000")
	// just predefine the err variable to avoid some problems
	var err error
	// create an instance of Telegram Bot Api
	bot, err = telegram.NewBotAPI(BOTAPIKEY)
	if err != nil {
		log.Panic(err)
	}

	// Compile the regexpression to match /action@botname
	actionSeprator := regexp.MustCompile(`^\/[\da-zA-z@]+`)

	// prepare the Gin Router
	router := gin.Default()
	// on request
	router.POST("/", func(c *gin.Context) {
		buf, err := ioutil.ReadAll(c.Request.Body)

		update := telegram.Update{}
		json.Unmarshal(buf, &update)
		if err != nil {
			c.String(500, err.Error())
			return
		}
		// Extracting action name from text
		botName := ""
		act := actionSeprator.FindString(update.Message.Text)
		actLength := len(act)
		atsignPos := strings.Index(act, "@")
		if atsignPos != -1 {
			botName = act[atsignPos+1:]
			act = act[:atsignPos]
		}

		if botName != "" && botName != BOTNAME {
			c.String(200, "Wrong bot")
			return
		}
		act = strings.TrimPrefix(act, "/")
		act = strings.ToLower(act)
		update.Message.Text = update.Message.Text[actLength:]

		// check if the requested action exist or not
		_, has := actions[act]
		if has {
			err = actions[act](c, &update)
			if err != nil {
				c.String(500, err.Error())
				return
			}
		}

		c.String(200, "done")

	})

	router.Run(bind)
}
Example #2
0
// Telegram is the message provider meant to be used in development of rule sets.
func Telegram(token string) *providerTelegram {
	telegram := &providerTelegram{
		token: token,
		in:    make(chan messages.Message),
		out:   make(chan messages.Message),
	}

	tg, err := tgbotapi.NewBotAPI(token)
	if err != nil {
		telegram.err = err
		return telegram
	}

	log.Println("telegram: logged as", tg.Self.UserName)
	telegram.tg = tg

	go telegram.intakeLoop()
	go telegram.dispatchLoop()
	return telegram
}
Example #3
0
//SendEvents implements Sender interface Send
func (sender *Sender) SendEvents(events notifier.EventsData, contact notifier.ContactData, trigger notifier.TriggerData, throttled bool) error {
	bot, err := tgbotapi.NewBotAPI(sender.APIToken)
	if err != nil {
		return fmt.Errorf("Failed to init telegram api: %s", err.Error())
	}

	var message bytes.Buffer

	state := events.GetSubjectState()
	tags := trigger.GetTags()

	message.WriteString(fmt.Sprintf("%s %s %s (%d)\n\n", state, trigger.Name, tags, len(events)))

	for _, event := range events {
		value := strconv.FormatFloat(event.Value, 'f', -1, 64)
		message.WriteString(fmt.Sprintf("%s: %s = %s (%s to %s)\n", time.Unix(event.Timestamp, 0).Format("15:04"), event.Metric, value, event.OldState, event.State))
	}

	if len(events) > 5 {
		message.WriteString(fmt.Sprintf("\n...and %d more events.", len(events)-5))
	}

	if throttled {
		message.WriteString("\nPlease, fix your system or tune this trigger to generate less events.")
	}

	log.Debug("Calling telegram api with chat_id %s and message body %s", contact.Value, message)

	telegramParams := url.Values{}
	telegramParams.Set("chat_id", contact.Value)
	telegramParams.Set("text", message.String())
	telegramParams.Set("disable_web_page_preview", "true")

	_, err = bot.MakeRequest("sendMessage", telegramParams)
	if err != nil {
		return fmt.Errorf("Failed to send message to telegram contact %s: %s", contact.Value, err.Error())
	}
	return nil

}