-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
plugin.go
135 lines (108 loc) · 2.1 KB
/
plugin.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
package main
import (
"errors"
"fmt"
"log"
"strconv"
"strings"
"gopkg.in/telegram-bot-api.v4"
)
type (
// Repo information.
Repo struct {
Owner string
Name string
}
// Build information.
Build struct {
Event string
Number int
Commit string
Message string
Branch string
Author string
Status string
Link string
}
// Config for the plugin.
Config struct {
Token string
Debug bool
To []string
Message []string
Format string
}
// Plugin values.
Plugin struct {
Repo Repo
Build Build
Config Config
}
)
func trimElement(keys []string) []string {
var newKeys []string
for _, value := range keys {
value = strings.Trim(value, " ")
if len(value) == 0 {
continue
}
newKeys = append(newKeys, value)
}
return newKeys
}
func parseID(keys []string) []int64 {
var newKeys []int64
for _, value := range keys {
id, err := strconv.ParseInt(value, 10, 64)
if err != nil {
log.Println(err.Error())
continue
}
newKeys = append(newKeys, id)
}
return newKeys
}
// Exec executes the plugin.
func (p Plugin) Exec() error {
if len(p.Config.Token) == 0 || len(p.Config.To) == 0 {
log.Println("missing telegram token or user list")
return errors.New("missing telegram token or user list")
}
var message []string
if len(p.Config.Message) > 0 {
message = p.Config.Message
} else {
message = p.Message(p.Repo, p.Build)
}
bot, err := tgbotapi.NewBotAPI(p.Config.Token)
if err != nil {
log.Println(err.Error())
return err
}
bot.Debug = p.Config.Debug
// parse ids
ids := parseID(p.Config.To)
// send message.
for _, user := range ids {
for _, value := range trimElement(message) {
log.Println(user)
msg := tgbotapi.NewMessage(user, value)
msg.ParseMode = p.Config.Format
_, err := bot.Send(msg)
if err != nil {
log.Println(err.Error())
}
}
}
return nil
}
// Message is plugin default message.
func (p Plugin) Message(repo Repo, build Build) []string {
return []string{fmt.Sprintf("[%s] <%s> (%s)『%s』by %s",
build.Status,
build.Link,
build.Branch,
build.Message,
build.Author,
)}
}