/
session.go
77 lines (61 loc) · 1.38 KB
/
session.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
package discord
import (
"sync"
"sync/atomic"
"github.com/bwmarrin/discordgo"
"github.com/benthosdev/benthos/v4/internal/cli"
)
type refCountedSession struct {
count int64
sess *discordgo.Session
}
type refCountedSessions struct {
mut sync.Mutex
sessions map[string]*refCountedSession
}
func (r *refCountedSessions) done(botToken string) {
r.mut.Lock()
defer r.mut.Unlock()
c, exists := r.sessions[botToken]
if !exists {
return
}
count := atomic.AddInt64(&c.count, -1)
if count > 0 {
return
}
_ = c.sess.Close()
delete(r.sessions, botToken)
}
func (r *refCountedSessions) Get(botToken string) (sess *discordgo.Session, done func(), err error) {
done = func() {
r.done(botToken)
}
r.mut.Lock()
defer r.mut.Unlock()
c, exists := globalSessions.sessions[botToken]
if exists {
atomic.AddInt64(&c.count, 1)
sess = c.sess
return
}
if sess, err = discordgo.New("Bot " + botToken); err != nil {
return
}
sess.UserAgent = "Benthos " + cli.Version
sess.Identify.Intents |= discordgo.IntentMessageContent
if err = sess.Open(); err != nil {
return
}
globalSessions.sessions[botToken] = &refCountedSession{
count: 1,
sess: sess,
}
return
}
var globalSessions = &refCountedSessions{
sessions: map[string]*refCountedSession{},
}
func getGlobalSession(botToken string) (*discordgo.Session, func(), error) {
return globalSessions.Get(botToken)
}