-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathdiscord.go
1429 lines (1312 loc) · 45.1 KB
/
discord.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
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"log"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/AvraamMavridis/randomcolor"
"github.com/aidarkhanov/nanoid/v2"
"github.com/bwmarrin/discordgo"
"github.com/dustin/go-humanize"
"github.com/fatih/color"
"github.com/teris-io/shortid"
)
const (
fmtBotSendPerm = "Bot does not have permission to send messages in %s"
)
//#region Getters
func getChannel(channelID string) (*discordgo.Channel, error) {
channel, err := bot.Channel(channelID)
if err != nil {
channel, err = bot.State.Channel(channelID)
}
return channel, err
}
func getChannelErr(channelID string) error {
_, errr := getChannel(channelID)
return errr
}
func getServer(guildID string) (*discordgo.Guild, error) {
guild, err := bot.Guild(guildID)
if err != nil {
guild, err = bot.State.Guild(guildID)
}
return guild, err
}
func getServerErr(guildID string) error {
_, errr := getServer(guildID)
return errr
}
//#endregion
//#region Labels
func getServerLabel(serverID string) (displayLabel string) {
displayLabel = "Discord"
sourceGuild, err := bot.State.Guild(serverID)
if err != nil {
sourceGuild, _ = bot.Guild(serverID)
}
if sourceGuild != nil {
if sourceGuild.Name != "" {
displayLabel = sourceGuild.Name
}
}
return displayLabel
}
func getCategoryLabel(channelID string) (displayLabel string) {
displayLabel = "Category"
sourceChannel, err := bot.State.Channel(channelID)
if err != nil {
sourceChannel, err = bot.Channel(channelID)
}
if err == nil {
if sourceChannel != nil {
sourceParent, err := bot.State.Channel(sourceChannel.ParentID)
if err != nil {
sourceParent, err = bot.Channel(sourceChannel.ParentID)
}
if err == nil {
if sourceParent != nil {
if sourceChannel.Name != "" {
displayLabel = sourceParent.Name
}
}
}
}
}
return displayLabel
}
func getChannelLabel(channelID string, channelData *discordgo.Channel) (displayLabel string) {
displayLabel = channelID
sourceChannel, err := bot.State.Channel(channelID)
if err != nil {
sourceChannel, _ = bot.Channel(channelID)
}
if channelData != nil {
sourceChannel = channelData
}
if sourceChannel != nil {
if sourceChannel.Name != "" {
displayLabel = sourceChannel.Name
} else if sourceChannel.Topic != "" {
displayLabel = sourceChannel.Topic
} else {
switch sourceChannel.Type {
case discordgo.ChannelTypeDM:
displayLabel = "DM"
case discordgo.ChannelTypeGroupDM:
displayLabel = "Group-DM"
}
}
}
return displayLabel
}
func getUserIdentifier(usr discordgo.User) string {
if usr.Discriminator == "0" {
return "@" + usr.Username
}
return fmt.Sprintf("\"%s\"#%s", usr.Username, usr.Discriminator)
}
//#endregion
//#region Time
const (
discordEpoch = 1420070400000
)
//TODO: Clean these two
func discordTimestampToSnowflake(format string, timestamp string) string {
var snowflake string = ""
var err error
parsed, err := time.ParseInLocation(format, timestamp, time.Local)
if err == nil {
snowflake = fmt.Sprint(((parsed.UnixNano() / int64(time.Millisecond)) - discordEpoch) << 22)
} else {
log.Println(lg("Main", "", color.HiRedString,
"Failed to convert timestamp to discord snowflake... Format: '%s', Timestamp: '%s' - Error:\t%s",
format, timestamp, err))
}
return snowflake
}
func discordSnowflakeToTimestamp(snowflake string, format string) string {
i, err := strconv.ParseInt(snowflake, 10, 64)
if err != nil {
return ""
}
t := time.Unix(0, ((i>>22)+discordEpoch)*1000000)
return t.Local().Format(format)
}
//#endregion
//#region Messages
// For command case-insensitivity
func messageToLower(message *discordgo.Message) *discordgo.Message {
newMessage := *message
newMessage.Content = strings.ToLower(newMessage.Content)
return &newMessage
}
func fixMessage(m *discordgo.Message) *discordgo.Message {
// If message content is empty (likely due to userbot/selfbot)
ubIssue := "Message is corrupted due to endpoint restriction"
if m.Content == "" && len(m.Attachments) == 0 && len(m.Embeds) == 0 {
// Get message history
mCache, err := bot.ChannelMessages(m.ChannelID, 20, "", "", "")
if err == nil {
if len(mCache) > 0 {
for _, mCached := range mCache {
if mCached.ID == m.ID {
// Fix original message having empty Guild ID
serverID := m.GuildID
// Replace message
m = mCached
// ^^
if m.GuildID == "" && serverID != "" {
m.GuildID = serverID
}
// Parse commands
botCommands.FindAndExecute(bot, strings.ToLower(config.CommandPrefix), bot.State.User.ID, messageToLower(m))
break
}
}
} else if config.Debug {
log.Println(lg("Debug", "fixMessage",
color.RedString, "%s, and an attempt to get channel messages found nothing...",
ubIssue))
}
} else if config.Debug {
log.Println(lg("Debug", "fixMessage",
color.HiRedString, "%s, and an attempt to get channel messages encountered an error:\t%s", ubIssue, err))
}
}
if m.Content == "" && len(m.Attachments) == 0 && len(m.Embeds) == 0 {
if config.Debug && selfbot {
log.Println(lg("Debug", "fixMessage",
color.YellowString, "%s, and attempts to fix seem to have failed...", ubIssue))
}
}
return m
}
//#endregion
func channelDisplay(channelID string) (sourceName string, sourceChannelName string) {
sourceChannelName = channelID
sourceName = "UNKNOWN"
sourceChannel, err := bot.State.Channel(channelID)
if err != nil {
sourceChannel, _ = bot.Channel(channelID)
}
if sourceChannel != nil {
// Channel Naming
if sourceChannel.Name != "" {
sourceChannelName = "#" + sourceChannel.Name // #example
}
switch sourceChannel.Type {
case discordgo.ChannelTypeGuildText:
case discordgo.ChannelTypeGuildNews:
case discordgo.ChannelTypeGuildNewsThread:
case discordgo.ChannelTypeGuildPrivateThread:
case discordgo.ChannelTypeGuildPublicThread:
// Server Naming
if sourceChannel.GuildID != "" {
sourceGuild, _ := bot.State.Guild(sourceChannel.GuildID)
if sourceGuild != nil && sourceGuild.Name != "" {
sourceName = sourceGuild.Name
}
}
// Category Naming
if sourceChannel.ParentID != "" {
sourceParent, err := bot.State.Channel(sourceChannel.ParentID)
if err != nil {
sourceParent, _ = bot.Channel(sourceChannel.ParentID)
}
if sourceParent != nil {
if sourceParent.Name != "" {
sourceChannelName = sourceParent.Name + " - " + sourceChannelName
}
}
}
case discordgo.ChannelTypeDM:
sourceName = "Direct Messages"
case discordgo.ChannelTypeGroupDM:
sourceName = "Group Messages"
}
}
return sourceName, sourceChannelName
}
//#region Presence
func dataKeys(input string) string {
//TODO: Case-insensitive key replacement. -- If no streamlined way to do it, convert to lower to find substring location but replace normally
if strings.Contains(input, "{{") && strings.Contains(input, "}}") {
countInt := int64(dbDownloadCount()) + *config.InflateDownloadCount
timeNow := time.Now()
keys := [][]string{
{"{{dgVersion}}",
discordgo.VERSION},
{"{{ddgVersion}}",
projectVersion},
{"{{apiVersion}}",
discordgo.APIVersion},
{"{{botUsername}}",
clearPathIllegalChars(botUser.Username)},
{"{{countNoCommas}}",
fmt.Sprint(countInt)},
{"{{count}}",
formatNumber(countInt)},
{"{{countShort}}",
formatNumberShort(countInt)},
{"{{numServers}}",
fmt.Sprint(len(bot.State.Guilds))},
{"{{numBoundChannels}}",
fmt.Sprint(getBoundChannelsCount())},
{"{{numBoundCategories}}",
fmt.Sprint(getBoundCategoriesCount())},
{"{{numBoundServers}}",
fmt.Sprint(getBoundServersCount())},
{"{{numBoundUsers}}",
fmt.Sprint(getBoundUsersCount())},
{"{{numAdminChannels}}",
fmt.Sprint(len(config.AdminChannels))},
{"{{numAdmins}}",
fmt.Sprint(len(config.Admins))},
//TODO: redo time stuff
{"{{timeSavedShort}}",
timeLastUpdated.Format("3:04pm")},
{"{{timeSavedShortTZ}}",
timeLastUpdated.Format("3:04pm MST")},
{"{{timeSavedMid}}",
timeLastUpdated.Format("3:04pm MST 1/2/2006")},
{"{{timeSavedLong}}",
timeLastUpdated.Format("3:04:05pm MST - January 2, 2006")},
{"{{timeSavedShort24}}",
timeLastUpdated.Format("15:04")},
{"{{timeSavedShortTZ24}}",
timeLastUpdated.Format("15:04 MST")},
{"{{timeSavedMid24}}",
timeLastUpdated.Format("15:04 MST 2/1/2006")},
{"{{timeSavedLong24}}",
timeLastUpdated.Format("15:04:05 MST - 2 January, 2006")},
{"{{timeNowShort}}",
timeNow.Format("3:04pm")},
{"{{timeNowShortTZ}}",
timeNow.Format("3:04pm MST")},
{"{{timeNowMid}}",
timeNow.Format("3:04pm MST 1/2/2006")},
{"{{timeNowLong}}",
timeNow.Format("3:04:05pm MST - January 2, 2006")},
{"{{timeNowShort24}}",
timeNow.Format("15:04")},
{"{{timeNowShortTZ24}}",
timeNow.Format("15:04 MST")},
{"{{timeNowMid24}}",
timeNow.Format("15:04 MST 2/1/2006")},
{"{{timeNowLong24}}",
timeNow.Format("15:04:05 MST - 2 January, 2006")},
{"{{uptime}}",
timeSinceShort(startTime)},
}
for _, key := range keys {
if strings.Contains(input, key[0]) {
input = strings.ReplaceAll(input, key[0], key[1])
}
}
}
return input
}
func dataKeysDownload(input string, sourceConfig configurationSource, download downloadRequestStruct, buildingFilename bool) string {
//TODO: same as dataKeys
ret := input
if buildingFilename {
if sourceConfig == emptySourceConfig {
return config.FilenameFormat
}
ret = config.FilenameFormat
if sourceConfig.FilenameFormat != nil {
if *sourceConfig.FilenameFormat != "" {
ret = *sourceConfig.FilenameFormat
}
}
}
if strings.Contains(ret, "{{") && strings.Contains(ret, "}}") {
// Format Filename Date
filenameDateFormat := config.FilenameDateFormat
if sourceConfig.FilenameDateFormat != nil {
if *sourceConfig.FilenameDateFormat != "" {
filenameDateFormat = *sourceConfig.FilenameDateFormat
}
}
messageTime := download.Message.Timestamp
shortID, err := shortid.Generate()
if err != nil && config.Debug {
log.Println(lg("Debug", "dataKeysDownload", color.HiCyanString, "Error when generating a shortID %s", err))
}
nanoID, err := nanoid.New()
if err != nil && config.Debug {
log.Println(lg("Debug", "dataKeysDownload", color.HiCyanString, "Error when creating a nanoID %s", err))
}
userID := ""
username := ""
if download.Message.Author != nil {
userID = download.Message.Author.ID
username = download.Message.Author.Username
}
channelName := download.Message.ChannelID
categoryID := download.Message.ChannelID
categoryName := download.Message.ChannelID
guildName := download.Message.GuildID
chinfo, err := bot.State.Channel(download.Message.ChannelID)
if err != nil {
chinfo, err = bot.Channel(download.Message.ChannelID)
}
if err == nil {
channelName = chinfo.Name
categoryID = chinfo.ParentID
catinfo, err := bot.State.Channel(categoryID)
if err != nil {
catinfo, err = bot.Channel(categoryID)
}
if err == nil {
categoryName = catinfo.Name
}
}
guildinfo, err := bot.State.Guild(download.Message.GuildID)
if err != nil {
guildinfo, err = bot.Guild(download.Message.GuildID)
}
if err == nil {
guildName = guildinfo.Name
}
domain := "unknown"
if parsedURL, err := url.Parse(download.InputURL); err == nil {
domain = parsedURL.Hostname()
}
fileinfo, err := os.Stat(download.Path + download.Filename)
filesize := "unknown"
if err == nil {
filesize = humanize.Bytes(uint64(fileinfo.Size()))
}
fmt_msg := download.Message.Content
if buildingFilename {
fmt_msg = clearPathIllegalChars(download.Message.Content)
}
fmt_url := download.InputURL
if buildingFilename {
fmt_url = clearPathIllegalChars(download.InputURL)
}
keys := [][]string{
{"{{date}}", messageTime.Format(filenameDateFormat)},
{"{{file}}", download.Filename},
{"{{fileType}}", download.Extension},
{"{{fileSize}}", filesize},
{"{{attachmentID}}", download.AttachmentID},
{"{{messageID}}", download.Message.ID},
{"{{userID}}", userID},
{"{{username}}", username},
{"{{usernameNoLeadPeriod}}", func() string {
usernameCleaned := username
for strings.HasPrefix(usernameCleaned, ".") {
if len(usernameCleaned) <= 1 {
break
} else {
usernameCleaned = usernameCleaned[1:]
}
}
return usernameCleaned
}()},
{"{{channelID}}", download.Message.ChannelID},
{"{{channelName}}", channelName},
{"{{categoryID}}", categoryID},
{"{{categoryName}}", categoryName},
{"{{serverID}}", download.Message.GuildID},
{"{{serverName}}", guildName},
{"{{message}}", fmt_msg},
{"{{downloadTime}}", timeSinceShort(download.StartTime)},
{"{{downloadTimeLong}}", timeSince(download.StartTime)},
{"{{url}}", fmt_url},
{"{{domain}}", domain},
{"{{nanoID}}", nanoID},
{"{{shortID}}", shortID},
{"{{botUsername}}",
clearPathIllegalChars(botUser.Username)},
}
for _, key := range keys {
if strings.Contains(ret, key[0]) {
ret = strings.ReplaceAll(ret, key[0], key[1])
}
}
}
return dataKeys(ret)
}
func dataKeys_DiscordMessage(input string, m *discordgo.Message) string {
ret := input
if strings.Contains(ret, "{{") && strings.Contains(ret, "}}") && m != nil {
// Basic message data
keys := [][]string{
{"{{year}}",
fmt.Sprint(m.Timestamp.Year())},
{"{{monthNum}}",
fmt.Sprintf("%02d", m.Timestamp.Month())},
{"{{dayOfMonth}}",
fmt.Sprintf("%02d", m.Timestamp.Day())},
{"{{hour}}",
fmt.Sprintf("%02d", m.Timestamp.Hour())},
{"{{minute}}",
fmt.Sprintf("%02d", m.Timestamp.Minute())},
{"{{second}}",
fmt.Sprintf("%02d", m.Timestamp.Second())},
{"{{timestamp}}", discordSnowflakeToTimestamp(m.ID, "2006-01-02_15-04-05")},
{"{{timestampYYYYMMDD}}", discordSnowflakeToTimestamp(m.ID, "2006-01-02")},
{"{{timestampHHMMSS}}", discordSnowflakeToTimestamp(m.ID, "15-04-05")},
{"{{messageID}}", m.ID},
{"{{message}}", clearPathIllegalChars(m.Content)},
{"{{channelID}}", m.ChannelID},
{"{{botUsername}}",
clearPathIllegalChars(botUser.Username)},
}
// Author data if present
if m.Author != nil {
keys = append(keys, [][]string{
{"{{userID}}", m.Author.ID},
{"{{username}}", clearPathIllegalChars(m.Author.Username)},
{"{{usernameNoLeadPeriod}}", func() string {
usernameCleaned := clearPathIllegalChars(m.Author.Username)
for strings.HasPrefix(usernameCleaned, ".") {
if len(usernameCleaned) <= 1 {
break
} else {
usernameCleaned = usernameCleaned[1:]
}
}
return usernameCleaned
}()},
{"{{userDisc}}", m.Author.Discriminator},
}...)
}
// Lookup channel
var ch *discordgo.Channel = nil
ch, err = bot.Channel(m.ChannelID)
if err != nil || ch == nil {
ch, _ = bot.State.Channel(m.ChannelID)
}
if ch != nil {
keys = append(keys, [][]string{
{"{{channelName}}", clearPathIllegalChars(ch.Name)},
{"{{channelTopic}}", clearPathIllegalChars(ch.Topic)},
{"{{serverID}}", ch.GuildID},
}...)
// Lookup server
var srv *discordgo.Guild = nil
srv, err = bot.Guild(ch.GuildID)
if err != nil || srv == nil {
srv, _ = bot.State.Guild(ch.GuildID)
}
if srv != nil {
keys = append(keys, [][]string{
{"{{serverName}}", clearPathIllegalChars(srv.Name)},
}...)
}
// Lookup parent channel
if ch.ParentID != "" {
var cat *discordgo.Channel = nil
cat, err = bot.Channel(ch.ParentID)
if err != nil || cat == nil {
cat, _ = bot.State.Channel(ch.ParentID)
}
if cat != nil {
if cat.Type == discordgo.ChannelTypeGuildCategory {
keys = append(keys, [][]string{
{"{{categoryID}}", cat.ID},
{"{{categoryName}}", clearPathIllegalChars(cat.Name)},
{"{{forumID}}", ch.ID}, // no check that this is actually a forum, just accountability so it's not using {{}}
{"{{forumName}}", clearPathIllegalChars(ch.Name)}, // ^^^
}...)
} else {
keys = append(keys, [][]string{
{"{{threadID}}", ch.ID},
{"{{threadName}}", clearPathIllegalChars(ch.Name)},
{"{{threadTopic}}", clearPathIllegalChars(ch.Topic)},
{"{{forumID}}", cat.ID},
{"{{forumName}}", clearPathIllegalChars(cat.Name)},
}...)
// Parent Category
if cat.ParentID != "" {
cat2, err := bot.State.Channel(cat.ParentID)
if err != nil {
cat2, err = bot.Channel(cat.ParentID)
}
if err == nil {
keys = append(keys, [][]string{
{"{{categoryID}}", cat2.ID},
{"{{categoryName}}", clearPathIllegalChars(cat2.Name)},
}...)
}
}
}
}
}
}
for _, key := range keys {
if strings.Contains(ret, key[0]) {
ret = strings.ReplaceAll(ret, key[0], key[1])
}
}
}
// Cleanup
ret = strings.ReplaceAll(ret, "{{channelName}}", "DM")
ret = strings.ReplaceAll(ret, "{{channelTopic}}", "DM")
ret = strings.ReplaceAll(ret, "{{serverName}}", "DM")
ret = strings.ReplaceAll(ret, "{{categoryID}}", "Uncategorized")
ret = strings.ReplaceAll(ret, "{{categoryName}}", "Uncategorized")
ret = strings.ReplaceAll(ret, "{{forumID}}", "NOT_FORUM")
ret = strings.ReplaceAll(ret, "{{forumName}}", "NOT_FORUM")
ret = strings.ReplaceAll(ret, "{{threadID}}", "NOT_THREAD")
ret = strings.ReplaceAll(ret, "{{threadName}}", "NOT_THREAD")
ret = strings.ReplaceAll(ret, "{{threadTopic}}", "NOT_THREAD")
return ret
}
func dataKeys_DownloadStatus(input string, status downloadStatusStruct, download downloadRequestStruct) string {
ret := input
if strings.Contains(ret, "{{") && strings.Contains(ret, "}}") {
// Basic message data
keys := [][]string{
{"{{downloadStatus}}", getDownloadStatusShort(status.Status)},
{"{{downloadStatusLong}}", getDownloadStatus(status.Status)},
{"{{downloadFilename}}", download.Filename},
{"{{downloadExt}}", download.Extension},
{"{{downloadPath}}", download.Path},
}
for _, key := range keys {
if strings.Contains(ret, key[0]) {
ret = strings.ReplaceAll(ret, key[0], key[1])
}
}
}
return ret
}
func updateDiscordPresence() {
if bot != nil && botReady && config.PresenceEnabled {
// Vars
countInt := int64(dbDownloadCount()) + *config.InflateDownloadCount
count := formatNumber(countInt)
countShort := formatNumberShort(countInt)
timeShort := timeLastUpdated.Format("3:04pm")
timeLong := timeLastUpdated.Format("3:04:05pm MST - January 2, 2006")
// Defaults
status := fmt.Sprintf("%s - %s files", timeShort, countShort)
statusDetails := timeLong
statusState := fmt.Sprintf("%s files total", count)
// Overwrite Presence
if config.PresenceLabel != nil {
status = *config.PresenceLabel
if status != "" {
status = dataKeys(status)
}
}
// Overwrite Details
if config.PresenceDetails != nil {
statusDetails = *config.PresenceDetails
if statusDetails != "" {
statusDetails = dataKeys(statusDetails)
}
}
// Overwrite State
if config.PresenceState != nil {
statusState = *config.PresenceState
if statusState != "" {
statusState = dataKeys(statusState)
}
}
// Update
bot.UpdateStatusComplex(discordgo.UpdateStatusData{
Game: &discordgo.Game{
Name: status,
Type: config.PresenceType,
Details: statusDetails, // Only visible if real user
State: statusState,
},
Status: config.PresenceStatus,
})
} else if config.PresenceStatus != string(discordgo.StatusOnline) {
bot.UpdateStatusComplex(discordgo.UpdateStatusData{
Status: config.PresenceStatus,
})
}
}
//#endregion
//#region Embeds
func getEmbedColor(channelID string) int {
var err error
var color *string
var channelInfo *discordgo.Channel
// Assign Defined Color
if config.EmbedColor != nil {
if *config.EmbedColor != "" {
color = config.EmbedColor
}
}
// Overwrite with Defined Color for Channel
/*var msg *discordgo.Message
msg.ChannelID = channelID
if channelRegistered(msg) {
sourceConfig := getSource(channelID)
if sourceConfig.OverwriteEmbedColor != nil {
if *sourceConfig.OverwriteEmbedColor != "" {
color = sourceConfig.OverwriteEmbedColor
}
}
}*/
// Use Defined Color
if color != nil {
// Defined as Role, fetch role color
if *color == "role" || *color == "user" {
botColor := bot.State.UserColor(botUser.ID, channelID)
if botColor != 0 {
return botColor
}
goto color_random
}
// Defined as Random, jump below (not preferred method but seems to work flawlessly)
if *color == "random" || *color == "rand" {
goto color_random
}
var colorString string = *color
// Input is Hex
colorString = strings.ReplaceAll(colorString, "#", "")
if convertedHex, err := strconv.ParseUint(colorString, 16, 64); err == nil {
return int(convertedHex)
}
// Input is Int
if convertedInt, err := strconv.Atoi(colorString); err == nil {
return convertedInt
}
// Definition is invalid since hasn't returned, so defaults to below...
}
// User color
channelInfo, err = bot.State.Channel(channelID)
if err != nil {
channelInfo, err = bot.Channel(channelID)
}
if err == nil {
if channelInfo.Type != discordgo.ChannelTypeDM && channelInfo.Type != discordgo.ChannelTypeGroupDM {
if bot.State.UserColor(botUser.ID, channelID) != 0 {
return bot.State.UserColor(botUser.ID, channelID)
}
}
}
// Random color
color_random:
var randomColor string = randomcolor.GetRandomColorInHex()
if convertedRandom, err := strconv.ParseUint(strings.ReplaceAll(randomColor, "#", ""), 16, 64); err == nil {
return int(convertedRandom)
}
return 16777215 // white
}
// Shortcut function for quickly constructing a styled embed with Title & Description
func buildEmbed(channelID string, title string, description string) *discordgo.MessageEmbed {
return &discordgo.MessageEmbed{
Title: title,
Description: description,
Color: getEmbedColor(channelID),
Footer: &discordgo.MessageEmbedFooter{
IconURL: projectIcon,
Text: fmt.Sprintf("%s v%s", projectName, projectVersion),
},
}
}
// Shortcut function for quickly replying a styled embed with Title & Description
func replyEmbed(m *discordgo.Message, title string, description string) (*discordgo.Message, error) {
if m != nil {
if hasPerms(m.ChannelID, discordgo.PermissionSendMessages) {
mention := m.Author.Mention()
if !config.CommandTagging { // Erase mention if tagging disabled
mention = ""
}
if selfbot {
if mention != "" { // Add space if mentioning
mention += " "
}
return bot.ChannelMessageSend(m.ChannelID, fmt.Sprintf("%s**%s**\n\n%s", mention, title, description))
} else {
return bot.ChannelMessageSendComplex(m.ChannelID,
&discordgo.MessageSend{
Content: mention,
Embed: buildEmbed(m.ChannelID, title, description),
},
)
}
}
log.Println(lg("Discord", "replyEmbed", color.HiRedString, fmtBotSendPerm, m.ChannelID))
}
return nil, nil
}
//#endregion
//#region Send Status Message
type sendStatusType int
const (
sendStatusStartup sendStatusType = iota
sendStatusReconnect
sendStatusExit
sendStatusSettings
)
func sendStatusLabel(status sendStatusType) string {
switch status {
case sendStatusStartup:
return "has launched"
case sendStatusReconnect:
return "has reconnected"
case sendStatusExit:
return "is exiting"
case sendStatusSettings:
return "updated settings"
}
return "is confused"
}
func sendStatusMessage(status sendStatusType) {
for _, adminChannel := range config.AdminChannels {
if *adminChannel.LogStatus {
var message string
var label string
var emoji string
//TODO: CLEAN
if status == sendStatusStartup || status == sendStatusReconnect {
label = "startup"
emoji = "🟩"
if status == sendStatusReconnect {
emoji = "🟧"
}
message += fmt.Sprintf("%s %s and connected to %d server%s...\n", projectLabel, sendStatusLabel(status), len(bot.State.Guilds), pluralS(len(bot.State.Guilds)))
message += fmt.Sprintf("\n• Uptime is %s", uptime())
message += fmt.Sprintf("\n• %s total downloads", formatNumber(int64(dbDownloadCount())))
message += fmt.Sprintf("\n• Bound to %d channel%s, %d categories, %d server%s, %d user%s",
getBoundChannelsCount(), pluralS(getBoundChannelsCount()),
getBoundCategoriesCount(),
getBoundServersCount(), pluralS(getBoundServersCount()),
getBoundUsersCount(), pluralS(getBoundUsersCount()),
)
if config.All != nil {
message += "\n• **ALL MODE ENABLED -** Bot will use all available channels"
}
allChannels := getAllRegisteredChannels()
message += fmt.Sprintf("\n• ***Listening to %s channel%s...***\n", formatNumber(int64(len(allChannels))), pluralS(len(allChannels)))
message += fmt.Sprintf("\n_%s_", versions(true))
} else if status == sendStatusExit {
label = "exit"
emoji = "🟥"
message += fmt.Sprintf("%s %s...\n", projectLabel, sendStatusLabel(status))
message += fmt.Sprintf("\n• Uptime was %s", uptime())
message += fmt.Sprintf("\n• %s total downloads", formatNumber(int64(dbDownloadCount())))
message += fmt.Sprintf("\n• Bound to %d channel%s, %d categories, %d server%s, %d user%s",
getBoundChannelsCount(), pluralS(getBoundChannelsCount()),
getBoundCategoriesCount(),
getBoundServersCount(), pluralS(getBoundServersCount()),
getBoundUsersCount(), pluralS(getBoundUsersCount()),
)
} else if status == sendStatusSettings {
label = "settings"
emoji = "🟨"
message += fmt.Sprintf("%s %s...\n", projectLabel, sendStatusLabel(status))
message += fmt.Sprintf("\n• Bound to %d channel%s, %d categories, %d server%s, %d user%s",
getBoundChannelsCount(), pluralS(getBoundChannelsCount()),
getBoundCategoriesCount(),
getBoundServersCount(), pluralS(getBoundServersCount()),
getBoundUsersCount(), pluralS(getBoundUsersCount()),
)
}
// Send
if config.Debug {
log.Println(lg("Debug", "Bot Status", color.YellowString, "Sending log for %s to admin channel: %s",
strings.ToUpper(label), getChannelLabel(adminChannel.ChannelID, nil)))
}
if hasPerms(adminChannel.ChannelID, discordgo.PermissionEmbedLinks) && !selfbot {
bot.ChannelMessageSendEmbed(adminChannel.ChannelID,
buildEmbed(adminChannel.ChannelID, emoji+" Log — Status", message))
} else if hasPerms(adminChannel.ChannelID, discordgo.PermissionSendMessages) {
bot.ChannelMessageSend(adminChannel.ChannelID, message)
} else {
log.Println(lg("Debug", "Bot Status", color.HiRedString, "Perms checks failed for sending %s status log to %s",
strings.ToUpper(label), adminChannel.ChannelID))
}
}
}
}
func sendErrorMessage(err string) {
for _, adminChannel := range config.AdminChannels {
if *adminChannel.LogErrors {
// Send
if hasPerms(adminChannel.ChannelID, discordgo.PermissionEmbedLinks) && !selfbot { // not confident this is the right permission
if config.Debug {
log.Println(lg("Debug", "sendErrorMessage", color.HiCyanString, "Sending embed log for error to %s",
adminChannel.ChannelID))
}
bot.ChannelMessageSendEmbed(adminChannel.ChannelID, buildEmbed(adminChannel.ChannelID, "Log — Error", err))
} else if hasPerms(adminChannel.ChannelID, discordgo.PermissionSendMessages) {
if config.Debug {
log.Println(lg("Debug", "sendErrorMessage", color.HiCyanString, "Sending embed log for error to %s",
adminChannel.ChannelID))
}
bot.ChannelMessageSend(adminChannel.ChannelID, err)
} else {
log.Println(lg("Debug", "sendErrorMessage", color.HiRedString, "Perms checks failed for sending error log to %s",
adminChannel.ChannelID))
}
}
}
}
//#endregion
//#region Permissions
func hasPerms(channelID string, permission int64) bool {
if selfbot {
return true
}
sourceChannel, err := bot.State.Channel(channelID)
if err != nil {
sourceChannel, err = bot.Channel(channelID)
}
if sourceChannel != nil && err == nil {
switch sourceChannel.Type {
case discordgo.ChannelTypeDM:
return true
case discordgo.ChannelTypeGroupDM:
return true
default:
perms, err := bot.UserChannelPermissions(botUser.ID, channelID)
if err == nil {
return perms&permission == permission
}
log.Println(lg("Debug", "hasPerms", color.HiRedString,
"Failed to check permissions (%d) for %s:\t%s", permission, channelID, err))
}
}
return true
}
//#endregion
//#region Download Emojis & Stickers
func downloadDiscordEmojis() {
dataKeysEmoji := func(emoji discordgo.Emoji, serverID string) string {
ret := config.EmojisFilenameFormat
keys := [][]string{
{"{{ID}}", emoji.ID},
{"{{name}}", emoji.Name},
}
for _, key := range keys {
if strings.Contains(ret, key[0]) {
ret = strings.ReplaceAll(ret, key[0], key[1])
}
}
return ret
}
if config.EmojisServers != nil {
// Handle destination
destination := "emojis"
if config.EmojisDestination != nil {
destination = *config.EmojisDestination
}
if err = os.MkdirAll(destination, 0755); err != nil {
log.Println(lg("Discord", "Emojis", color.HiRedString, "Error while creating destination folder \"%s\": %s", destination, err))
}
// Start
log.Println(lg("Discord", "Emojis", color.MagentaString, "Starting emoji downloads..."))
for _, serverID := range *config.EmojisServers {
emojis, err := bot.GuildEmojis(serverID)
if err != nil {
log.Println(lg("Discord", "Emojis", color.HiRedString, "Error fetching emojis from %s... %s", serverID, err))
} else {
guildName := "UNKNOWN"
guild, err := bot.Guild(serverID)
if err == nil {
guildName = guild.Name
}
subfolder := destination + string(os.PathSeparator) + clearPathIllegalChars(guildName)
if err = os.MkdirAll(subfolder, 0755); err != nil {