-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
393 lines (343 loc) · 9.18 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// +build !gen
//go:generate go run -tags=gen .
package main
import (
"errors"
"flag"
"fmt"
"github.com/bwmarrin/discordgo"
"github.com/gen2brain/beeep"
"github.com/getlantern/systray"
"github.com/kyoh86/xdg"
"github.com/lu4p/binclude"
"log"
"net"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var userGuildSettings = make(map[string]discordgo.UserGuildSettings)
const appName = "discord-notify"
const appHomepage = "https://github.com/efskap/discord-notify"
var assetPath = binclude.Include("assets") // include ./assets with all files and subdirectories
var updateState = func(s ...string) { fmt.Println(strings.Join(s, " ")) }
var exitSignal = make(chan bool, 1)
func main() {
var token string
var useSystray bool
var soundPath string
var err error
ctrlC := make(chan os.Signal, 1)
signal.Notify(ctrlC, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
flag.StringVar(&token, "t", "", "Discord token")
flag.BoolVar(&useSystray, "systray", true, "Show an icon in the system tray")
flag.StringVar(&soundPath, "sound", builtInSounds()[0], `MP3 to play on notifications`)
listSounds := flag.Bool("list-sounds", false, "List available built-in sounds.")
flag.Parse()
if listSounds != nil && *listSounds {
for _, name := range builtInSounds() {
fmt.Println(name)
}
os.Exit(0)
}
if token == "" {
token, err = readTokenFromFile()
if err != nil {
log.Println("error reading token:", err)
log.Println("put a file called `discord.token` in one of:")
for _, cfgDir := range xdg.AllConfigDirs() {
log.Println(" ", cfgDir)
}
log.Println("or pass it via the -t flag")
os.Exit(1)
}
}
if soundPath == "" || strings.ToLower(soundPath) != "none" {
if !strings.ContainsAny(soundPath, "./") {
err = setSoundBuiltin(soundPath)
fmt.Println("using built-in sound:", soundPath)
} else {
err = setSoundFromDisk(soundPath)
}
if err != nil {
log.Println(err)
log.Println("notifications will be silent!")
log.Println("you can explicitly disable the notification sound via `-sound none`")
}
}
dg, err := discordgo.New(token)
if err != nil {
log.Fatal("Error creating Discord session: ", err)
}
dg.AddHandler(onMessageCreate)
dg.AddHandler(onReady)
dg.AddHandler(onGuildSettingsUpdate)
dg.AddHandler(onDisconnect)
defer func() {
fmt.Println("Closing Discord session")
if err = dg.Close(); err != nil {
fmt.Fprintln(os.Stderr, "Error closing session:", err)
}
}()
if useSystray {
statusMenuItem := systray.AddMenuItem("Logging in...", "")
statusMenuItem.Disable()
systray.AddSeparator()
oldUpdateState := updateState
updateState = func(s ...string) {
oldUpdateState(s...)
statusMenuItem.SetTitle(strings.Join(s, " "))
}
defer systray.Quit()
go systray.Run(onSystrayReady, onSystrayExit)
}
for {
err = dg.Open()
if err != nil {
setStatusIcon(true)
var netErr net.Error
if errors.As(err, &netErr) {
updateState(fmt.Sprintln("Error connecting:", netErr, "(retrying in a bit)"))
time.Sleep(5 * time.Second)
continue
} else {
updateState(fmt.Errorf("error opening Discord session: %w", err).Error())
if useSystray {
break
} else {
return
}
}
} else {
break
}
}
if useSystray {
fmt.Println(appName + " is now running. Press CTRL-C or use the system tray menu to exit.")
} else {
fmt.Println(appName + " is now running. Press CTRL-C to exit.")
}
select {
case <-exitSignal:
break
case <-ctrlC:
break
}
}
func setStatusIcon(isError bool) {
iconPath := "assets/icon.ico"
if isError {
iconPath = "assets/icon_err.ico"
}
if err := trySetIcon(iconPath); err != nil {
log.Println("unable to set systray icon:", err)
}
}
func onSystrayReady() {
systray.SetTitle(appName)
setStatusIcon(false)
type entry struct {
menu *systray.MenuItem
soundName string
}
var soundMenus []entry
mSound := systray.AddMenuItem("Sound", "Temporarily change the sound")
noneSound := mSound.AddSubMenuItemCheckbox("<none>", "No notification sound", currentSound.buffer == nil)
soundMenus = append(soundMenus, entry{
menu: noneSound,
soundName: "",
})
for _, name := range builtInSounds() {
checked := name == currentSound.name
item := mSound.AddSubMenuItemCheckbox(name, "Built-in sound", checked)
soundMenus = append(soundMenus, entry{
menu: item,
soundName: name,
})
}
for _, m_ := range soundMenus {
currentMenu := m_
go func() {
for range currentMenu.menu.ClickedCh {
for _, m := range soundMenus {
if currentMenu.menu != m.menu {
m.menu.Uncheck()
}
}
currentMenu.menu.Check()
setSoundBuiltin(currentMenu.soundName)
}
}()
}
m := systray.AddMenuItem("Open GitHub", "Visit repo")
go func() {
for range m.ClickedCh {
if err := openBrowser(appHomepage); err != nil {
fmt.Fprintln(os.Stderr, "error opening", appHomepage, ":", err)
}
}
}()
mQuit := systray.AddMenuItem("Quit", "Quit the app.")
go func() {
<-mQuit.ClickedCh
systray.Quit()
}()
}
var curIcon = ""
func trySetIcon(path string) error {
if path == curIcon {
return nil
}
curIcon = path
f, err := BinFS.ReadFile(path)
if err != nil {
return err
}
systray.SetIcon(f)
return nil
}
func onSystrayExit() {
exitSignal <- true
}
func isMe(s *discordgo.Session, u *discordgo.User) bool {
return u.String() == s.State.User.String()
}
func shouldShowNotification(s *discordgo.Session, m *discordgo.Message) bool {
mentionsMe, mentionsRole, mentionsEveryone := mentions(s, m)
ugs := userGuildSettings[m.GuildID]
notificationSetting := notifyOption(ugs.MessageNotifications)
muted := ugs.Muted
// apply overrides
for _, override := range ugs.ChannelOverrides {
if override.ChannelID == m.ChannelID {
notificationSetting = notifyOption(override.MessageNotifications)
muted = override.Muted
break
}
}
// print debug stuff
if strings.HasPrefix(m.Content, "!test") && isMe(s, m.Author) {
fmt.Println("----")
fmt.Println("muted:\t", muted)
fmt.Println("notificationSetting:\t", notificationSetting)
fmt.Println()
fmt.Println("mentionsEveryone:\t", mentionsEveryone)
fmt.Println("supressEveryone:\t", ugs.SupressEveryone)
fmt.Println()
fmt.Println("mentionsRole:\t", mentionsRole)
fmt.Println("supressRoles:\t", ugs.SupressRoles)
fmt.Println()
fmt.Println("mentionsMe:\t", mentionsMe)
fmt.Println("----")
return true
}
// no need to send the notification when ripcord is focused
if ripFocused, err := isRipcordFocused(); err == nil && ripFocused {
return false
}
// ignore if we sent the message
if m.Author.ID == s.State.User.ID {
return false
}
if mentionsEveryone && !ugs.SupressEveryone {
return true
}
if mentionsRole && !ugs.SupressRoles {
return true
}
if mentionsMe {
return true
}
if muted {
return false
}
if notificationSetting == notifyAllMessages {
return true
}
return false
}
func mentions(s *discordgo.Session, m *discordgo.Message) (me, role, everyone bool) {
for _, mentionedUser := range m.Mentions {
if isMe(s, mentionedUser) {
me = true
break
}
}
if guildMember, err := s.GuildMember(m.GuildID, s.State.User.ID); err != nil {
// message didn't come from a guild
role = false
} else {
for _, mentionedRole := range m.MentionRoles {
for _, guildRole := range guildMember.Roles {
if mentionedRole == guildRole {
role = true
break
}
}
}
}
everyone = m.MentionEveryone
return
}
func onMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
setStatusIcon(false)
if !shouldShowNotification(s, m.Message) {
return
}
playSound()
title, body := formatNotification(s, m.Message)
if err := beeep.Notify(title, body, getAvatarFor(m.Author)); err != nil {
fmt.Println("error posting notification:", err)
}
}
func formatNotification(s *discordgo.Session, m *discordgo.Message) (title, body string) {
authorName := m.Author.String()
if guildMember, err := s.GuildMember(m.GuildID, m.Author.ID); err == nil {
if guildMember.Nick != "" {
authorName = guildMember.Nick
} else {
authorName = guildMember.User.Username
}
}
locationText := "you"
if channel, err := s.Channel(m.ChannelID); err == nil {
if channel.GuildID != "" {
locationText = "#" + channel.Name
} else if channel.Name != "" {
locationText = channel.Name
}
}
title = fmt.Sprintf("%s (%s)", authorName, locationText)
var err error
body, err = m.ContentWithMoreMentionsReplaced(s)
if err != nil {
body = m.ContentWithMentionsReplaced()
}
// iterate in reverse order since we're adding a prefix each iteration
for i := len(m.Attachments) - 1; i >= 0; i-- {
body = fmt.Sprintf("[%s]\n%s", m.Attachments[i].Filename, body)
}
return
}
func onReady(_ *discordgo.Session, r *discordgo.Ready) {
setStatusIcon(false)
updateState("Logged in as " + r.User.String())
for _, u := range r.UserGuildSettings {
userGuildSettings[u.GuildID] = *u
}
}
func onGuildSettingsUpdate(_ *discordgo.Session, u *discordgo.UserGuildSettingsUpdate) {
userGuildSettings[u.GuildID] = *u.UserGuildSettings
}
func onDisconnect(_ *discordgo.Session, d *discordgo.Disconnect) {
updateState("Disconnected!")
setStatusIcon(true)
}
type notifyOption int
const (
notifyAllMessages notifyOption = 0
notifyOnlyMentions = 1
notifyNever = 2
)