-
Notifications
You must be signed in to change notification settings - Fork 30
/
history.go
674 lines (622 loc) · 23.3 KB
/
history.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
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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"time"
"github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
orderedmap "github.com/wk8/go-ordered-map/v2"
)
type historyStatus int
const (
historyStatusWaiting historyStatus = iota
historyStatusRunning
historyStatusAbortRequested
historyStatusAbortCompleted
historyStatusErrorReadMessageHistoryPerms
historyStatusErrorRequesting
historyStatusCompletedNoMoreMessages
historyStatusCompletedToBeforeFilter
historyStatusCompletedToSinceFilter
)
func historyStatusLabel(status historyStatus) string {
switch status {
case historyStatusWaiting:
return "Waiting..."
case historyStatusRunning:
return "Currently Downloading..."
case historyStatusAbortRequested:
return "Abort Requested..."
case historyStatusAbortCompleted:
return "Aborted..."
case historyStatusErrorReadMessageHistoryPerms:
return "ERROR: Cannot Read Message History"
case historyStatusErrorRequesting:
return "ERROR: Message Requests Failed"
case historyStatusCompletedNoMoreMessages:
return "COMPLETE: No More Messages"
case historyStatusCompletedToBeforeFilter:
return "COMPLETE: Exceeded Before Date Filter"
case historyStatusCompletedToSinceFilter:
return "COMPLETE: Exceeded Since Date Filter"
default:
return "Unknown"
}
}
type historyJob struct {
Status historyStatus
OriginUser string
OriginChannel string
TargetCommandingMessage *discordgo.Message
TargetChannelID string
TargetBefore string
TargetSince string
DownloadCount int64
DownloadSize int64
Updated time.Time
Added time.Time
}
var (
historyJobs *orderedmap.OrderedMap[string, historyJob]
historyJobCnt int
historyJobCntWaiting int
historyJobCntRunning int
historyJobCntAborted int
historyJobCntErrored int
historyJobCntCompleted int
)
// TODO: cleanup
type historyCache struct {
Updated time.Time
Running bool
RunningBefore string // messageID for last before range attempted if interrupted
CompletedSince string // messageID for last message the bot has 100% assumed completion on (since start of channel)
}
func handleHistory(commandingMessage *discordgo.Message, subjectChannelID string, before string, since string) int {
var err error
historyStartTime := time.Now()
var historyDownloadDuration time.Duration
// Log Prefix
var commander string = "AUTORUN"
var autorun bool = true
if commandingMessage != nil { // Only time commandingMessage is nil is Autorun
commander = getUserIdentifier(*commandingMessage.Author)
autorun = false
}
logPrefix := fmt.Sprintf("%s/%s: ", subjectChannelID, commander)
// Skip Requested
if job, exists := historyJobs.Get(subjectChannelID); exists && job.Status != historyStatusWaiting {
log.Println(lg("History", "", color.RedString, logPrefix+"History job skipped, Status: %s", historyStatusLabel(job.Status)))
return -1
}
// Vars
baseChannelInfo, err := bot.State.Channel(subjectChannelID)
if err != nil {
baseChannelInfo, err = bot.Channel(subjectChannelID)
if err != nil {
log.Println(lg("History", "", color.HiRedString, logPrefix+"Error fetching channel data from discordgo:\t%s", err))
}
}
var totalMessages int64 = 0
var totalDownloads int64 = 0
var totalFilesize int64 = 0
var messageRequestCount int = 0
sourceMessage := discordgo.Message{} // dummy message
sourceMessage.ChannelID = subjectChannelID
sourceMessage.GuildID = baseChannelInfo.GuildID
sourceConfig := getSource(&sourceMessage)
var responseMsg *discordgo.Message = nil
guildName := getServerLabel(baseChannelInfo.GuildID)
categoryName := getCategoryLabel(baseChannelInfo.ID)
subjectChannels := []discordgo.Channel{}
// Check channel type
baseChannelIsForum := true
if baseChannelInfo.Type != discordgo.ChannelTypeGuildCategory &&
baseChannelInfo.Type != discordgo.ChannelTypeGuildForum &&
baseChannelInfo.Type != discordgo.ChannelTypeGuildStageVoice &&
baseChannelInfo.Type != discordgo.ChannelTypeGuildVoice &&
baseChannelInfo.Type != discordgo.ChannelTypeGuildStore {
subjectChannels = append(subjectChannels, *baseChannelInfo)
baseChannelIsForum = false
}
// Index Threads
indexedThreads := map[string]bool{}
if threads, err := bot.ThreadsActive(subjectChannelID); err == nil {
for _, thread := range threads.Threads {
if indexedThreads[thread.ID] {
continue
}
subjectChannels = append(subjectChannels, *thread)
indexedThreads[thread.ID] = true
}
}
if threads, err := bot.ThreadsArchived(subjectChannelID, nil, 0); err == nil {
for _, thread := range threads.Threads {
if indexedThreads[thread.ID] {
continue
}
subjectChannels = append(subjectChannels, *thread)
indexedThreads[thread.ID] = true
}
}
if threads, err := bot.ThreadsPrivateArchived(subjectChannelID, nil, 0); err == nil {
for _, thread := range threads.Threads {
if indexedThreads[thread.ID] {
continue
}
subjectChannels = append(subjectChannels, *thread)
indexedThreads[thread.ID] = true
}
}
if threads, err := bot.ThreadsPrivateJoinedArchived(subjectChannelID, nil, 0); err == nil {
for _, thread := range threads.Threads {
if indexedThreads[thread.ID] {
continue
}
subjectChannels = append(subjectChannels, *thread)
indexedThreads[thread.ID] = true
}
}
// Send Status?
var sendStatus bool = true
if (autorun && !config.SendAutoHistoryStatus) || (!autorun && !config.SendHistoryStatus) {
sendStatus = false
}
// Check Read History perms
if !baseChannelIsForum && !hasPerms(subjectChannelID, discordgo.PermissionReadMessageHistory) {
if job, exists := historyJobs.Get(subjectChannelID); exists {
job.Status = historyStatusRunning
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
}
log.Println(lg("History", "", color.HiRedString, logPrefix+"BOT DOES NOT HAVE PERMISSION TO READ MESSAGE HISTORY!!!"))
}
// Update Job Status to Downloading
if job, exists := historyJobs.Get(subjectChannelID); exists {
job.Status = historyStatusRunning
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
}
//#region Cache Files
openHistoryCache := func(channel string) historyCache {
if f, err := os.ReadFile(pathCacheHistory + string(os.PathSeparator) + channel + ".json"); err == nil {
var ret historyCache
if err = json.Unmarshal(f, &ret); err != nil {
log.Println(lg("Debug", "History", color.RedString,
logPrefix+"Failed to unmarshal json for cache:\t%s", err))
} else {
return ret
}
}
return historyCache{}
}
writeHistoryCache := func(channel string, cache historyCache) {
cacheJson, err := json.Marshal(cache)
if err != nil {
log.Println(lg("Debug", "History", color.RedString,
logPrefix+"Failed to format cache into json:\t%s", err))
} else {
if err := os.MkdirAll(pathCacheHistory, 0755); err != nil {
log.Println(lg("Debug", "History", color.HiRedString,
logPrefix+"Error while creating history cache folder \"%s\": %s", pathCacheHistory, err))
}
f, err := os.OpenFile(
pathCacheHistory+string(os.PathSeparator)+channel+".json",
os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Println(lg("Debug", "History", color.RedString,
logPrefix+"Failed to open cache file:\t%s", err))
}
if _, err = f.WriteString(string(cacheJson)); err != nil {
log.Println(lg("Debug", "History", color.RedString,
logPrefix+"Failed to write cache file:\t%s", err))
} else if !autorun && config.Debug {
log.Println(lg("Debug", "History", color.YellowString,
logPrefix+"Wrote to cache file."))
}
f.Close()
}
}
deleteHistoryCache := func(channel string) {
fp := pathCacheHistory + string(os.PathSeparator) + channel + ".json"
if _, err := os.Stat(fp); err == nil {
err = os.Remove(fp)
if err != nil {
log.Println(lg("Debug", "History", color.HiRedString,
logPrefix+"Encountered error deleting cache file:\t%s", err))
} else if commandingMessage != nil && config.Debug {
log.Println(lg("Debug", "History", color.HiRedString,
logPrefix+"Deleted cache file."))
}
}
}
//#endregion
for _, channel := range subjectChannels {
logPrefix = fmt.Sprintf("%s/%s: ", channel.ID, commander)
// Invalid Source?
if sourceConfig == emptySourceConfig {
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Invalid source: "+channel.ID))
if job, exists := historyJobs.Get(subjectChannelID); exists {
job.Status = historyStatusErrorRequesting
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
}
continue
} else { // Process
logHistoryStatus := true
if sourceConfig.OutputHistoryStatus != nil {
logHistoryStatus = *sourceConfig.OutputHistoryStatus
}
// Overwrite Send Status
if sourceConfig.SendAutoHistoryStatus != nil {
if autorun && !*sourceConfig.SendAutoHistoryStatus {
sendStatus = false
}
}
if sourceConfig.SendHistoryStatus != nil {
if !autorun && !*sourceConfig.SendHistoryStatus {
sendStatus = false
}
}
hasPermsToRespond := hasPerms(channel.ID, discordgo.PermissionSendMessages)
if !autorun {
hasPermsToRespond = hasPerms(commandingMessage.ChannelID, discordgo.PermissionSendMessages)
}
// Date Range Vars
rangeContent := ""
var beforeTime time.Time
var beforeID = before
var sinceID = ""
// Handle Cache File
if cache := openHistoryCache(channel.ID); cache != (historyCache{}) {
if cache.CompletedSince != "" {
if config.Debug {
log.Println(lg("Debug", "History", color.GreenString,
logPrefix+"Assuming history is completed prior to "+cache.CompletedSince))
}
since = cache.CompletedSince
}
if cache.Running {
if config.Debug {
log.Println(lg("Debug", "History", color.YellowString,
logPrefix+"Job was interrupted last run, picking up from "+beforeID))
}
beforeID = cache.RunningBefore
}
}
//#region Date Range Output
var beforeRange = before
if beforeRange != "" {
if isDate(beforeRange) { // user has input YYYY-MM-DD
beforeRange = discordTimestampToSnowflake("2006-01-02", beforeID)
} else { // try to parse duration
dur, err := time.ParseDuration(beforeRange)
if err == nil {
beforeRange = discordTimestampToSnowflake("2006-01-02 15:04:05.999999999 -0700 MST", time.Now().Add(-dur).Format("2006-01-02 15:04:05.999999999 -0700 MST"))
}
}
if isNumeric(beforeRange) { // did we convert something (or was it always a number)?
rangeContent += fmt.Sprintf("**Before:** `%s`\n", beforeRange)
}
before = beforeRange
}
var sinceRange = since
if sinceRange != "" {
if isDate(sinceRange) { // user has input YYYY-MM-DD
sinceRange = discordTimestampToSnowflake("2006-01-02", sinceRange)
} else { // try to parse duration
dur, err := time.ParseDuration(sinceRange)
if err == nil {
sinceRange = discordTimestampToSnowflake("2006-01-02 15:04:05.999999999 -0700 MST", time.Now().Add(-dur).Format("2006-01-02 15:04:05.999999999 -0700 MST"))
}
}
if isNumeric(sinceRange) { // did we convert something (or was it always a number)?
rangeContent += fmt.Sprintf("**Since:** `%s`\n", sinceRange)
}
since = sinceRange
}
if rangeContent != "" {
rangeContent += "\n"
}
//#endregion
channelName := getChannelLabel(channel.ID, &channel)
if channel.ParentID != "" {
channelName = getChannelLabel(channel.ParentID, nil) + " \"" + getChannelLabel(channel.ID, &channel) + "\""
}
sourceName := fmt.Sprintf("%s / %s", guildName, channelName)
msgSourceDisplay := fmt.Sprintf("`Server:` **%s**\n`Channel:` #%s", guildName, channelName)
if categoryName != "unknown" {
sourceName = fmt.Sprintf("%s / %s / %s", guildName, categoryName, channelName)
msgSourceDisplay = fmt.Sprintf("`Server:` **%s**\n`Category:` _%s_\n`Channel:` #%s",
guildName, categoryName, channelName)
}
// Initial Status Message
if sendStatus {
if hasPermsToRespond {
responseMsg, err = replyEmbed(commandingMessage, "Command — History", msgSourceDisplay)
if err != nil {
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to send command embed message:\t%s", err))
}
} else {
log.Println(lg("History", "", color.HiRedString,
logPrefix+fmtBotSendPerm, commandingMessage.ChannelID))
}
}
log.Println(lg("History", "", color.HiCyanString, logPrefix+"Began checking history for \"%s\"...", sourceName))
lastMessageID := ""
MessageRequestingLoop:
for {
// Next 100
if beforeTime != (time.Time{}) {
messageRequestCount++
writeHistoryCache(channel.ID, historyCache{
Updated: time.Now(),
Running: true,
RunningBefore: beforeID,
})
// Update Status
if logHistoryStatus {
log.Println(lg("History", "", color.CyanString,
logPrefix+"Requesting more, \t%d downloaded (%s), \t%d processed, \tsearching before %s ago (%s)",
totalDownloads, humanize.Bytes(uint64(totalFilesize)), totalMessages, timeSinceShort(beforeTime), beforeTime.String()[:10]))
}
if sendStatus {
var status string
if totalDownloads == 0 {
status = fmt.Sprintf(
"``%s:`` **No files downloaded...**\n"+
"_%s messages processed, avg %d msg/s_\n\n"+
"%s\n\n"+
"%s`(%d)` _Processing more messages, please wait..._\n",
timeSinceShort(historyStartTime),
formatNumber(totalMessages), int(float64(totalMessages)/time.Since(historyStartTime).Seconds()),
msgSourceDisplay, rangeContent, messageRequestCount,
)
} else {
status = fmt.Sprintf(
"``%s:`` **%s files downloaded...**\n`%s so far, avg %1.1f MB/s`\n"+
"_%s messages processed, avg %d msg/s_\n\n"+
"%s\n\n"+
"%s`(%d)` _Processing more messages, please wait..._\n",
timeSinceShort(historyStartTime), formatNumber(totalDownloads),
humanize.Bytes(uint64(totalFilesize)), float64(totalFilesize/humanize.MByte)/historyDownloadDuration.Seconds(),
formatNumber(totalMessages), int(float64(totalMessages)/time.Since(historyStartTime).Seconds()),
msgSourceDisplay, rangeContent, messageRequestCount,
)
}
if responseMsg == nil {
log.Println(lg("History", "", color.RedString,
logPrefix+"Tried to edit status message but it doesn't exist, sending new one."))
if responseMsg, err = replyEmbed(commandingMessage, "Command — History", status); err != nil { // Failed to Edit Status, Send New Message
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to send replacement status message:\t%s", err))
}
} else {
if !hasPermsToRespond {
log.Println(lg("History", "", color.HiRedString,
logPrefix+fmtBotSendPerm+" - %s", responseMsg.ChannelID, status))
} else {
// Edit Status
if selfbot {
responseMsg, err = bot.ChannelMessageEdit(responseMsg.ChannelID, responseMsg.ID,
fmt.Sprintf("**Command — History**\n\n%s", status))
} else {
responseMsg, err = bot.ChannelMessageEditComplex(&discordgo.MessageEdit{
ID: responseMsg.ID,
Channel: responseMsg.ChannelID,
Embed: buildEmbed(responseMsg.ChannelID, "Command — History", status),
})
}
// Failed to Edit Status
if err != nil {
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to edit status message, sending new one:\t%s", err))
if responseMsg, err = replyEmbed(responseMsg, "Command — History", status); err != nil { // Failed to Edit Status, Send New Message
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to send replacement status message:\t%s", err))
}
}
}
}
}
// Update presence
timeLastUpdated = time.Now()
if *sourceConfig.PresenceEnabled {
go updateDiscordPresence()
}
}
// Request More Messages
msg_rq_cnt := 0
request_messages:
msg_rq_cnt++
if config.HistoryRequestDelay > 0 {
if logHistoryStatus {
log.Println(lg("History", "", color.YellowString, "Delaying next batch request for %d seconds...", config.HistoryRequestDelay))
}
time.Sleep(time.Second * time.Duration(config.HistoryRequestDelay))
}
if messages, err := bot.ChannelMessages(channel.ID, config.HistoryRequestCount, beforeID, sinceID, ""); err != nil {
// Error requesting messages
if sendStatus {
if !hasPermsToRespond {
log.Println(lg("History", "", color.HiRedString,
logPrefix+fmtBotSendPerm, responseMsg.ChannelID))
} else {
_, err = replyEmbed(responseMsg, "Command — History",
fmt.Sprintf("Encountered an error requesting messages for %s: %s", channel.ID, err.Error()))
if err != nil {
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to send error message:\t%s", err))
}
}
}
log.Println(lg("History", "", color.HiRedString, logPrefix+"Error requesting messages:\t%s", err))
if job, exists := historyJobs.Get(subjectChannelID); exists {
job.Status = historyStatusErrorRequesting
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
}
//TODO: delete cahce or handle it differently?
break MessageRequestingLoop
} else {
// No More Messages
if len(messages) <= 0 {
if msg_rq_cnt > 3 {
if job, exists := historyJobs.Get(subjectChannelID); exists {
job.Status = historyStatusCompletedNoMoreMessages
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
}
writeHistoryCache(channel.ID, historyCache{
Updated: time.Now(),
Running: false,
RunningBefore: "",
CompletedSince: lastMessageID,
})
break MessageRequestingLoop
} else { // retry to make sure no more
time.Sleep(10 * time.Millisecond)
goto request_messages
}
}
// Set New Range, this shouldn't be changed regardless of before/since filters. The bot will always go latest to oldest.
beforeID = messages[len(messages)-1].ID
beforeTime = messages[len(messages)-1].Timestamp
sinceID = ""
// Process Messages
if sourceConfig.HistoryTyping != nil && !autorun {
if *sourceConfig.HistoryTyping && hasPermsToRespond {
bot.ChannelTyping(commandingMessage.ChannelID)
}
}
for _, message := range messages {
// Ordered to Cancel
if job, exists := historyJobs.Get(subjectChannelID); exists {
if job.Status == historyStatusAbortRequested {
job.Status = historyStatusAbortCompleted
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
deleteHistoryCache(channel.ID) //TODO: Replace with different variation of writing cache?
break MessageRequestingLoop
}
}
lastMessageID = message.ID
// Check Message Range
message64, _ := strconv.ParseInt(message.ID, 10, 64)
if before != "" {
before64, _ := strconv.ParseInt(before, 10, 64)
if message64 > before64 { // keep scrolling back in messages
continue
}
}
if since != "" {
since64, _ := strconv.ParseInt(since, 10, 64)
if message64 < since64 { // message too old, kill loop
if job, exists := historyJobs.Get(subjectChannelID); exists {
job.Status = historyStatusCompletedToSinceFilter
job.Updated = time.Now()
historyJobs.Set(subjectChannelID, job)
}
deleteHistoryCache(channel.ID) // unsure of consequences of caching when using filters, so deleting to be safe for now.
break MessageRequestingLoop
}
}
// Process Message
timeStartingDownload := time.Now()
downloadedFiles := handleMessage(message, &channel, false, true)
if len(downloadedFiles) > 0 {
totalDownloads += int64(len(downloadedFiles))
for _, file := range downloadedFiles {
totalFilesize += file.Filesize
}
historyDownloadDuration += time.Since(timeStartingDownload)
}
totalMessages++
}
}
}
// Final log
log.Println(lg("History", "", color.HiGreenString, logPrefix+"Finished history for \"%s\", %s files, %s total",
sourceName, formatNumber(totalDownloads), humanize.Bytes(uint64(totalFilesize))))
// Final status update
if sendStatus {
jobStatus := "Unknown"
if job, exists := historyJobs.Get(subjectChannelID); exists {
jobStatus = historyStatusLabel(job.Status)
}
var status string
if totalDownloads == 0 {
status = fmt.Sprintf(
"``%s:`` **No files found...**\n"+
"_%s total messages processed, avg %d msg/s_\n\n"+
"%s\n\n"+ // msgSourceDisplay^
"**DONE!** - %s\n"+
"Ran ``%d`` message history requests\n\n"+
"%s_Duration was %s_",
timeSinceShort(historyStartTime),
formatNumber(int64(totalMessages)), int(float64(totalMessages)/time.Since(historyStartTime).Seconds()),
msgSourceDisplay,
jobStatus,
messageRequestCount,
rangeContent, timeSince(historyStartTime),
)
} else {
status = fmt.Sprintf(
"``%s:`` **%s total files downloaded!**\n`%s total, avg %1.1f MB/s`\n"+
"_%s total messages processed, avg %d msg/s_\n\n"+
"%s\n\n"+ // msgSourceDisplay^
"**DONE!** - %s\n"+
"Ran ``%d`` message history requests\n\n"+
"%s_Duration was %s_",
timeSinceShort(historyStartTime), formatNumber(int64(totalDownloads)),
humanize.Bytes(uint64(totalFilesize)), float64(totalFilesize/humanize.MByte)/historyDownloadDuration.Seconds(),
formatNumber(int64(totalMessages)), int(float64(totalMessages)/time.Since(historyStartTime).Seconds()),
msgSourceDisplay,
jobStatus,
messageRequestCount,
rangeContent, timeSince(historyStartTime),
)
}
if !hasPermsToRespond {
log.Println(lg("History", "", color.HiRedString, logPrefix+fmtBotSendPerm, responseMsg.ChannelID))
} else {
if responseMsg == nil {
log.Println(lg("History", "", color.RedString,
logPrefix+"Tried to edit status message but it doesn't exist, sending new one."))
if _, err = replyEmbed(commandingMessage, "Command — History", status); err != nil { // Failed to Edit Status, Send New Message
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to send replacement status message:\t%s", err))
}
} else {
if selfbot {
responseMsg, err = bot.ChannelMessageEdit(responseMsg.ChannelID, responseMsg.ID,
fmt.Sprintf("**Command — History**\n\n%s", status))
} else {
responseMsg, err = bot.ChannelMessageEditComplex(&discordgo.MessageEdit{
ID: responseMsg.ID,
Channel: responseMsg.ChannelID,
Embed: buildEmbed(responseMsg.ChannelID, "Command — History", status),
})
}
// Edit failure
if err != nil {
log.Println(lg("History", "", color.RedString,
logPrefix+"Failed to edit status message, sending new one:\t%s", err))
if _, err = replyEmbed(responseMsg, "Command — History", status); err != nil {
log.Println(lg("History", "", color.HiRedString,
logPrefix+"Failed to send replacement status message:\t%s", err))
}
}
}
}
}
}
}
return int(totalDownloads)
}