2021-03-31 01:38:34 +02:00
package telegram
import (
"fmt"
"net/http"
2021-05-18 22:29:15 -04:00
"github.com/TwinProduction/gatus/alerting/alert"
2021-03-31 01:38:34 +02:00
"github.com/TwinProduction/gatus/alerting/provider/custom"
"github.com/TwinProduction/gatus/core"
)
// AlertProvider is the configuration necessary for sending an alert using Telegram
type AlertProvider struct {
Token string `yaml:"token"`
ID string `yaml:"id"`
2021-05-15 21:31:32 -04:00
// DefaultAlert is the default alert configuration to use for services with an alert of the appropriate type
2021-05-18 22:29:15 -04: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-18 22:29:15 -04: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-15 21:31:32 -04: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-14 23:01:40 -04: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-15 21:31:32 -04:00
// GetDefaultAlert returns the provider's default alert configuration
2021-05-18 22:29:15 -04:00
func ( provider AlertProvider ) GetDefaultAlert () * alert . Alert {
2021-05-15 21:31:32 -04:00
return provider . DefaultAlert
}