package notify import ( "context" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "math/big" "net/http" "net/url" "strconv" "strings" "time" ) // Chat services and messengers, including WhatsApp gateways and home // automation. func text(name string, required bool) Field { return Field{Name: name, Required: required, Kind: "text"} } func secret(name string, required bool) Field { return Field{Name: name, Required: required, Secret: true, Kind: "text"} } func urlField(name string, required bool, def string) Field { return Field{Name: name, Required: required, Kind: "url", Default: def} } // secretURL is a URL that carries a credential, such as a webhook. func secretURL(name string) Field { return Field{Name: name, Required: true, Secret: true, Kind: "url"} } var messageTypeField = Field{Name: "message_type", Kind: "select", Options: []string{"private", "group"}, Default: "private"} var chatProviders = []Provider{ {Type: "bale", Group: "chat", Fields: []Field{secret("bot_token", true), text("chat_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, "https://tapi.bale.ai/bot"+cfg["bot_token"]+"/sendMessage", nil, map[string]any{"chat_id": cfg["chat_id"], "text": m.text()}) }}, {Type: "bitrix", Group: "chat", Fields: []Field{secretURL("webhook_url"), text("user_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { color := "#b73419" if m.Event == Resolved { color = "#67b518" } _, err := c.get(ctx, trimURL(cfg["webhook_url"])+"/im.notify.system.add.json", nil, url.Values{ "user_id": {cfg["user_id"]}, "message": {"[B]" + m.Title + "[/B]"}, "ATTACH[COLOR]": {color}, "ATTACH[BLOCKS][0][MESSAGE]": {m.Body + "\n" + m.URL}, }) return err }}, {Type: "clickup", Group: "chat", Fields: []Field{secret("api_token", true), text("workspace_id", true), text("channel_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { u := "https://api.clickup.com/api/v3/workspaces/" + url.PathEscape(cfg["workspace_id"]) + "/chat/channels/" + url.PathEscape(cfg["channel_id"]) + "/messages" return c.json(ctx, http.MethodPost, u, http.Header{"Authorization": {cfg["api_token"]}}, map[string]any{"type": "message", "content": "**" + m.Title + "**\n" + m.Body + "\n" + m.URL, "content_format": "text/md"}) }}, {Type: "dingtalk", Group: "chat", Fields: []Field{secretURL("webhook_url"), secret("sign_secret", false)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { u := cfg["webhook_url"] if key := cfg["sign_secret"]; key != "" { // Robots with "additional signature" security check the // timestamp signed with the secret. ts := strconv.FormatInt(time.Now().UnixMilli(), 10) mac := hmac.New(sha256.New, []byte(key)) mac.Write([]byte(ts + "\n" + key)) u += "×tamp=" + ts + "&sign=" + url.QueryEscape(base64.StdEncoding.EncodeToString(mac.Sum(nil))) } reply, err := c.callJSON(ctx, http.MethodPost, u, nil, map[string]any{"msgtype": "text", "text": map[string]any{"content": m.text()}}) return replyCheck(reply, err, func(v map[string]any) string { if str(v["errcode"]) != "0" { return "DingTalk: " + str(v["errmsg"]) } return "" }) }}, {Type: "feishu", Group: "chat", Fields: []Field{secretURL("webhook_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { reply, err := c.callJSON(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"msg_type": "text", "content": map[string]any{"text": m.text()}}) return replyCheck(reply, err, func(v map[string]any) string { if code := str(v["code"]); code != "" && code != "0" { return "Feishu: " + str(v["msg"]) } return "" }) }}, {Type: "fluxer", Group: "chat", Fields: []Field{secretURL("webhook_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"username": "UptimeSebi", "content": m.text()}) }}, {Type: "kook", Group: "chat", Fields: []Field{secret("bot_token", true), text("channel_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { reply, err := c.callJSON(ctx, http.MethodPost, "https://www.kookapp.cn/api/v3/message/create", http.Header{"Authorization": {"Bot " + cfg["bot_token"]}}, map[string]any{"target_id": cfg["channel_id"], "content": m.text()}) return replyCheck(reply, err, func(v map[string]any) string { if str(v["code"]) != "0" { return "KOOK: " + str(v["message"]) } return "" }) }}, {Type: "line", Group: "chat", Fields: []Field{secret("access_token", true), text("user_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, "https://api.line.me/v2/bot/message/push", bearer(cfg["access_token"]), map[string]any{"to": cfg["user_id"], "messages": []map[string]any{{"type": "text", "text": m.text()}}}) }}, {Type: "max", Group: "chat", Fields: []Field{secret("bot_token", true), text("chat_id", true), urlField("api_url", false, "https://platform-api.max.ru")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { u := trimURL(or(cfg["api_url"], "https://platform-api.max.ru")) + "/messages?chat_id=" + url.QueryEscape(cfg["chat_id"]) return c.json(ctx, http.MethodPost, u, http.Header{"Authorization": {cfg["bot_token"]}}, map[string]any{"text": m.text()}) }}, {Type: "milky", Group: "chat", Fields: []Field{urlField("api_url", true, ""), secret("access_token", false), messageTypeField, text("receiver_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // Milky, a QQ bot protocol. id, _ := strconv.ParseInt(cfg["receiver_id"], 10, 64) body := map[string]any{"message": []map[string]any{{"type": "text", "data": map[string]any{"text": m.text()}}}} endpoint := "send_private_message" if cfg["message_type"] == "group" { endpoint, body["group_id"] = "send_group_message", id } else { body["user_id"] = id } return c.json(ctx, http.MethodPost, trimURL(cfg["api_url"])+"/api/"+endpoint, bearer(cfg["access_token"]), body) }}, {Type: "onebot", Group: "chat", Fields: []Field{urlField("api_url", true, ""), secret("access_token", false), messageTypeField, text("receiver_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { body := map[string]any{"auto_escape": true, "message": m.text(), "message_type": "private", "user_id": cfg["receiver_id"]} if cfg["message_type"] == "group" { delete(body, "user_id") body["message_type"], body["group_id"] = "group", cfg["receiver_id"] } return c.json(ctx, http.MethodPost, trimURL(cfg["api_url"])+"/send_msg", bearer(cfg["access_token"]), body) }}, {Type: "onechat", Group: "chat", Fields: []Field{secret("access_token", true), text("receiver_id", true), text("bot_id", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, "https://chat-api.one.th/message/api/v1/push_message", bearer(cfg["access_token"]), map[string]any{"to": cfg["receiver_id"], "bot_id": cfg["bot_id"], "type": "text", "message": m.text()}) }}, {Type: "nextcloudtalk", Group: "chat", Fields: []Field{urlField("server_url", true, ""), text("conversation_token", true), secret("bot_secret", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // Talk bots sign a random value followed by the message. random := randomHex(32) msg := m.text() mac := hmac.New(sha256.New, []byte(cfg["bot_secret"])) mac.Write([]byte(random + msg)) h := http.Header{ "X-Nextcloud-Talk-Bot-Random": {random}, "X-Nextcloud-Talk-Bot-Signature": {hex.EncodeToString(mac.Sum(nil))}, "OCS-APIRequest": {"true"}, } u := trimURL(cfg["server_url"]) + "/ocs/v2.php/apps/spreed/api/v1/bot/" + url.PathEscape(cfg["conversation_token"]) + "/message" return c.json(ctx, http.MethodPost, u, h, map[string]any{"message": msg}) }}, {Type: "pumble", Group: "chat", Fields: []Field{secretURL("webhook_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { color := map[string]string{"down": "#DC3645", "up": "#5BDD8B"}[m.status()] return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{ "attachments": []map[string]any{{"title": m.Title, "text": m.Body + "\n" + m.URL, "color": or(color, "#5BDD8B")}}, }) }}, {Type: "stackfield", Group: "chat", Fields: []Field{secretURL("webhook_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"Title": m.text()}) }}, {Type: "vk", Group: "chat", Fields: []Field{secret("access_token", true), text("peer_id", true), text("api_version", false)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { id, _ := rand.Int(rand.Reader, big.NewInt(1<<31-1)) reply, err := c.form(ctx, "https://api.vk.ru/method/messages.send", nil, url.Values{ "access_token": {cfg["access_token"]}, "v": {or(cfg["api_version"], "5.199")}, "peer_id": {cfg["peer_id"]}, "message": {m.text()}, "random_id": {id.String()}, }) return replyCheck(reply, err, func(v map[string]any) string { if e, ok := v["error"].(map[string]any); ok { return fmt.Sprintf("VK: %s (%s)", str(e["error_msg"]), str(e["error_code"])) } return "" }) }}, {Type: "vkteams", Group: "chat", Fields: []Field{secret("bot_token", true), text("chat_id", true), urlField("api_url", false, "https://myteam.mail.ru")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { reply, err := c.get(ctx, trimURL(or(cfg["api_url"], "https://myteam.mail.ru"))+"/bot/v1/messages/sendText", nil, url.Values{"token": {cfg["bot_token"]}, "chatId": {cfg["chat_id"]}, "text": {m.text()}}) return replyCheck(reply, err, func(v map[string]any) string { if v["ok"] == false { return "VK Teams: " + str(v["description"]) } return "" }) }}, {Type: "wecom", Group: "chat", Fields: []Field{secret("bot_key", true), text("mentioned_mobiles", false)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { t := map[string]any{"content": m.text()} if mobiles := list(cfg["mentioned_mobiles"]); len(mobiles) > 0 { t["mentioned_mobile_list"] = mobiles } reply, err := c.callJSON(ctx, http.MethodPost, "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+url.QueryEscape(cfg["bot_key"]), nil, map[string]any{"msgtype": "text", "text": t}) return replyCheck(reply, err, func(v map[string]any) string { if str(v["errcode"]) != "0" { return "WeCom: " + str(v["errmsg"]) } return "" }) }}, {Type: "yunzhijia", Group: "chat", Fields: []Field{urlField("webhook_url", true, ""), secret("token", true)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { u := cfg["webhook_url"] + "?yzjtype=0&yzjtoken=" + url.QueryEscape(cfg["token"]) reply, err := c.callJSON(ctx, http.MethodPost, u, nil, map[string]any{"content": m.text()}) return replyCheck(reply, err, func(v map[string]any) string { if v["success"] != true { return "Yunzhijia: " + str(v["errmsg"]) } return "" }) }}, {Type: "zohocliq", Group: "chat", Fields: []Field{secretURL("webhook_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{"text": m.text()}) }}, {Type: "threema", Group: "chat", Fields: []Field{ text("gateway_id", true), secret("gateway_secret", true), {Name: "recipient_type", Kind: "select", Options: []string{"identity", "phone", "email"}, Default: "identity"}, text("recipient", true), }, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { v := url.Values{"from": {cfg["gateway_id"]}, "secret": {cfg["gateway_secret"]}, "text": {m.text()}} switch cfg["recipient_type"] { case "phone": v.Set("phone", cfg["recipient"]) case "email": v.Set("email", cfg["recipient"]) default: v.Set("to", cfg["recipient"]) } _, err := c.form(ctx, "https://msgapi.threema.ch/send_simple", nil, v) return err }}, {Type: "evolution", Group: "chat", Fields: []Field{ urlField("api_url", true, ""), secret("api_key", true), text("instance", true), text("recipient", true), }, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // Evolution API, a WhatsApp gateway. u := trimURL(cfg["api_url"]) + "/message/sendText/" + url.PathEscape(cfg["instance"]) return c.json(ctx, http.MethodPost, u, http.Header{"apikey": {cfg["api_key"]}}, map[string]any{"number": cfg["recipient"], "text": m.text()}) }}, {Type: "waha", Group: "chat", Fields: []Field{ urlField("api_url", true, ""), secret("api_key", false), text("session", true), text("chat_id", true), }, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, trimURL(cfg["api_url"])+"/api/sendText", http.Header{"X-Api-Key": {cfg["api_key"]}}, map[string]any{"session": cfg["session"], "chatId": cfg["chat_id"], "text": m.text()}) }}, {Type: "whapi", Group: "chat", Fields: []Field{secret("api_token", true), text("recipient", true), urlField("api_url", false, "https://gate.whapi.cloud")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { return c.json(ctx, http.MethodPost, trimURL(or(cfg["api_url"], "https://gate.whapi.cloud"))+"/messages/text", bearer(cfg["api_token"]), map[string]any{"to": cfg["recipient"], "body": m.text()}) }}, {Type: "openwa", Group: "chat", Fields: []Field{ urlField("api_url", true, ""), secret("api_key", true), text("session", true), text("chat_ids", true), }, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { u := trimURL(cfg["api_url"]) + "/api/sessions/" + url.PathEscape(cfg["session"]) + "/messages/send-text" for _, id := range list(cfg["chat_ids"]) { if err := c.json(ctx, http.MethodPost, u, http.Header{"X-Api-Key": {cfg["api_key"]}}, map[string]any{"chatId": id, "text": m.text()}); err != nil { return err } } return nil }}, {Type: "onesender", Group: "chat", Fields: []Field{ urlField("api_url", true, ""), secret("api_token", true), messageTypeField, text("recipient", true), }, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { to, kind := cfg["recipient"]+"@s.whatsapp.net", "individual" if cfg["message_type"] == "group" { to, kind = cfg["recipient"]+"@g.us", "group" } return c.json(ctx, http.MethodPost, cfg["api_url"], bearer(cfg["api_token"]), map[string]any{ "to": to, "type": "text", "recipient_type": kind, "text": map[string]any{"body": m.text()}, }) }}, {Type: "messenger360", Group: "chat", Fields: []Field{secret("api_token", true), text("recipients", false), text("group_ids", false)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // 360messenger, a WhatsApp gateway. recipients, groups := list(cfg["recipients"]), list(cfg["group_ids"]) if len(recipients)+len(groups) == 0 { return fmt.Errorf("no recipient or group set") } h := bearer(cfg["api_token"]) for _, r := range recipients { if err := c.json(ctx, http.MethodPost, "https://api.360messenger.com/v2/sendMessage", h, map[string]any{"phonenumber": r, "text": m.text()}); err != nil { return err } } for _, g := range groups { if err := c.json(ctx, http.MethodPost, "https://api.360messenger.com/v2/sendGroup", h, map[string]any{"groupId": g, "text": m.text()}); err != nil { return err } } return nil }}, {Type: "nostr", Group: "chat", Fields: []Field{secret("sender_nsec", true), text("recipients", true), text("relays", true)}, send: sendNostr}, {Type: "homeassistant", Group: "chat", Fields: []Field{urlField("server_url", true, ""), secret("access_token", true), text("service", false)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // A notify service such as mobile_app_phone; "notify" reaches // the default ones. u := trimURL(cfg["server_url"]) + "/api/services/notify/" + url.PathEscape(or(cfg["service"], "notify")) body := map[string]any{"title": m.Title, "message": m.Body + "\n" + m.URL} if cfg["service"] != "persistent_notification" { body["data"] = map[string]any{"name": m.Monitor, "status": m.status(), "url": m.URL} } return c.json(ctx, http.MethodPost, u, bearer(cfg["access_token"]), body) }}, {Type: "indigo", Group: "chat", Fields: []Field{urlField("server_url", true, ""), secret("api_key", true), text("variable_id", false), text("action_group_id", false)}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // Indigo home automation: set a variable to the message and run // an action group. variable, _ := strconv.Atoi(cfg["variable_id"]) group, _ := strconv.Atoi(cfg["action_group_id"]) if variable == 0 && group == 0 { return fmt.Errorf("set a variable ID, an action group ID or both") } u := trimURL(cfg["server_url"]) + "/v2/api/command" h := bearer(cfg["api_key"]) if variable != 0 { if err := c.json(ctx, http.MethodPost, u, h, map[string]any{"id": "uptimesebi", "message": "indigo.variable.updateValue", "objectId": variable, "parameters": map[string]any{"value": m.text()}}); err != nil { return err } } if group != 0 { return c.json(ctx, http.MethodPost, u, h, map[string]any{"id": "uptimesebi", "message": "indigo.actionGroup.execute", "objectId": group}) } return nil }}, {Type: "googlesheets", Group: "chat", Fields: []Field{secretURL("webhook_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // A Google Apps Script web app appending rows. return c.json(ctx, http.MethodPost, cfg["webhook_url"], nil, map[string]any{ "timestamp": time.Now().UTC().Format(time.RFC3339), "status": strings.ToUpper(m.status()), "monitorName": or(m.Monitor, "N/A"), "monitorUrl": or(m.Target, "N/A"), "message": m.Title + "\n" + m.Body, }) }}, {Type: "callmebot", Group: "chat", Fields: []Field{secretURL("endpoint_url")}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error { // The URL CallMeBot hands out, with phone and API key. _, err := c.get(ctx, cfg["endpoint_url"], nil, url.Values{"text": {m.text()}}) return err }}, } func randomHex(n int) string { b := make([]byte, n) _, _ = rand.Read(b) return hex.EncodeToString(b) }