-
Notifications
You must be signed in to change notification settings - Fork 10
/
module_stats.lua
890 lines (746 loc) · 23.8 KB
/
module_stats.lua
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
-- Copyright (C) 2018 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local bot = Bot
local client = Client
local config = Config
local discordia = Discordia
local enums = discordia.enums
local fs = require("coro-fs")
local json = require("json")
local path = require("path")
local httpCodec = require("http-codec")
local net = require("coro-net")
local querystring = require("querystring")
Module.Name = "stats"
local dayPerMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
local function DayPerMonth(month, year)
if (month == 2) then
if ((year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0) then
return 29
else
return 28
end
else
return dayPerMonth[month]
end
end
local function numcmp(left, right)
if (left == right) then
return 0
elseif (left < right) then
return -1
else
return 1
end
end
local function CompareDates(day1, month1, year1, day2, month2, year2)
if (year1 == year2) then
if (month1 == month2) then
return numcmp(day1, day2)
else
return numcmp(month1, month2)
end
else
return numcmp(year1, year2)
end
end
local AccumulateArray
AccumulateArray = function(dstArray, srcArray)
for k,v in pairs(srcArray) do
if (type(v) == "number") then
local refValue = dstArray[k]
if (refValue == nil) then
dstArray[k] = v
else
assert(type(refValue) == "number")
dstArray[k] = refValue + v
end
else
assert(type(v) == "table")
local refValue = dstArray[k]
if (refValue == nil) then
refValue = {}
dstArray[k] = refValue
end
AccumulateArray(refValue, v)
end
end
end
local function AccumulateStats(stats, dateStats)
stats.MemberLeft = stats.MemberLeft + dateStats.MemberLeft
stats.MemberJoined = stats.MemberJoined + dateStats.MemberJoined
stats.MessageCount = stats.MessageCount + dateStats.MessageCount
stats.ReactionAdded = stats.ReactionAdded + dateStats.ReactionAdded
stats.ReactionRemoved = stats.ReactionRemoved + dateStats.ReactionRemoved
stats.MemberCount = dateStats.MemberCount
table.insert(stats.MemberCountHistory, dateStats.MemberCount)
AccumulateArray(stats.Channels, dateStats.Channels)
AccumulateArray(stats.Reactions, dateStats.Reactions)
AccumulateArray(stats.Users, dateStats.Users)
end
local function BadRequest(body)
local header = {
code = 404,
reason = "Not Found",
{"Content-Type", "charset=utf-8"},
{"Content-Length", 0}
}
return header, body or ""
end
local Unauthorized = function (body)
local header = {
code = 401,
{"Content-Type", "charset=utf-8"}
}
return header, body or ""
end
local Ok = function (body)
local header = {
code = 200,
reason = "OK",
{"Content-Type", "charset=utf-8"}
}
return header, body or ""
end
local function NotFound(body)
local header = {
code = 404,
reason = "Not Found",
{"Content-Type", "charset=utf-8"}
}
return header, body or ""
end
local ServerError = function (body)
local header = {
code = 500,
{"Content-Type", "charset=utf-8"}
}
return header, body or ""
end
function Module:GetConfigTable()
return {
{
Name = "LogChannel",
Description = "Channel where stats will be posted each day",
Type = bot.ConfigType.Channel,
Optional = true
},
{
Name = "ShowActiveUsers",
Description = "Allows most active users stats to be shown",
Type = bot.ConfigType.Boolean,
Default = false
},
{
Name = "AllowAPIAccess",
Description = "Allows to access this server stats via the web API",
Type = bot.ConfigType.Boolean,
Default = false
},
{
Name = "APIPrivateKey",
Description = "Private key required to access stats via the web API (empty to allow public access)",
Type = bot.ConfigType.String,
Optional = true,
Sensitive = true
},
{
Global = true,
Name = "ListenPort",
Description = "Port on which internal server listens",
Type = bot.ConfigType.Integer,
Default = 14794
}
}
end
function Module:CreateServer(host, port, onConnect)
return net.createServer({
host = host,
port = port,
encoder = httpCodec.encoder,
decoder = httpCodec.decoder,
}, function (read, write, socket)
for head in read do
local parts = {}
for part in read do
if #part > 0 then
parts[#parts + 1] = part
else
break
end
end
local body = table.concat(parts)
local head, body = onConnect(head, body, socket)
write(head)
if body then write(body) end
write("")
if not head.keepAlive then break end
end
write() --FIXME: This should be done by coro-net
end)
end
function Module:API_ServerList(req)
local servers = {}
self:ForEachGuild(function (guildId, config, data, persistentData)
if config.AllowAPIAccess and (config.APIPrivateKey == nil or #config.APIPrivateKey <= 0) then
local guild = client:getGuild(guildId)
if (guild) then
table.insert(servers, {
id = guildId,
name = guild.name,
memberCount = guild.totalMemberCount
})
end
end
end)
return {
code = 200,
reason = "OK",
{"Content-Type", "application/json"}
}, json.encode(servers)
end
function Module:API_Server(req)
local serverId = req.params[1]
if not serverId then
return NotFound("InvalidServerId")
end
local date = string.match(req.params[2] or "", "^%d%d%d%d%-%d%d%-%d%d$")
if not date then
return NotFound("InvalidDate")
end
local guild = client:getGuild(serverId)
if not guild then
return NotFound("InvalidServerId")
end
local guildConfig = self:GetConfig(guild, true)
if not guildConfig or not guildConfig.AllowAPIAccess then
return NotFound("InvalidServerId")
end
if guildConfig.APIPrivateKey and #guildConfig.APIPrivateKey > 0 then
local auth = req.headers.authorization
if not auth then
self:LogWarning("Stats API server: Access forbidden (no authorization)")
return Unauthorized("MissingAuthorization")
end
local token = string.match(auth, "Bearer (.+)")
if not token then
return BadRequest("InvalidAuthorizationHeader")
end
if token ~= guildConfig.APIPrivateKey then
self:LogWarning("Stats API server: Access forbidden (wrong token)")
return Unauthorized()
end
end
local stats = self:LoadStats(guild, self:GetStatsFilename(guild, date))
if not stats then
return NotFound("NoData")
end
return {
code = 200,
reason = "OK",
{"Content-Type", "application/json"}
}, json.encode(stats)
end
function Module:SetupServer()
if self.GlobalConfig.ListenPort <= 0 then
return
end
local routes = {
["^/servers$"] = self.API_ServerList,
["^/server/(%d+)/day/(.+)$"] = self.API_Server
}
return self:CreateServer("127.0.0.1", self.GlobalConfig.ListenPort, function (head, body, socket)
local headers = {}
for _, keyvalue in ipairs(head) do
local key, value = unpack(keyvalue)
headers[key:lower()] = value
end
if head.method == "GET" and head.path then
local pathname, query = head.path:match("^([^?]*)%??(.*)")
for pattern, handler in pairs(routes) do
local matches = {pathname:match(pattern)}
if #matches > 0 then
local req = {
headers = headers,
path = head.path,
params = matches,
query = query and querystring.parse(query) or nil
}
local success, header, body = bot:ProtectedCall("Stats API", handler, self, req)
if not success then
self:LogWarning("Stats API: Server error")
return ServerError()
end
return header, body
end
end
end
return NotFound()
end)
end
function Module:OnLoaded()
self.Server = self:SetupServer()
if not self.Server then
self:LogError(nil, "Failed to start stats server")
end
self.Clock = discordia.Clock()
self.Clock:on("day", function ()
self:ForEachGuild(function (guildId, config, data, persistentData)
local guild = client:getGuild(guildId)
if (guild) then
local stats = persistentData.Stats
self:SaveStats(self:GetStatsFilename(guild, stats.Date), stats)
persistentData.Stats = self:BuildStats(guild)
if (config.LogChannel) then
local channel = guild:getChannel(config.LogChannel)
if (channel) then
coroutine.wrap(function() self:PrintStats(channel, stats) end)()
end
end
end
end)
end)
self:RegisterCommand({
Name = "resetstats",
Args = {},
PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end,
Help = "Resets stats of the day",
Func = function (commandMessage)
local data = self:GetPersistentData(commandMessage.guild)
data.Stats = self:BuildStats()
commandMessage:reply("Stats reset successfully")
end
})
self:RegisterCommand({
Name = "serverstats",
Args = {
{Name = "date/from", Type = Bot.ConfigType.String, Optional = true},
{Name = "to", Type = Bot.ConfigType.String, Optional = true}
},
Help = "Prints stats",
Func = function (commandMessage, from, to)
if (from and to and from ~= to) then
local fromY, fromM, fromD = from:match("^(%d%d%d%d)-(%d%d)-(%d%d)$")
if (not fromY) then
commandMessage:reply("Invalid date format for `from` parameter, please write it as YYYY-MM-DD")
return
end
local toY, toM, toD = to:match("^(%d%d%d%d)-(%d%d)-(%d%d)$")
if (not toY) then
commandMessage:reply("Invalid date format for `to` parameter, please write it as YYYY-MM-DD")
return
end
if (CompareDates(fromD, fromM, fromY, toD, toM, toY) >= 0) then
commandMessage:reply("`from` date must be earlier than `to` date")
return
end
commandMessage.channel:broadcastTyping()
-- Check available dates
local guildStatsFolder = self:GetStatsFolder(commandMessage.guild)
local availableStats = {}
for file in fs.scandir(guildStatsFolder) do
if (file.type == "file") then
local year, month, day = file.name:match("^stats_(%d%d%d%d)-(%d%d)-(%d%d).json$")
if (year) then
table.insert(availableStats, { d = day, m = month, y = year })
end
end
end
local compareDateFunc = function (left, right)
return CompareDates(left.d, left.m, left.y, right.d, right.m, right.y)
end
table.sort(availableStats, function (left, right) return compareDateFunc(left, right) < 0 end)
local fromDate = { d = fromD, m = fromM, y = fromY }
if (compareDateFunc(fromDate, availableStats[1]) < 0) then
fromDate = availableStats[1]
end
local toDate = { d = toD, m = toM, y = toY }
if (compareDateFunc(toDate, availableStats[#availableStats]) > 0) then
toDate = availableStats[#availableStats]
end
local _, firstIndex = table.binsearch(availableStats, fromDate, compareDateFunc)
local _, lastIndex = table.binsearch(availableStats, toDate, compareDateFunc)
local accumulatedStats = self:BuildStats(commandMessage.guild)
accumulatedStats.MemberCount = nil
accumulatedStats.MemberCountHistory = {}
for i = firstIndex, lastIndex do
local v = availableStats[i]
local fileName = string.format("%s/stats_%s-%s-%s.json", guildStatsFolder, v.y, v.m, v.d)
local stats, err = self:LoadStats(commandMessage.guild, fileName)
if (not stats) then
commandMessage:reply("Failed to load some stats")
return
end
AccumulateStats(accumulatedStats, stats)
end
self:PrintStats(commandMessage.channel, accumulatedStats, string.format("%s-%s-%s", fromDate.d, fromDate.m, fromDate.y), string.format("%s-%s-%s", toDate.d, toDate.m, toDate.y), lastIndex - firstIndex + 1)
elseif (from) then
if (not from:match("^%d%d%d%d%-%d%d%-%d%d$")) then
commandMessage:reply("Invalid date format, please write it as YYYY-MM-DD")
return
end
local stats = self:LoadStats(commandMessage.guild, self:GetStatsFilename(commandMessage.guild, from))
if (not stats) then
commandMessage:reply("We have no stats for that date")
return
end
self:PrintStats(commandMessage.channel, stats)
else
local data = self:GetPersistentData(commandMessage.guild)
self:PrintStats(commandMessage.channel, data.Stats)
end
end
})
return true
end
function Module:OnEnable(guild)
local data = self:GetPersistentData(guild)
if (not data.Stats) then
self:LogInfo(guild, "No previous stats found, resetting...")
data.Stats = self:BuildStats(guild)
else
local currentDate = os.date("%Y-%m-%d")
local statsDate = os.date("%Y-%m-%d", data.Stats.Date)
if (currentDate ~= statsDate) then
self:LogInfo(guild, "Previous stats data has been found but date does not match (%s), saving and resetting", statsDate)
self:SaveStats(self:GetStatsFilename(guild, data.Stats.Date), data.Stats)
data.Stats = self:BuildStats(guild)
else
self:LogInfo(guild, "Previous stats data has been found and date does match, continuing...")
end
end
return true
end
function Module:OnReady()
self.Clock:start()
end
function Module:OnUnload()
if self.Clock then
self.Clock:stop()
end
if self.Server then
self.Server:close()
end
end
function Module:LoadStats(guild, filepath)
local stats, err = bot:UnserializeFromFile(filepath)
if (not stats) then
self:LogError(guild, "Failed to load stats: %s", err)
return
end
return stats
end
function Module:GetStatsFilename(guild, time)
return string.format("%s/stats_%s.json", self:GetStatsFolder(guild), (type(time) == "number") and os.date("%Y-%m-%d", time) or time)
end
function Module:GetStatsFolder(guild)
return string.format("stats/guild_%s", guild.id)
end
function Module:PrintStats(channel, stats, fromDate, toDate, dayCount)
local guild = channel.guild
local config = self:GetConfig(guild)
local memberCount
local valueFunc
if (dayCount) then
local memberCountHistory = stats.MemberCountHistory
if (#memberCountHistory > 0) then
local firstMemberCount = memberCountHistory[1]
local lastMemberCount = memberCountHistory[#memberCountHistory]
if (lastMemberCount > firstMemberCount) then
memberCount = string.format("%u (+ %u)", lastMemberCount, lastMemberCount - firstMemberCount)
elseif (lastMemberCount < firstMemberCount) then
memberCount = string.format("%u (- %u)", lastMemberCount, firstMemberCount - lastMemberCount)
else
memberCount = string.format("%u (=)", lastMemberCount)
end
end
valueFunc = function (value, msg)
if (value) then
return string.format("%s (%s avg.)", value, math.floor(value / dayCount))
else
return msg or 0
end
end
else
valueFunc = function (value, msg)
if (value) then
return tostring(value)
else
return msg or 0
end
end
end
if (not memberCount) then
memberCount = stats.MemberCount or "<No logs>"
end
local mostAddedReaction = {}
for reactionName, reactionStats in pairs(stats.Reactions) do
table.insert(mostAddedReaction, { name = reactionName, count = reactionStats.ReactionCount })
end
table.sort(mostAddedReaction, function (a, b) return a.count > b.count end)
local addedReactionList = ""
for i = 1, 5 do
if (i > #mostAddedReaction) then
break
end
local reactionData = mostAddedReaction[i]
local emojiData = bot:GetEmojiData(guild, reactionData.name)
if (not emojiData) then
self:LogError("Most added reaction %s is not found", reactionData.name)
end
addedReactionList = addedReactionList .. string.format("%s %s\n", valueFunc(reactionData.count), emojiData and emojiData.MentionString or string.format("<bot error on %s>", reactionData.name))
end
local mostActiveChannels = {}
for channelId, channelStats in pairs(stats.Channels) do
table.insert(mostActiveChannels, { id = channelId, messageCount = channelStats.MessageCount })
end
table.sort(mostActiveChannels, function (a, b) return a.messageCount > b.messageCount end)
local activeChannelList = ""
for i = 1, 5 do
if (i > #mostActiveChannels) then
break
end
local channelData = mostActiveChannels[i]
local channel = guild:getChannel(channelData.id)
activeChannelList = activeChannelList .. string.format("%s: %s m.\n", channel and string.format("[#%s](%s)", channel.name, channel.link) or "<deleted channel>", valueFunc(channelData.messageCount))
end
local activeMemberList
if (config.ShowActiveUsers) then
local mostActiveMembers = {}
for userId, userStats in pairs(stats.Users) do
table.insert(mostActiveMembers, { id = userId, messageCount = userStats.MessageCount })
end
table.sort(mostActiveMembers, function (a, b) return a.messageCount > b.messageCount end)
activeMemberList = ""
for i = 1, 5 do
if (i > #mostActiveMembers) then
break
end
local memberData = mostActiveMembers[i]
activeMemberList = activeMemberList .. string.format("%s: %s m.\n", "<@" .. memberData.id .. ">", valueFunc(memberData.messageCount))
end
end
local fields = {
{
name = "Member count", value = memberCount, inline = true
},
{
name = "New members", value = valueFunc(stats.MemberJoined), inline = true
},
{
name = "Lost members", value = valueFunc(stats.MemberLeft), inline = true
},
{
name = "Messages posted", value = valueFunc(stats.MessageCount), inline = true
},
{
name = "Active members", value = table.count(stats.Users), inline = true
},
{
name = "Active channels", value = table.count(stats.Channels), inline = true
},
{
name = "Total reactions added", value = valueFunc(stats.ReactionAdded), inline = true
},
{
name = "Most added reactions", value = #addedReactionList > 0 and addedReactionList or "<None>", inline = true
},
{
name = "Most active channels", value = #activeChannelList > 0 and activeChannelList or "<None>", inline = true
}
}
if (activeMemberList) then
table.insert(fields,
{
name = "Most active members", value = #activeMemberList > 0 and activeMemberList or "<None>", inline = true
})
end
local title
if (not fromDate) then
local resetTime = os.difftime(os.time(), stats.Date)
title = string.format("Server stats - %s, started %s ago", os.date("%d-%m-%Y", stats.Date), util.FormatTime(resetTime, 2))
else
title = string.format("Server stats - from %s to %s", fromDate, toDate)
end
channel:send({
embed = {
title = title,
fields = fields,
timestamp = discordia.Date(stats.Date):toISO('T', 'Z')
}
})
end
function Module:BuildStats(guild)
local stats = {}
stats.Date = os.time()
stats.Channels = {}
stats.Reactions = {}
stats.Users = {}
stats.MemberCount = guild.totalMemberCount
stats.MemberLeft = 0
stats.MemberJoined = 0
stats.MessageCount = 0
stats.ReactionAdded = 0
stats.ReactionRemoved = 0
return stats
end
function Module:SaveStats(filename, stats)
local dirname = path.dirname(filename)
if (dirname ~= "." and not fs.mkdirp(dirname)) then
self:LogError("Failed to create directory %s", dirname)
return
end
local outputFile = io.open(filename, "w+")
if (not outputFile) then
self:LogError("Failed to open %s", filename)
return
end
local success, err = outputFile:write(json.encode(stats))
if (not success) then
self:LogError("Failed to write %s: %s", filename, err)
return
end
outputFile:close()
end
function Module:GetChannelStats(guild, channel)
local channelId
if (channel.isThread) then
channelId = channel._parent_id
else
channelId = channel.id
end
if (type(channelId) ~= "string") then
self:LogError("expected string as channel id, got " .. type(channelId))
return { MessageCount = 0, ReactionCount = 0 } -- dummy temporary table
end
local data = self:GetPersistentData(guild)
local channels = data.Stats.Channels
local channelStats = channels[channelId]
if (not channelStats) then
channelStats = {}
channelStats.MessageCount = 0
channelStats.ReactionCount = 0
channels[channelId] = channelStats
end
return channelStats
end
function Module:GetReactionStats(guild, reactionName)
if (type(reactionName) ~= "string") then
self:LogError("expected string as reaction name, got " .. type(reactionName))
return { ReactionCount = 0 } -- dummy temporary table
end
local data = self:GetPersistentData(guild)
local reactions = data.Stats.Reactions
local reactionStats = reactions[reactionName]
if (not reactionStats) then
reactionStats = {}
reactionStats.ReactionCount = 0
reactions[reactionName] = reactionStats
end
return reactionStats
end
function Module:GetUserStats(guild, userId)
if (type(userId) ~= "string") then
self:LogError("expected string as user id, got " .. type(userId))
return { MessageCount = 0, ReactionCount = 0 } -- dummy temporary table
end
local data = self:GetPersistentData(guild)
local users = data.Stats.Users
local userStats = users[userId]
if (not userStats) then
userStats = {}
userStats.MessageCount = 0
userStats.ReactionCount = 0
users[userId] = userStats
end
return userStats
end
function Module:OnMessageCreate(message)
if (not bot:IsPublicChannel(message.channel)) then
return
end
if (message.author.bot) then
return
end
local data = self:GetPersistentData(message.guild)
data.Stats.MessageCount = data.Stats.MessageCount + 1
-- Channels
local channelStats = self:GetChannelStats(message.guild, message.channel)
channelStats.MessageCount = channelStats.MessageCount + 1
-- Members
local userStats = self:GetUserStats(message.guild, message.author.id)
userStats.MessageCount = userStats.MessageCount + 1
end
function Module:OnMemberJoin(member)
if (member.user.bot) then
return
end
local data = self:GetPersistentData(member.guild)
data.Stats.MemberJoined = data.Stats.MemberJoined + 1
data.Stats.MemberCount = data.Stats.MemberCount + 1
end
function Module:OnMemberLeave(member)
if (member.user.bot) then
return
end
local data = self:GetPersistentData(member.guild)
data.Stats.MemberLeft = data.Stats.MemberLeft + 1
data.Stats.MemberCount = data.Stats.MemberCount - 1
end
function Module:OnReactionAdd(reaction, userId)
if (not bot:IsPublicChannel(reaction.message.channel)) then
return
end
local emojiData = bot:GetEmojiData(reaction.message.guild, reaction.emojiId or reaction.emojiName)
if (not emojiData) then
return
end
local data = self:GetPersistentData(reaction.message.guild)
data.Stats.ReactionAdded = data.Stats.ReactionAdded + 1
local channelStats = self:GetChannelStats(reaction.message.guild, reaction.message.channel)
channelStats.ReactionCount = channelStats.ReactionCount + 1
local reactionStats = self:GetReactionStats(reaction.message.guild, emojiData.Name)
reactionStats.ReactionCount = reactionStats.ReactionCount + 1
local userStats = self:GetUserStats(reaction.message.guild, userId)
userStats.ReactionCount = userStats.ReactionCount + 1
end
function Module:OnReactionAddUncached(channel, messageId, reactionIdorName, userId)
if (not bot:IsPublicChannel(channel)) then
return
end
local emojiData = bot:GetEmojiData(channel.guild, reactionIdorName)
if (not emojiData) then
return
end
local data = self:GetPersistentData(channel.guild)
data.Stats.ReactionAdded = data.Stats.ReactionAdded + 1
local channelStats = self:GetChannelStats(channel.guild, channel)
channelStats.ReactionCount = channelStats.ReactionCount + 1
local reactionStats = self:GetReactionStats(channel.guild, emojiData.Name)
reactionStats.ReactionCount = reactionStats.ReactionCount + 1
local userStats = self:GetUserStats(channel.guild, userId)
userStats.ReactionCount = userStats.ReactionCount + 1
end
function Module:OnReactionRemove(reaction, userId)
if (not bot:IsPublicChannel(reaction.message.channel)) then
return
end
local data = self:GetPersistentData(reaction.message.guild)
data.Stats.ReactionRemoved = data.Stats.ReactionRemoved + 1
local reactionStats = self:GetReactionStats(reaction.message.guild, reaction.emojiId or reaction.emojiName)
reactionStats.ReactionCount = math.max(reactionStats.ReactionCount - 1, 0)
end
function Module:OnReactionRemoveUncached(channel, messageId, reactionIdorName, userId)
if (not bot:IsPublicChannel(channel)) then
return
end
local emojiData = bot:GetEmojiData(channel.guild, reactionIdorName)
if (not emojiData) then
return
end
local data = self:GetPersistentData(channel.guild)
data.Stats.ReactionRemoved = data.Stats.ReactionRemoved + 1
local reactionStats = self:GetReactionStats(channel.guild, emojiData.Name)
reactionStats.ReactionCount = math.max(reactionStats.ReactionCount - 1, 0)
end