forked from discordconsole-team/DiscordConsole
/
events.go
97 lines (82 loc) · 2.37 KB
/
events.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
/*
DiscordConsole is a software aiming to give you full control over accounts, bots and webhooks!
Copyright (C) 2017 LEGOlord208
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"sync"
"github.com/bwmarrin/discordgo"
)
var mutexCacheGuilds sync.RWMutex
var cacheGuilds []*discordgo.UserGuild
var cacheChannels []*discordgo.Channel
var cachedChannelType string
var chanReady = make(chan []*discordgo.UserGuild)
func ready(session *discordgo.Session, e *discordgo.Ready) {
select {
case _, ok := <-chanReady:
if !ok {
return
}
default:
}
guilds := make([]*discordgo.UserGuild, len(e.Guilds))
for i, guild := range e.Guilds {
guilds[i] = toUserGuild(guild)
}
if userType == typeUser {
guilds = sortGuilds(guilds, e.Settings)
}
mutexCacheGuilds.Lock()
cacheGuilds = guilds
mutexCacheGuilds.Unlock()
select {
case chanReady <- guilds:
default:
}
close(chanReady)
}
func guildCreate(session *discordgo.Session, e *discordgo.GuildCreate) {
mutexCacheGuilds.Lock()
defer mutexCacheGuilds.Unlock()
// Fot bots, the guildcreate event triggers on startup.
for _, guild := range cacheGuilds {
if guild.ID == e.ID {
guild.Name = e.Name // For bots, the ready event does not send it's name
return
}
}
mutexCacheGuilds.Unlock()
cacheGuilds = append(cacheGuilds, toUserGuild(e.Guild))
}
func guildDelete(session *discordgo.Session, e *discordgo.GuildDelete) {
index := -1
mutexCacheGuilds.RLock()
for i, guild := range cacheGuilds {
if guild.ID == e.Guild.ID {
index = i
}
}
mutexCacheGuilds.RUnlock()
if index >= 0 {
mutexCacheGuilds.Lock()
cacheGuilds = append(cacheGuilds[index:], cacheGuilds[index+1:]...)
mutexCacheGuilds.Unlock()
}
}
func toUserGuild(guild *discordgo.Guild) *discordgo.UserGuild {
return &discordgo.UserGuild{
ID: guild.ID,
Name: guild.Name,
}
}