2021-03-31 01:38:34 +02:00
package telegram
import (
"fmt"
"net/http"
2021-10-08 03:28:04 +02:00
"github.com/TwiN/gatus/v3/alerting/alert"
"github.com/TwiN/gatus/v3/alerting/provider/custom"
"github.com/TwiN/gatus/v3/core"
2021-03-31 01:38:34 +02:00
)
// AlertProvider is the configuration necessary for sending an alert using Telegram
type AlertProvider struct {
Token string ` yaml:"token" `
ID string ` yaml:"id" `
2021-05-16 03:31:32 +02:00
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
2021-05-19 04:29:15 +02:00
DefaultAlert * alert . Alert ` yaml:"default-alert" `
2021-03-31 01:38:34 +02:00
}
// IsValid returns whether the provider's configuration is valid
func ( provider * AlertProvider ) IsValid ( ) bool {
return len ( provider . Token ) > 0 && len ( provider . ID ) > 0
}
// ToCustomAlertProvider converts the provider into a custom.AlertProvider
2021-05-19 04:29:15 +02:00
func ( provider * AlertProvider ) ToCustomAlertProvider ( service * core . Service , alert * alert . Alert , result * core . Result , resolved bool ) * custom . AlertProvider {
2021-03-31 01:38:34 +02:00
var message , results string
if resolved {
message = fmt . Sprintf ( "An alert for *%s* has been resolved:\\n—\\n _healthcheck passing successfully %d time(s) in a row_\\n— " , service . Name , alert . FailureThreshold )
} else {
message = fmt . Sprintf ( "An alert for *%s* has been triggered:\\n—\\n _healthcheck failed %d time(s) in a row_\\n— " , service . Name , alert . FailureThreshold )
}
for _ , conditionResult := range result . ConditionResults {
var prefix string
if conditionResult . Success {
prefix = "✅"
} else {
prefix = "❌"
}
results += fmt . Sprintf ( "%s - `%s`\\n" , prefix , conditionResult . Condition )
}
var text string
2021-05-16 03:31:32 +02:00
if len ( alert . GetDescription ( ) ) > 0 {
text = fmt . Sprintf ( "⛑ *Gatus* \\n%s \\n*Description* \\n_%s_ \\n\\n*Condition results*\\n%s" , message , alert . GetDescription ( ) , results )
2021-03-31 01:38:34 +02:00
} else {
text = fmt . Sprintf ( "⛑ *Gatus* \\n%s \\n*Condition results*\\n%s" , message , results )
}
return & custom . AlertProvider {
URL : fmt . Sprintf ( "https://api.telegram.org/bot%s/sendMessage" , provider . Token ) ,
Method : http . MethodPost ,
2021-04-15 05:01:40 +02:00
Body : fmt . Sprintf ( ` { "chat_id": "%s", "text": "%s", "parse_mode": "MARKDOWN"} ` , provider . ID , text ) ,
2021-03-31 01:38:34 +02:00
Headers : map [ string ] string { "Content-Type" : "application/json" } ,
}
}
2021-05-16 03:31:32 +02:00
// GetDefaultAlert returns the provider's default alert configuration
2021-05-19 04:29:15 +02:00
func ( provider AlertProvider ) GetDefaultAlert ( ) * alert . Alert {
2021-05-16 03:31:32 +02:00
return provider . DefaultAlert
}