Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
/.release
/.tarballs
/vendor
/.idea
*.iml

!.golangci.yml
!/cli/testdata/*.yml
Expand Down
4 changes: 2 additions & 2 deletions asset/assets_vfsdata.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 18 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -503,6 +503,21 @@ func (c *Config) UnmarshalYAML(unmarshal func(any) error) error {
ogc.APIKeyFile = c.Global.OpsGenieAPIKeyFile
}
}
for _, oa := range rcv.OnebotConfigs {
if oa.HTTPConfig == nil {
oa.HTTPConfig = c.Global.HTTPConfig
}
if oa.APIURL == nil {
if c.Global.OnebotAPIURL == nil {
return errors.New("no global onebot URL set")
}
oa.APIURL = c.Global.WeChatAPIURL
}
if !strings.HasSuffix(oa.APIURL.Path, "/") {
oa.APIURL.Path += "/"
}
}

for _, wcc := range rcv.WechatConfigs {
if wcc.HTTPConfig == nil {
wcc.HTTPConfig = c.Global.HTTPConfig
Expand Down Expand Up @@ -736,6 +751,7 @@ func DefaultGlobalConfig() GlobalConfig {
SMTPTLSConfig: &defaultSMTPTLSConfig,
PagerdutyURL: mustParseURL("https://events.pagerduty.com/v2/enqueue"),
OpsGenieAPIURL: mustParseURL("https://api.opsgenie.com/"),
OnebotAPIURL: mustParseURL("http://127.0.0.1:3000"),
WeChatAPIURL: mustParseURL("https://qyapi.weixin.qq.com/cgi-bin/"),
VictorOpsAPIURL: mustParseURL("https://alert.victorops.com/integrations/generic/20131114/alert/"),
TelegramAPIUrl: mustParseURL("https://api.telegram.org"),
Expand Down Expand Up @@ -859,6 +875,7 @@ type GlobalConfig struct {
OpsGenieAPIURL *URL `yaml:"opsgenie_api_url,omitempty" json:"opsgenie_api_url,omitempty"`
OpsGenieAPIKey Secret `yaml:"opsgenie_api_key,omitempty" json:"opsgenie_api_key,omitempty"`
OpsGenieAPIKeyFile string `yaml:"opsgenie_api_key_file,omitempty" json:"opsgenie_api_key_file,omitempty"`
OnebotAPIURL *URL `yaml:"onebot_api_url,omitempty" json:"onebot_api_url,omitempty"`
WeChatAPIURL *URL `yaml:"wechat_api_url,omitempty" json:"wechat_api_url,omitempty"`
WeChatAPISecret Secret `yaml:"wechat_api_secret,omitempty" json:"wechat_api_secret,omitempty"`
WeChatAPICorpID string `yaml:"wechat_api_corp_id,omitempty" json:"wechat_api_corp_id,omitempty"`
Expand Down Expand Up @@ -1020,6 +1037,7 @@ type Receiver struct {
WebhookConfigs []*WebhookConfig `yaml:"webhook_configs,omitempty" json:"webhook_configs,omitempty"`
OpsGenieConfigs []*OpsGenieConfig `yaml:"opsgenie_configs,omitempty" json:"opsgenie_configs,omitempty"`
WechatConfigs []*WechatConfig `yaml:"wechat_configs,omitempty" json:"wechat_configs,omitempty"`
OnebotConfigs []*OnebotConfig `yaml:"onebot_configs,omitempty" json:"onebot_configs,omitempty"`
PushoverConfigs []*PushoverConfig `yaml:"pushover_configs,omitempty" json:"pushover_configs,omitempty"`
VictorOpsConfigs []*VictorOpsConfig `yaml:"victorops_configs,omitempty" json:"victorops_configs,omitempty"`
SNSConfigs []*SNSConfig `yaml:"sns_configs,omitempty" json:"sns_configs,omitempty"`
Expand Down
1 change: 1 addition & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -937,6 +937,7 @@ func TestEmptyFieldsAndRegex(t *testing.T) {
SMTPRequireTLS: true,
PagerdutyURL: mustParseURL("https://events.pagerduty.com/v2/enqueue"),
OpsGenieAPIURL: mustParseURL("https://api.opsgenie.com/"),
OnebotAPIURL: mustParseURL("http://127.0.0.1:3000"),
WeChatAPIURL: mustParseURL("https://qyapi.weixin.qq.com/cgi-bin/"),
VictorOpsAPIURL: mustParseURL("https://alert.victorops.com/integrations/generic/20131114/alert/"),
TelegramAPIUrl: mustParseURL("https://api.telegram.org"),
Expand Down
47 changes: 46 additions & 1 deletion config/notifiers.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,15 @@ var (
Source: `{{ template "opsgenie.default.source" . }}`,
// TODO: Add a details field with all the alerts.
}

// DefaultOnebotConfig defines default values for onebot configurations.
DefaultOnebotConfig = OnebotConfig{
NotifierConfig: NotifierConfig{
VSendResolved: false,
},
Message: `{{ template "onebot.default.message" . }}`,
ToUser: `{{ template "onebot.default.to_user" . }}`,
ToParty: `{{ template "onebot.default.to_party" . }}`,
}
// DefaultWechatConfig defines default values for wechat configurations.
DefaultWechatConfig = WechatConfig{
NotifierConfig: NotifierConfig{
Expand Down Expand Up @@ -330,6 +338,43 @@ func (c *EmailConfig) UnmarshalYAML(unmarshal func(any) error) error {
return nil
}

type OnebotConfig struct {
NotifierConfig `yaml:",inline" json:",inline"`

HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"`

APIURL *URL `yaml:"api_url,omitempty" json:"api_url,omitempty"`
ToUser string `yaml:"to_user,omitempty" json:"to_user,omitempty"`
ToParty string `yaml:"to_party,omitempty" json:"to_party,omitempty"`
Message string `yaml:"message,omitempty" json:"message,omitempty"`
MessageType string `yaml:"message_type,omitempty" json:"message_type,omitempty"`
}

const onebotValidTypesRe = `^(text|raw)$`

var onebotTypeMatcher = regexp.MustCompile(wechatValidTypesRe)

func (c *OnebotConfig) UnmarshalYAML(unmarshal func(any) error) error {
*c = DefaultOnebotConfig
type plain OnebotConfig
if err := unmarshal((*plain)(c)); err != nil {
return err
}
if c.APIURL == nil || c.APIURL.String() == "" {
return errors.New("`api_url` must be configured")
}
if c.ToUser == "" && c.ToParty == "" {
return errors.New("`to_user` or `to_party` must be configured")
}
if c.MessageType == "" {
c.MessageType = "text"
}
if !onebotTypeMatcher.MatchString(c.MessageType) {
return fmt.Errorf("onebot message type %q does not match valid options %s", c.MessageType, onebotValidTypesRe)
}
return nil
}

// PagerdutyConfig configures notifications via PagerDuty.
type PagerdutyConfig struct {
NotifierConfig `yaml:",inline" json:",inline"`
Expand Down
4 changes: 4 additions & 0 deletions config/receiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package receiver
import (
"log/slog"

"github.com/prometheus/alertmanager/notify/onebot"
commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/promslog"

Expand Down Expand Up @@ -74,6 +75,9 @@ func BuildReceiverIntegrations(nc config.Receiver, tmpl *template.Template, logg
for i, c := range nc.OpsGenieConfigs {
add("opsgenie", i, c, func(l *slog.Logger) (notify.Notifier, error) { return opsgenie.New(c, tmpl, l, httpOpts...) })
}
for i, c := range nc.OnebotConfigs {
add("onebot", i, c, func(l *slog.Logger) (notify.Notifier, error) { return onebot.New(c, tmpl, l, httpOpts...) })
}
for i, c := range nc.WechatConfigs {
add("wechat", i, c, func(l *slog.Logger) (notify.Notifier, error) { return wechat.New(c, tmpl, l, httpOpts...) })
}
Expand Down
139 changes: 139 additions & 0 deletions notify/onebot/onebot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
// Copyright 2025 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package onebot

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strings"

"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
commoncfg "github.com/prometheus/common/config"
)

// Notifier implements a Notifier for wechat notifications.
type Notifier struct {
conf *config.OnebotConfig
tmpl *template.Template
logger *slog.Logger
client *http.Client
}

// New returns a new Wechat notifier.
func New(c *config.OnebotConfig, t *template.Template, l *slog.Logger, httpOpts ...commoncfg.HTTPClientOption) (*Notifier, error) {
client, err := commoncfg.NewClientFromConfig(*c.HTTPConfig, "onebot", httpOpts...)
if err != nil {
return nil, err
}

return &Notifier{conf: c, tmpl: t, logger: l, client: client}, nil
}

func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {
key, err := notify.ExtractGroupKey(ctx)
if err != nil {
return false, err
}

n.logger.Debug("extracted group key", "key", key)
data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)
tmpl := notify.TmplText(n.tmpl, data, &err)
if err != nil {
return false, err
}
toUser := tmpl(n.conf.ToUser)
if err != nil {
return false, err
}
toParty := tmpl(n.conf.ToParty)
if err != nil {
return false, err
}
msg := tmpl(n.conf.Message)
if err != nil {
return false, err
}
var messages []map[string]any
if msg == "" {
return false, errors.New("message is empty")
}
if n.conf.MessageType == "raw" {
if err := json.Unmarshal([]byte(msg), &messages); err != nil {
return false, err
}
} else {
messages = append(messages, map[string]any{
"type": "text",
"data": map[string]any{
"text": msg,
},
})
}

var resp *http.Response
if toUser != "" {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(map[string]any{
"user_id": toUser,
"message": messages,
}); err != nil {
return false, err
}
url := n.conf.APIURL.Copy()
url.Path = strings.TrimSuffix(url.Path, "/") + "/send_private_msg"
resp, err = notify.PostJSON(ctx, n.client, url.String(), &buf)
} else if toParty != "" {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(map[string]any{
"group_id": toParty,
"message": messages,
}); err != nil {
return false, err
}
url := n.conf.APIURL.Copy()
url.Path = strings.TrimSuffix(url.Path, "/") + "/send_group_msg"
resp, err = notify.PostJSON(ctx, n.client, url.String(), &buf)
} else {
return false, errors.New("no group_id or to_user specified")
}
if err != nil {
return true, notify.RedactURL(err)
}
defer notify.Drain(resp)
if resp.StatusCode != 200 {
return true, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), fmt.Errorf("unexpected status code %v", resp.StatusCode))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return true, err
}
n.logger.Debug(string(body), "incident", key)
var onebotResp map[string]any
if err := json.Unmarshal(body, &onebotResp); err != nil {
return true, err
}
if onebotResp["status"] == "ok" {
return false, nil
}
return false, errors.New(fmt.Sprintf("%v", onebotResp["message"]))
}
Loading