-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
executable file
·313 lines (291 loc) · 8.49 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
package main
import (
"bytes"
"fmt"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"syscall"
"time"
"gopkg.in/robfig/cron.v2"
"github.com/FlameInTheDark/dtbot/bot"
"github.com/FlameInTheDark/dtbot/cmd"
"github.com/bwmarrin/discordgo"
)
var (
conf *bot.Config
// CmdHandler bot command handler.
CmdHandler *bot.CommandHandler
// Sessions bot session manager
Sessions *bot.SessionManager
botId string
youtube *bot.Youtube
botMsg *bot.BotMessages
dataType *bot.DataType
dbWorker *bot.DBWorker
guilds *bot.GuildsMap
botCron *cron.Cron
twitch *bot.Twitch
albUpdater *bot.AlbionUpdater
blacklist *bot.BlackListStruct
messagesCounter int
)
func main() {
botCron = cron.New()
conf = bot.LoadConfig()
CmdHandler = bot.NewCommandHandler()
registerCommands()
Sessions = bot.NewSessionManager()
youtube = &bot.Youtube{Conf: conf}
botMsg = bot.NewMessagesMap()
dataType = bot.NewDataType()
discord, err := discordgo.New("Bot " + os.Getenv("BOT_TOKEN"))
if err != nil {
fmt.Println("Create session error, ", err)
return
}
usr, err := discord.User("@me")
if err != nil {
fmt.Println("Error obtaining account details,", err)
return
}
botId = usr.ID
discord.AddHandler(func(discord *discordgo.Session, ready *discordgo.Ready) {
_ = discord.UpdateStatus(0, conf.General.Game)
guilds := discord.State.Guilds
fmt.Println("Ready with", len(guilds), "guilds.")
})
err = discord.Open()
if err != nil {
fmt.Printf("Connection open error: %v", err)
return
}
defer discord.Close()
fmt.Println("Bot is now running.")
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
dbWorker = bot.NewDBSession(conf.General.DatabaseName)
guilds = dbWorker.InitGuilds(discord, conf)
botCron.Start()
defer botCron.Stop()
defer dbWorker.DBSession.Close()
twitch = bot.TwitchInit(discord, conf, dbWorker)
albUpdater = bot.AlbionGetUpdater(dbWorker)
blacklist = dbWorker.GetBlacklist()
go BotUpdater(discord)
// Init command handler
discord.AddHandler(guildAddHandler)
discord.AddHandler(commandHandler)
discord.AddHandler(joinHandler)
onStart()
<-sc
}
// Handle new users
func joinHandler(discord *discordgo.Session, e *discordgo.GuildMemberAdd) {
if _, ok := guilds.Guilds[e.GuildID]; !ok {
dbWorker.InitNewGuild(e.GuildID, conf, guilds)
} else {
bot.Greetings(discord, e, guilds.Guilds[e.GuildID])
}
}
// Handle new guilds
func guildAddHandler(discord *discordgo.Session, e *discordgo.GuildCreate) {
if _, ok := guilds.Guilds[e.ID]; !ok {
dbWorker.InitNewGuild(e.ID, conf, guilds)
}
emb := bot.NewEmbed("").
Field(conf.GetLocaleLang("bot_joined_title", guilds.Guilds[e.ID].Language), conf.GetLocaleLang("bot_joined_text", guilds.Guilds[e.ID].Language), false)
_, _ = discord.ChannelMessageSendEmbed(e.OwnerID, emb.GetEmbed())
}
// Handle discord messages
func commandHandler(discord *discordgo.Session, message *discordgo.MessageCreate) {
if blacklist.CheckGuild(message.GuildID) || blacklist.CheckUser(message.Author.ID) {
return
}
messagesCounter++
user := message.Author
if user.ID == botId || user.Bot {
return
}
args := strings.Split(message.Content, " ")
name := strings.ToLower(args[0])
command, found := CmdHandler.Get(name)
if !found {
return
}
var permission = true
var msg string
// Checking permissions
perm, err := discord.State.UserChannelPermissions(botId, message.ChannelID)
if err != nil {
msg = fmt.Sprintf("Error whilst getting bot permissions %v\n", err)
permission = false
} else {
if perm&discordgo.PermissionSendMessages != discordgo.PermissionSendMessages ||
perm&discordgo.PermissionAttachFiles != discordgo.PermissionAttachFiles {
msg = "Permissions denied"
permission = false
}
}
channel, err := discord.State.Channel(message.ChannelID)
if err != nil {
fmt.Println("Error getting channel,", err)
return
}
guild, err := discord.State.Guild(channel.GuildID)
if err != nil {
fmt.Println("Error getting guild,", err)
return
}
if permission {
ctx := bot.NewContext(
botId,
discord,
guild,
channel,
user,
message,
conf,
CmdHandler,
Sessions,
youtube,
botMsg,
dataType,
dbWorker,
guilds,
botCron,
twitch,
albUpdater,
blacklist)
ctx.Args = args[1:]
c := *command
c(*ctx)
} else {
dbWorker.Log("Message", guild.ID, msg)
query := []byte(fmt.Sprintf("logs,server=%v module=\"%v\"", guild.ID, "message"))
addr := fmt.Sprintf("%v/write?db=%v", conf.Metrics.Address, conf.Metrics.Database)
r := bytes.NewReader(query)
_, _ = http.Post(addr, "", r)
}
}
// Adds bot commands
func registerCommands() {
CmdHandler.Register("!r", cmd.RadioCommand)
CmdHandler.Register("!w", cmd.WeatherCommand)
CmdHandler.Register("!ww", cmd.WeatherWeekCommand)
CmdHandler.Register("!t", cmd.TranslateCommand)
CmdHandler.Register("!n", cmd.NewsCommand)
CmdHandler.Register("!c", cmd.CurrencyCommand)
CmdHandler.Register("!y", cmd.YoutubeCommand)
CmdHandler.Register("!v", cmd.VoiceCommand)
CmdHandler.Register("!b", cmd.BotCommand)
CmdHandler.Register("!play", cmd.YoutubeShortCommand)
CmdHandler.Register("!d", cmd.DebugCommand)
CmdHandler.Register("!p", cmd.PollCommand)
CmdHandler.Register("!m", cmd.YandexmapCommand)
CmdHandler.Register("!dice", cmd.DiceCommand)
CmdHandler.Register("!help", cmd.HelpCommand)
CmdHandler.Register("!cron", cmd.CronCommand)
CmdHandler.Register("!geoip", cmd.GeoIPCommand)
CmdHandler.Register("!twitch", cmd.TwitchCommand)
CmdHandler.Register("!greetings", cmd.GreetingsCommand)
CmdHandler.Register("!alb", cmd.AlbionCommand)
CmdHandler.Register("!slap", cmd.SlapCommand)
CmdHandler.Register("!fu", cmd.FUCommand)
}
// MetricsSender sends metrics to InfluxDB and another services
func BotUpdater(d *discordgo.Session) {
for {
var vregions = make(map[string]int)
go twitch.Update()
go albUpdater.Update(d, dbWorker, conf)
go clearSessions(d, Sessions)
// Calculating users count
usersCount := 0
for _, g := range d.State.Guilds {
vregions[g.Region] += 1
if !blacklist.CheckGuild(g.ID) {
usersCount += g.MemberCount
}
}
// Metrics counters
queryCounters := []byte(fmt.Sprintf("counters guilds=%d,messages=%d,users=%d,voices=%d", len(d.State.Guilds), messagesCounter, usersCount, Sessions.Count()))
addrCounters := fmt.Sprintf("%v/write?db=%v&u=%v&p=%v",
conf.Metrics.Address, conf.Metrics.Database, conf.Metrics.User, conf.Metrics.Password)
rCounters := bytes.NewReader(queryCounters)
_, _ = http.Post(addrCounters, "", rCounters)
// Voice region metrics
for r, c := range vregions {
queryCounters := []byte(fmt.Sprintf("region_%s count=%d", r, c))
addrCounters := fmt.Sprintf("%v/write?db=%v&u=%v&p=%v",
conf.Metrics.Address, conf.Metrics.Database, conf.Metrics.User, conf.Metrics.Password)
rCounters := bytes.NewReader(queryCounters)
_, _ = http.Post(addrCounters, "", rCounters)
}
// Bot lists
if conf.DBL.Token != "" {
sendDBL(conf.DBL.BotID, conf.DBL.Token, len(d.State.Guilds))
}
messagesCounter = 0
time.Sleep(time.Minute)
}
}
func sendDBL(botID, token string, guilds int) {
client := &http.Client{
Timeout: time.Duration(1) * time.Second,
}
query := url.Values{}
query.Add("server_count", fmt.Sprintf("%v", guilds))
req, _ := http.NewRequest("POST",
fmt.Sprintf("https://discordbots.org/api/bots/%v/stats",
botID), strings.NewReader(query.Encode()))
req.Header.Add("Authorization", token)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
_, _ = client.Do(req)
}
func onStart() {
queryCounters := []byte(fmt.Sprintf("starts value=1"))
addrCounters := fmt.Sprintf("%v/write?db=%v&u=%v&p=%v",
conf.Metrics.Address, conf.Metrics.Database, conf.Metrics.User, conf.Metrics.Password)
rCounters := bytes.NewReader(queryCounters)
_, _ = http.Post(addrCounters, "", rCounters)
}
func clearSessions(d *discordgo.Session, s *bot.SessionManager) {
gids := s.GetGuilds()
for _, gid := range gids {
cs := s.GetByGuild(gid)
g, gerr := d.Guild(gid)
if gerr != nil {
continue
}
var ok bool
for _, vs := range g.VoiceStates {
if vs.ChannelID == cs.ChannelID {
if vs.UserID != botId {
ok = true
}
}
}
if !ok && cs != nil {
s.Leave(d, *cs)
}
}
for _, sess := range s.GetAll() {
if !sess.IsOk() {
s.Leave(d, *sess)
}
}
for i,vc := range d.VoiceConnections {
if _,b := s.GetByChannel(vc.ChannelID); b == false {
err := vc.Disconnect()
if err != nil {
log.Println(err)
}
vc.Close()
delete(d.VoiceConnections, i)
}
}
}