-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
257 lines (222 loc) · 7.53 KB
/
main.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package main
import (
"context"
"fmt"
"log"
"os"
"reflect"
"regexp"
"unicode"
"github.com/ichisuke55/translate-bot/config"
"github.com/ichisuke55/translate-bot/logging"
"go.uber.org/zap"
translate "cloud.google.com/go/translate/apiv3"
"cloud.google.com/go/translate/apiv3/translatepb"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/slack-go/slack/socketmode"
)
func translateText(projectID string, sourceLang string, targetLang string, text string) (string, error) {
ctx := context.Background()
c, err := translate.NewTranslationClient(ctx)
if err != nil {
return "", err
}
defer c.Close()
req := &translatepb.TranslateTextRequest{
Contents: []string{text},
MimeType: "text/plain", // Mime types: "text/plain", default is "text/html"
Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
SourceLanguageCode: sourceLang,
TargetLanguageCode: targetLang,
}
resp, err := c.TranslateText(ctx, req)
if err != nil {
return "[ERROR] cannot translate message", err
}
// Return the translation result for each input text provided
var msg string
for _, translation := range resp.GetTranslations() {
msg = fmt.Sprintf("%v\n", translation.GetTranslatedText())
}
return msg, nil
}
func trancateText(msg string) (string, error) {
// slack's URL text style is <URL>
urlRegexp := `<(http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?>`
rep := regexp.MustCompile(urlRegexp)
// if URL contains in message, trancate it.
if match := rep.MatchString(msg); match {
msg = rep.ReplaceAllString(msg, "")
}
return msg, nil
}
func isJapanese(msg string) bool {
m := []rune(msg)
if unicode.In(m[0], unicode.Hiragana) {
return true
}
if unicode.In(m[0], unicode.Katakana) {
return true
}
if unicode.In(m[0], unicode.Han) { // check 漢字
return true
}
return false
}
func initializeLogger(conf *config.EnvConfig) (*zap.Logger, *os.File, error) {
// Create and open logfile
logfile, err := os.OpenFile(conf.LogFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
return nil, nil, fmt.Errorf("cannot create or open log file: %w", err)
}
// Init logger
logger, err := logging.NewLogger(logfile)
if err != nil {
logfile.Close()
return nil, nil, fmt.Errorf("cannot initialize logger: %w", err)
}
return logger, logfile, nil
}
func processSlackEvent(event socketmode.Event, client *slack.Client, conf *config.EnvConfig, logger *zap.Logger, socketClient *socketmode.Client) {
if event.Type == socketmode.EventTypeEventsAPI {
eventAPIEvent, ok := event.Data.(slackevents.EventsAPIEvent)
if !ok {
logger.Info("Ignored event", zap.Any("event", event))
return
}
// Prevent from sending duplicate message
socketClient.Ack(*event.Request)
if eventAPIEvent.Type == slackevents.CallbackEvent {
handleCallbackEvent(eventAPIEvent, client, conf, logger)
}
}
}
func handleCallbackEvent(eventAPIEvent slackevents.EventsAPIEvent, client *slack.Client, conf *config.EnvConfig, logger *zap.Logger) {
switch evt := eventAPIEvent.InnerEvent.Data.(type) { // nolint:gocritic
case *slackevents.MessageEvent:
// skip bot message
if evt.BotID != "" {
logger.Debug("this message sent by bot.")
return
}
logger.Debug("original text", zap.String("message", evt.Text))
logger.Debug("event message information", zap.Any("type", reflect.TypeOf(evt)), zap.Any("info", evt))
// skip image only, or delete image message
if evt.Text == "" {
logger.Debug("skip translate message, because of image only.")
return
}
// if URL contains in message, trancate it
message, err := trancateText(evt.Text)
if err != nil {
logger.Error("failed to trancate text", zap.Error(err))
return
}
// if only english in message
if isJapanese(message) {
// translate text via GoogleTranslate API
translatedMessage, err := translateText(conf.ProjectID, "ja-jp", "en-us", message)
if err != nil {
logger.Error("failed to translate", zap.Error(err))
return
}
logger.Info("translate success!", zap.String("originalText", message), zap.String("translatedText", translatedMessage))
// post slack message
if _, _, err = client.PostMessage(evt.Channel, slack.MsgOptionText(translatedMessage, false)); err != nil {
logger.Error("failed to post slack message", zap.Error(err))
}
}
}
}
func main() {
// Load environment variables
conf, err := config.NewEnvConfig()
if err != nil {
log.Fatal("cannot load environment variables")
}
// Initialize logger
logger, logfile, err := initializeLogger(conf)
if err != nil {
log.Fatalf("Logger initialization failed: %s", err)
}
defer logfile.Close()
defer logger.Sync() //nolint:errcheck
// Set Slack API client
client := slack.New(
conf.SlackBotToken,
slack.OptionAppLevelToken(conf.SlackAppToken),
// slack.OptionDebug(true),
slack.OptionLog(log.New(os.Stdout, "apiClient: ", log.Lshortfile|log.LstdFlags)),
)
// Test authenticate connection
if _, err = client.AuthTest(); err != nil {
logger.Fatal("failed to authenticate", zap.Error(err))
}
socketClient := socketmode.New(
client,
// socketmode.OptionDebug(true),
socketmode.OptionLog(log.New(os.Stdout, "socketClient: ", log.Lshortfile|log.LstdFlags)),
)
logger.Info("Bot starting...")
go func() {
for event := range socketClient.Events {
processSlackEvent(event, client, conf, logger, socketClient)
}
// for event := range socketClient.Events {
// switch event.Type { // nolint:gocritic
// case socketmode.EventTypeEventsAPI:
// eventAPIEvent, ok := event.Data.(slackevents.EventsAPIEvent)
// if !ok {
// logger.Info("Ignored event", zap.Any("event", event))
// }
// // Prevent from sending duplicate message
// socketClient.Ack(*event.Request)
// switch eventAPIEvent.Type { // nolint:gocritic
// case slackevents.CallbackEvent:
// switch evt := eventAPIEvent.InnerEvent.Data.(type) { // nolint:gocritic
// case *slackevents.MessageEvent:
// // skip bot message
// if evt.BotID != "" {
// logger.Debug("this message sent by bot.")
// continue
// }
// logger.Debug("original text", zap.String("message", evt.Text))
// logger.Debug("event message information", zap.Any("type", reflect.TypeOf(evt)), zap.Any("info", evt))
// // skip image only, or delete image message
// if evt.Text == "" {
// logger.Debug("skip translate message, because of image only.")
// continue
// }
// // if URL contains in message, trancate it
// message, err := trancateText(evt.Text)
// if err != nil {
// logger.Error("failed to trancate text", zap.Error(err))
// }
// // if only english in message
// match := isJapanese(message)
// if match {
// // translate text via GoogleTranslate API
// translatedMessage, err := translateText(conf.ProjectID, "ja-jp", "en-us", message)
// if err != nil {
// logger.Error("failed to translate", zap.Error(err))
// }
// logger.Info("translate success!", zap.String("originalText", message), zap.String("translatedText", translatedMessage))
// // post slack message
// _, _, err = client.PostMessage(
// evt.Channel,
// slack.MsgOptionText(translatedMessage, false),
// )
// if err != nil {
// logger.Error("failed to post slack message", zap.Error(err))
// }
// }
// }
// }
// }
// }
}()
if err = socketClient.Run(); err != nil {
logger.Error("failed to reconnect to slack", zap.Error(err))
}
}