Skip to content

Commit

Permalink
New feature: Telegram Notifier (#2503)
Browse files Browse the repository at this point in the history
Co-authored-by: Tom Limoncelli <tlimoncelli@stackoverflow.com>
  • Loading branch information
chrisbrownie and tlimoncelli committed Aug 29, 2023
1 parent 8bf996b commit e26afaf
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions documentation/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ Please see the [Teams documentation](https://docs.microsoft.com/en-us/microsoftt

Configure `teams_url` to this webhook.

### Telegram

If you want to use the [Telegram](https://telegram.org/) integration, you need to create a Telegram bot and obtain a Bot Token, as well as a Chat ID. Get a Bot Token by contacting [@BotFather](https://telegram.me/botfather), and a Chat ID by contacting [@myidbot](https://telegram.me/myidbot).

Configure `telegram_bot_token` and `telegram_chat_id` to these values.

### Bonfire

This is Stack Overflow's built in chat system. This is probably not useful for most people.
Expand Down
56 changes: 56 additions & 0 deletions pkg/notifications/telegram.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package notifications

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
)

func init() {
initers = append(initers, func(cfg map[string]string) Notifier {
if bot_token, ok := cfg["telegram_bot_token"]; ok {
if chat_id, ok := cfg["telegram_chat_id"]; ok {
notifier := &telegramNotifier{
BOT_TOKEN: bot_token,
CHAT_ID: chat_id,
}
return notifier
}
}
return nil
})
}

// telegramNotifier sends notifications to Telegram
type telegramNotifier struct {
BOT_TOKEN string
CHAT_ID string
}

func (s *telegramNotifier) Notify(domain, provider, msg string, err error, preview bool) {
var payload struct {
ChatID int64 `json:"chat_id"`
Text string `json:"text"`
}

var url = fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", s.BOT_TOKEN)

payload.ChatID, _ = strconv.ParseInt(s.CHAT_ID, 10, 64)

if preview {
payload.Text = fmt.Sprintf(`DNSControl preview: %s[%s] -** %s`, domain, provider, msg)
} else if err != nil {
payload.Text = fmt.Sprintf(`DNSControl ERROR running correction on %s[%s] -** (%s) Error: %s`, domain, provider, msg, err)
} else {
payload.Text = fmt.Sprintf(`DNSControl successfully ran correction for **%s[%s]** - %s`, domain, provider, msg)
}

marshaled_payload, _ := json.Marshal(payload)

_, _ = http.Post(url, "application/json", bytes.NewBuffer(marshaled_payload))

}

func (s *telegramNotifier) Done() {}

0 comments on commit e26afaf

Please sign in to comment.