-
Notifications
You must be signed in to change notification settings - Fork 0
/
teams.go
139 lines (111 loc) · 2.55 KB
/
teams.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/andrew-d/go-termutil"
"github.com/shu-go/xn/charconv"
)
type teamsCmd struct {
_ struct{} `help:"notify by Microsoft Teams"`
Send teamsSendCmd
Auth teamsAuthCmd
}
var (
teamsWebhookURL string = ""
)
type teamsSendCmd struct {
_ struct{} `help:"send a notification"`
Text string
}
type teamsAuthCmd struct {
_ struct{} `help:"authenticate"`
WebhookURL string `cli:"url=INCOMING_WEBHOOK_URL" help:"Workflows Webhook URL of your channel"`
}
func (c teamsAuthCmd) Run(global globalCmd, args []string) error {
config, _ := loadConfig(global.Config)
var argWebhookURL string
if len(args) >= 1 {
argWebhookURL = args[0]
}
//
// prepare
//
teamsWebhookURL = firstNonEmpty(
argWebhookURL,
config.Teams.WebhookURL,
os.Getenv("TEAMS_WEBHOOK_URL"),
teamsWebhookURL)
if teamsWebhookURL == "" {
fmt.Fprintf(os.Stderr, "Workflows Webhook URL is required.\n")
return nil
}
config.Teams.WebhookURL = teamsWebhookURL
saveConfig(config, global.Config)
return nil
}
func (c teamsSendCmd) Run(global globalCmd, args []string) error {
config, _ := loadConfig(global.Config)
if config.Teams.WebhookURL == "" {
return fmt.Errorf("auth first")
}
for _, v := range args {
if len(c.Text) > 0 {
c.Text += "\n"
}
c.Text += v
}
if !termutil.Isatty(os.Stdin.Fd()) {
bytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
bytes = []byte{}
}
str, _, err := charconv.Convert(bytes)
if err != nil {
return fmt.Errorf("failed to convert charset: %v", err)
}
if len(c.Text) == 0 {
c.Text = str
} else if len(bytes) != 0 {
c.Text += "\n" + str
}
}
c.Text = strings.ReplaceAll(c.Text, "\\n", "\n")
if len(c.Text) == 0 {
return nil
}
body := &bytes.Buffer{}
fmt.Fprintf(body, `{
"type": "message",
"attachments":[
{
"contentType":"application/vnd.microsoft.card.adaptive",
"contentUrl":null,
"content":{
"$schema":"http://adaptivecards.io/schemas/adaptive-card.json",
"type":"AdaptiveCard",
"version":"1.4",
"body":[
{ "type": "TextBlock", "wrap": true, "text": %q }
]
}
}
]
}`, c.Text)
_, err := http.Post(config.Teams.WebhookURL, "application/json", body)
if err != nil {
return nil
}
/*
buf, _ := ioutil.ReadAll(response.Body)
println(string(buf))
response.Body.Close()
*/
return err
}
func init() {
appendCommand(&teamsCmd{}, "teams, tm", "")
}