-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
186 lines (165 loc) · 4.55 KB
/
bot.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
package main
import (
"fmt"
"github.com/abadojack/whatlanggo"
"github.com/carlescere/scheduler"
"github.com/joho/godotenv"
"github.com/nlopes/slack"
"github.com/reiyw/paperbot/queue"
"github.com/reiyw/paperbot/translate"
"log"
"mvdan.cc/xurls"
"os"
"strings"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
api := slack.New(os.Getenv("PAPERBOT_SLACK_TOKEN"))
arxivTrendChannelId := os.Getenv("ARXIV_TREND_CHANNEL_ID")
botUserId := os.Getenv("BOT_USER_ID")
botUserName := os.Getenv("BOT_USER_NAME")
botIconUrl := os.Getenv("BOT_ICON_URL")
channelQueue := queue.New()
rtm := api.NewRTM()
go rtm.ManageConnection()
requestAndSendTrendingPapers := func() {
var papers []Paper
trendingPapers := RequestTrendingPapersOnArxiv()
for _, tp := range trendingPapers {
p, err := FromArxivId(tp.Id)
if err != nil {
continue
}
papers = append(papers, *p)
}
for i, p := range papers {
info := fmt.Sprintf("[%d tweets] %s", trendingPapers[i].TweetCount, formatAsPlainPaperInfo(p))
rtm.SendMessage(rtm.NewOutgoingMessage(info, arxivTrendChannelId))
channelQueue.PushBack(arxivTrendChannelId)
}
}
_, err = scheduler.Every().Day().At("12:00").Run(requestAndSendTrendingPapers)
if err != nil {
fmt.Printf("Scheduler error: %s\n", err)
}
for msg := range rtm.IncomingEvents {
fmt.Print("Event Received: ")
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
fmt.Println("Infos:", ev.Info)
fmt.Println("Connection counter:", ev.ConnectionCount)
case *slack.MessageEvent:
fmt.Printf("Message: %v\n", ev)
if ev.Text == "trend" {
fmt.Println("trend")
requestAndSendTrendingPapers()
continue
}
urls := xurls.Relaxed().FindAllString(ev.Text, -1)
var papers []Paper
for _, url := range urls {
p, err := Request(url)
if err != nil {
fmt.Printf("Request error: %s\n", err)
continue
}
papers = append(papers, *p)
}
if len(papers) > 0 {
for _, p := range papers {
rtm.SendMessage(rtm.NewOutgoingMessage(formatAsPlainPaperInfo(p), ev.Channel))
channelQueue.PushBack(ev.Channel)
}
continue
}
// if direct message or mention, do translate
if strings.HasPrefix(ev.Channel, "D") || strings.Contains(ev.Text, botUserId) {
text := strings.Replace(ev.Text, fmt.Sprintf("<@%s>", botUserId), "", 1)
lang := whatlanggo.DetectLang(text)
var langFrom string
var langTo string
switch lang {
case whatlanggo.Jpn:
langFrom = "ja"
langTo = "en"
case whatlanggo.Eng:
langFrom = "en"
langTo = "ja"
default:
langFrom = "auto"
langTo = "ja"
}
rtm.SendMessage(rtm.NewOutgoingMessage(translate.Google(langFrom, langTo, text), ev.Channel))
}
case *slack.PresenceChangeEvent:
fmt.Printf("Presence Change: %v\n", ev)
case *slack.LatencyReport:
fmt.Printf("Current latency: %v\n", ev.Value)
case *slack.RTMError:
fmt.Printf("Error: %s\n", ev.Error())
case *slack.InvalidAuthEvent:
fmt.Printf("Invalid credentials")
return
case *slack.AckMessage:
fmt.Printf("AckMessage: %v\n", ev)
urls := xurls.Relaxed().FindAllString(ev.Text, -1)
fmt.Println("found URLs: ", urls)
var papers []Paper
for _, url := range urls {
p, err := Request(url)
if err != nil {
continue
}
papers = append(papers, *p)
}
for _, p := range papers {
params := slack.PostMessageParameters{
Attachments: []slack.Attachment{formatAsAttachment(p)},
ThreadTimestamp: ev.Timestamp,
IconURL: botIconUrl,
Username: botUserName,
}
channel := fmt.Sprintf("%s", channelQueue.PopFront())
_, _, _ = rtm.PostMessage(channel, "", params)
}
default:
fmt.Printf("Unexpected: %v\n", msg.Data)
}
}
}
func formatAsPlainPaperInfo(p Paper) string {
return fmt.Sprintf("%s. <%s |%s>. %d", concatAuthors(p.Authors), p.AbstUrl, p.Title, p.Year)
}
func formatAsAttachment(p Paper) slack.Attachment {
abstTextJa := translate.Google("en", "ja", p.AbstText)
attachment := slack.Attachment{
Color: p.Preserver.ToColor(),
AuthorName: concatAuthors(p.Authors),
Title: p.Title,
TitleLink: p.AbstUrl,
Text: p.Comment,
Fields: []slack.AttachmentField{
{
Title: "Abstract",
Value: p.AbstText,
}, {
Title: "概要",
Value: abstTextJa,
},
},
}
return attachment
}
func concatAuthors(authors []string) string {
var b strings.Builder
for i, author := range authors {
if i != 0 {
_, _ = b.WriteString(", ")
}
_, _ = b.WriteString(author)
}
return b.String()
}