-
Notifications
You must be signed in to change notification settings - Fork 1
/
commands.go
1066 lines (1019 loc) · 44.5 KB
/
commands.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 (
"encoding/json"
"fmt"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/MoraGames/clockyuwu/events"
"github.com/MoraGames/clockyuwu/pkg/types"
"github.com/MoraGames/clockyuwu/structs"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/sirupsen/logrus"
)
// Rank is the type used for manage /ranking sorting
type Rank struct {
Username string
Points int
Partecipations int
}
// switch for all the commands that the bot can receive
func manageCommands(update tgbotapi.Update, utils types.Utils, data types.Data, curTime time.Time, eventKey string) {
switch update.Message.Command() {
case "alias":
// Get all set's patterns
text := "Ecco la lista di tutti i set e dei loro vecchi nomi:\n\n"
for _, set := range events.Sets {
text += fmt.Sprintf("%v => %v\n", set.Name, set.Pattern)
}
text += "\nNewNames => OldNames"
// Respond with the message
msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"message": update.Message.Text,
"sender": update.Message.From.UserName,
"chat": update.Message.Chat.Title,
}).Debug("Response to \"/alias\" command sent successfully")
case "check":
// Check actual event infos
if !isAdmin(update.Message.From, utils) {
// Respond and log with a message indicating that the user is not authorized to use this command
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Non sei autorizzato ad usare questo comando")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"cmd": update.Message.Command(),
}).Debug("Unauthorized user")
} else {
// Split the command arguments
cmdArgs := strings.Split(update.Message.CommandArguments(), " ")
if len(cmdArgs) != 1 {
// Respond with a message indicating that the command arguments are wrong
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Il comando è /check <events|users|logs>")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"msg": update.Message.Text,
}).Debug("Wrong command")
} else {
// Check if the command argument is events
switch cmdArgs[0] {
case "logs":
// Check the logs data structure
logTxt, err := os.ReadFile("files/log.txt")
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
}).Error("Error while reading files/log.txt")
}
// Respond with command executed successfully
msg := tgbotapi.NewDocument(update.Message.Chat.ID, tgbotapi.FileBytes{Name: "log.txt", Bytes: logTxt})
msg.Caption = "Log controllati. Ecco lo stato attuale:\n\n"
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /check command sent
utils.Logger.Debug("Logs checked")
case "users":
// Check the logs data structure
usersJson, err := os.ReadFile("files/users.json")
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
}).Error("Error while reading files/users.json")
}
// Respond with command executed successfully
msg := tgbotapi.NewDocument(update.Message.Chat.ID, tgbotapi.FileBytes{Name: "users.json", Bytes: usersJson})
msg.Caption = "Log controllati. Ecco lo stato attuale:\n\n"
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /check command sent
utils.Logger.Debug("Users checked")
case "events":
// Check the events data structure
eventsJson, err := json.MarshalIndent(events.Events, "", " ")
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
"note": "preoccupati",
}).Error("Error while marshalling Events data")
utils.Logger.Error(Users)
}
// Respond with command executed successfully
msg := tgbotapi.NewDocument(update.Message.Chat.ID, tgbotapi.FileBytes{Name: "events.json", Bytes: eventsJson})
msg.Caption = "Eventi controllati. Ecco lo stato attuale:\n\n"
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /check command sent
utils.Logger.Debug("Events checked")
default:
// Respond with a message indicating that the command arguments are wrong
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Il comando è /check <events|users|logs>")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"msg": update.Message.Text,
}).Debug("Wrong command")
}
}
}
case "credits":
// Respond with useful information about the project
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "The source code, available on GitHub at MoraGames/clockyuwu, is written entirely in GoLang and makes use of the \"telegram-bot-api\" library.\nFor any bug reports or feature proposals, please refer to the GitHub project.\n\nDeveloper:\n- Telegram: @MoraGames\n- Discord: @moragames\n- Instagram: @moragames.dev\n- GitHub: MoraGames\n\nProject:\n- Telegram: @clockyuwu_bot\n- GitHub: MoraGames/clockyuwu\n\nSpecial thanks go to the first testers (as well as players) of the minigame managed by the bot, \"Vano\", \"Ale\" and \"Alex\".")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"message": update.Message.Text,
"sender": update.Message.From.UserName,
"chat": update.Message.Chat.Title,
}).Debug("Response to \"/credits\" command sent successfully")
case "help":
// Respond with useful information about the working and commands of the bot
msg := tgbotapi.NewMessage(update.Message.Chat.ID,
ComposeMessage([]string{
"Name: %v\nVersion: %v\n\n",
"This is a list of all possible commands within the bot.\n\n",
"General purpose Commands:\n",
"- /start: Get an introductory message about the bot's features.\n",
"- /help: Get a complete list of all available commands.\n",
"- /credits: Get more informations abount the project.\n",
"- /ping: Verify if the bot is running.\n\n",
"In-Game utils Commands:\n",
"- /ranking: Get the ranking of the current championship.\n",
"- /stats: Get the player's game statistics.\n",
"- /list: Get a list of active seets or effects.\n",
"- /alias: Get a list of all sets and their old names.\n\n",
"Admins only Commands:\n",
"- /check: Get more informations about bot status and data.\n",
"- /reset: Force the execution of a specific Reset() function.\n",
"- /update: Update the value of a data structure.",
"- /send: Send a message to a specific user.",
}, utils.Config.App.Name, utils.Config.App.Version),
)
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"message": update.Message.Text,
"sender": update.Message.From.UserName,
"chat": update.Message.Chat.Title,
}).Debug("Response to \"/help\" command sent successfully")
case "list":
// Respond with the list of all enabled sets
/*
Description:
Retrive the events.Event.Stats data structure and return some useful informations abount current sets or effects.
Forms:
/list sets
/list effects
*/
// Split the command arguments
cmdArgs := strings.Split(update.Message.CommandArguments(), " ")
// Check if the command arguments are in one of the above forms
if len(cmdArgs) != 1 {
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/list <\"sets\"|\"effects\">"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Check if the command argument is sets or effects
switch cmdArgs[0] {
case "sets":
// Respond with the list of all enabled sets
text := fmt.Sprintf("\nSchemi Attivi (%v):\n", events.Events.Stats.EnabledSetsNum)
for _, setName := range events.Events.Stats.EnabledSets {
text += fmt.Sprintf(" | %q\n", setName)
}
SendMessage(tgbotapi.NewMessage(update.Message.Chat.ID, text), update, data, utils)
// Log the command executed successfully
FinalCommandLog("Events.Stats.EnabledSets sent", update, utils)
SuccessResponseLog(update, utils)
case "effects":
// Respond with the list of all enabled sets
text := fmt.Sprintf("\nEffetti Attivi (%v):\n", events.Events.Stats.EnabledEffectsNum)
for effectName, effectNum := range events.Events.Stats.EnabledEffects {
text += fmt.Sprintf(" | %q = %v\n", effectName, effectNum)
}
SendMessage(tgbotapi.NewMessage(update.Message.Chat.ID, text), update, data, utils)
// Log the command executed successfully
FinalCommandLog("Events.Stats.EnabledEffects sent", update, utils)
SuccessResponseLog(update, utils)
default:
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/list <\"sets\"|\"effects\">"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
}
}
case "ping":
// Respond with a "pong" message. Useful for checking if the bot is online
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "pong")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"message": update.Message.Text,
"sender": update.Message.From.UserName,
"chat": update.Message.Chat.Title,
}).Debug("Response to \"/ping\" command sent successfully")
case "ranking":
// Respond with the ranking based on users' points
// Generate the ranking
ranking := make([]Rank, 0)
for _, u := range Users {
if u != nil {
ranking = append(ranking, Rank{u.UserName, u.TotalPoints, u.TotalEventPartecipations})
}
}
// Sort the ranking by points (and partecipations if points are equal)
sort.Slice(
ranking,
func(i, j int) bool {
if ranking[i].Points == ranking[j].Points {
return ranking[i].Partecipations < ranking[j].Partecipations
}
return ranking[i].Points > ranking[j].Points
},
)
// Generate the string to send
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Ancora nessun utente ha partecipato agli eventi della season.")
if len(ranking) != 0 {
leadersPoints := ranking[0].Points
rankingString := ""
for i, r := range ranking {
rankingString += fmt.Sprintf("%v] %v: %v (-%v)\n", i+1, r.Username, r.Points, leadersPoints-r.Points)
}
// Send the message
msg = tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("La classifica è la seguente:\n\n%v", rankingString))
}
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /ranking command sent
utils.Logger.Debug("Ranking sent")
case "reset":
// Reset the events or users data structure
// Check if the user is an bot-admin
if !isAdmin(update.Message.From, utils) {
// Respond and log with a message indicating that the user is not authorized to use this command
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Non sei autorizzato ad usare questo comando")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"cmd": update.Message.Command(),
}).Debug("Unauthorized user")
} else {
// Split the command arguments
cmdArgs := strings.Split(update.Message.CommandArguments(), " ")
// Check if the command arguments are in the form /reset <events|users>
if len(cmdArgs) != 1 {
// Respond with a message indicating that the command arguments are wrong
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Il comando è /reset <events|users|gocron>")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"msg": update.Message.Text,
}).Debug("Wrong command")
} else {
// Check if the command argument is events or users
switch cmdArgs[0] {
case "events":
// Reset the events data structure
events.Events.Reset(
true,
&types.WriteMessageData{Bot: data.Bot, ChatID: update.Message.Chat.ID, ReplyMessageID: update.Message.MessageID},
utils,
)
// Respond with command executed successfully
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Eventi resettati")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /reset command sent
utils.Logger.Debug("Events resetted")
case "users":
// Reset the users data structure
Users = make(map[int64]*structs.User)
// Overwrite the files/users.json file with the new (and empty) data structure
file, err := json.MarshalIndent(Users, "", " ")
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
"note": "preoccupati",
}).Error("Error while marshalling data")
utils.Logger.Error(Users)
}
err = os.WriteFile("files/users.json", file, 0644)
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
"note": "preoccupati tanto",
}).Error("Error while writing data")
utils.Logger.Error(Users)
}
// Respond with command executed successfully
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Utenti resettati")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /reset command sent
utils.Logger.Debug("Users resetted")
case "gocron":
// Get the number of enabled events for the ended day
dailyEnabledEvents := events.Events.Stats.EnabledEventsNum
// Reset the events
events.Events.Reset(
true,
&types.WriteMessageData{Bot: data.Bot, ChatID: update.Message.Chat.ID, ReplyMessageID: update.Message.MessageID},
utils,
)
// Reward the users where DailyEventWins >= 30% of TotalDailyEventWins
// Then reset the daily user's stats (unconditionally)
DailyUserRewardAndReset(
Users,
dailyEnabledEvents,
&types.WriteMessageData{Bot: data.Bot, ChatID: update.Message.Chat.ID, ReplyMessageID: update.Message.MessageID},
utils,
)
// Respond with command executed successfully
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Funzione GoCron eseguita")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /reset command sent
utils.Logger.Debug("GoCron resetted")
default:
// Respond with a message indicating that the command arguments are wrong
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Il comando è /reset <events|users|gocron>")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
// Log the /reset command executed in a wrong form
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"cmd": update.Message.Command(),
}).Debug("Wrong command")
}
}
}
case "send":
// Send a message to a specific user
// Check if the user is an bot-admin
if !isAdmin(update.Message.From, utils) {
// Respond and log with a message indicating that the user is not authorized to use this command
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Non sei autorizzato ad usare questo comando")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"cmd": update.Message.Command(),
}).Debug("Unauthorized user")
} else {
// Split the command arguments
cmdArgs := strings.Split(update.Message.CommandArguments(), " ")
// Check if the command arguments are in the form /send <user> <"hint">
if len(cmdArgs) != 2 {
// Respond with a message indicating that the command arguments are wrong
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Il comando è /send <user> <\"hint\">")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"msg": update.Message.Text,
}).Debug("Wrong command")
} else {
// Get and check if the user exists
username := cmdArgs[0]
var userId int64
var founded bool
for userID, user := range Users {
if user.UserName == username {
founded = true
userId = userID
}
}
if !founded {
// Respond with a message indicating that the user does not exist
SendEntityNotFoundMessage("Utente", username, update, data, utils)
// Log the command failed execution
FinalCommandLog("User not found", update, utils)
} else {
// Check if the message type is valid
messageType := cmdArgs[1]
switch messageType {
case "hint":
// Send the message to the user
ManageRewardMessage(
userId,
&types.WriteMessageData{Bot: data.Bot, ChatID: update.Message.Chat.ID, ReplyMessageID: -1},
utils,
)
// Log the command executed successfully
FinalCommandLog("reward message sent", update, utils)
SuccessResponseLog(update, utils)
default:
// Respond with a message indicating that the command arguments are wrong
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Il comando è /send <user> <\"hint\">")
msg.ReplyToMessageID = update.Message.MessageID
message, error := data.Bot.Send(msg)
if error != nil {
utils.Logger.WithFields(logrus.Fields{
"err": error,
"msg": message,
}).Error("Error while sending message")
}
utils.Logger.WithFields(logrus.Fields{
"usr": update.Message.From.UserName,
"msg": update.Message.Text,
}).Debug("Wrong command")
}
}
}
}
case "start":
// Respond with an introduction message for the users of the bot
msg := tgbotapi.NewMessage(update.Message.Chat.ID,
ComposeMessage([]string{
"%v is a bot that allows you to play a time-wasting game with one or more groups of friends within Telegram groups.",
"Once the bot is added, the game mainly (but not exclusively) involves sending messages in the \"hh:mm\" format at certain times of the day, in exchange for valuable points.",
"The person who has earned the most points at the end of the championship will be the new Clocky Champion!\n",
"Use /help to get a list of all commands or /credits for more information about the project.\n\n- %v, a bot from @MoraGames.",
}, utils.Config.App.Name, utils.Config.App.Name),
)
SendMessage(msg, update, data, utils)
// Log the command executed successfully
FinalCommandLog("\"start message sent", update, utils)
SuccessResponseLog(update, utils)
case "stats":
/*
Description:
Get the stats of the user who sent the command or of the user specified in the command arguments.
Forms:
/stats
/stats [user]
*/
// Check if the command has arguments
if update.Message.CommandArguments() == "" {
// Get the user from the Users data structure
u := Users[update.Message.From.ID]
// Check (and eventually update) the user effects
UpdateUserEffects(update.Message.From.ID)
// Send the message with user's stats
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Non hai ancora partecipato a nessun evento.")
if u != nil {
msg = tgbotapi.NewMessage(update.Message.Chat.ID,
ComposeMessage(
[]string{
"Le tue statistiche sono:\n\n",
"Statistiche odierne:\n",
"- Punti: %v\n- Partecipazioni: %v\n- Vittorie: %v\n- Sconfitte: %v\n\n",
"- Punti/Partecipazioni: %.2f\n- Punti/Vittorie: %.2f\n- Vittorie/Partecipazioni: %.2f\n- Vittorie/Sconfitte: %.2f\n\n",
"Statistiche totali:\n",
"- Punti: %v\n- Partecipazioni: %v\n- Vittorie: %v\n- Sconfitte: %v\n\n",
"- Punti/Partecipazioni: %.2f\n- Punti/Vittorie: %.2f\n- Vittorie/Partecipazioni: %.2f\n- Vittorie/Sconfitte: %.2f\n\n",
"Effetti attivi: %v",
},
u.DailyPoints, u.DailyEventPartecipations, u.DailyEventWins, u.DailyEventPartecipations-u.DailyEventWins,
float64(u.DailyPoints)/float64(u.DailyEventPartecipations), float64(u.DailyPoints)/float64(u.DailyEventWins), float64(u.DailyEventWins)/float64(u.DailyEventPartecipations), float64(u.DailyEventWins)/float64(u.DailyEventPartecipations-u.DailyEventWins),
u.TotalPoints, u.TotalEventPartecipations, u.TotalEventWins, u.TotalEventPartecipations-u.TotalEventWins,
float64(u.TotalPoints)/float64(u.TotalEventPartecipations), float64(u.TotalPoints)/float64(u.TotalEventWins), float64(u.TotalEventWins)/float64(u.TotalEventPartecipations), float64(u.TotalEventWins)/float64(u.TotalEventPartecipations-u.TotalEventWins),
u.StringifyEffects(),
),
)
}
SendMessage(msg, update, data, utils)
// Log the command executed successfully
FinalCommandLog("User.Stats sent", update, utils)
SuccessResponseLog(update, utils)
} else {
// Split the command arguments
cmdArgs := strings.Split(update.Message.CommandArguments(), " ")
if len(cmdArgs) != 1 {
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/stats [user]"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Get and check if the user exists
username := cmdArgs[0]
var userKey int64
var founded bool
for userID, user := range Users {
if user.UserName == username {
founded = true
userKey = userID
}
}
if !founded {
// Respond with a message indicating that the user does not exist
SendEntityNotFoundMessage("Utente", username, update, data, utils)
// Log the command failed execution
FinalCommandLog("User not found", update, utils)
} else {
// Get the user from the Users data structure
u := Users[userKey]
// Check (and eventually update) the user effects
UpdateUserEffects(userKey)
// Send the message with user's stats
msg := tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("%v non ha ancora partecipato a nessun evento.", username))
if u != nil {
msg = tgbotapi.NewMessage(update.Message.Chat.ID,
ComposeMessage(
[]string{
"Le statistiche di %v sono:\n\n",
"Statistiche odierne:\n",
"- Punti: %v\n- Partecipazioni: %v\n- Vittorie: %v\n- Sconfitte: %v\n\n",
"- Punti/Partecipazioni: %.2f\n- Punti/Vittorie: %.2f\n- Vittorie/Partecipazioni: %.2f\n- Vittorie/Sconfitte: %.2f\n\n",
"Statistiche totali:\n",
"- Punti: %v\n- Partecipazioni: %v\n- Vittorie: %v\n- Sconfitte: %v\n\n",
"- Punti/Partecipazioni: %.2f\n- Punti/Vittorie: %.2f\n- Vittorie/Partecipazioni: %.2f\n- Vittorie/Sconfitte: %.2f\n\n",
"Effetti attivi: %v",
},
u.UserName,
u.DailyPoints, u.DailyEventPartecipations, u.DailyEventWins, u.DailyEventPartecipations-u.DailyEventWins,
float64(u.DailyPoints)/float64(u.DailyEventPartecipations), float64(u.DailyPoints)/float64(u.DailyEventWins), float64(u.DailyEventWins)/float64(u.DailyEventPartecipations), float64(u.DailyEventWins)/float64(u.DailyEventPartecipations-u.DailyEventWins),
u.TotalPoints, u.TotalEventPartecipations, u.TotalEventWins, u.TotalEventPartecipations-u.TotalEventWins,
float64(u.TotalPoints)/float64(u.TotalEventPartecipations), float64(u.TotalPoints)/float64(u.TotalEventWins), float64(u.TotalEventWins)/float64(u.TotalEventPartecipations), float64(u.TotalEventWins)/float64(u.TotalEventPartecipations-u.TotalEventWins),
u.StringifyEffects(),
),
)
}
SendMessage(msg, update, data, utils)
// Log the command executed successfully
FinalCommandLog("User.Stats sent", update, utils)
SuccessResponseLog(update, utils)
}
}
}
case "update":
/*
Description:
Update an event (points, enabled, effects) or user (points, partecipations, wins, effects) property.
Forms:
/update [-s|--save] event <event> points <points>
/update [-s|--save] event <event> enabled <enabled>
/update [-s|--save] event <event> effects <effects>
/update [-s|--save] user <user> points <points>
/update [-s|--save] user <user> partecipations <partecipations>
/update [-s|--save] user <user> wins <wins>
/update [-s|--save] user <user> effects <effects>
*/
// Check if the user is an bot-admin
if !isAdmin(update.Message.From, utils) {
// Respond and log with a message indicating that the user is not authorized to use this command
SendUserNotAuthorizedMessage(update, data, utils)
// Log the command failed execution
FinalCommandLog("Unauthorized user", update, utils)
} else {
// Split the command arguments
cmdArgs := strings.Split(update.Message.CommandArguments(), " ")
// Check if the command arguments are in one of the above forms
if ((cmdArgs[0] != "-s" && cmdArgs[0] != "--save") && len(cmdArgs) != 4) || ((cmdArgs[0] == "-s" || cmdArgs[0] == "--save") && len(cmdArgs) != 5) {
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/update [-s|--save] <\"event\"|\"user\"> <event|user> <\"points\"|\"enabled\"|\"effects\"|\"points\"|\"partecipations\"|\"wins\"|\"effects\"> <points|enabled|effects|points|partecipations|wins|effects>"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Check if the first argument is a flag and if true increases the offset to check all the other arguments.
offset := 0
cmdSuccess := false
flag := cmdArgs[0]
if flag == "-s" || flag == "--save" {
offset = 1
}
targetType := cmdArgs[0+offset]
switch targetType {
case "event":
// Get and check if the event exists
eventKey := cmdArgs[1+offset]
if event, ok := events.Events.Map[eventKey]; !ok {
// Respond with a message indicating that the event does not exist
SendEntityNotFoundMessage("Evento", eventKey, update, data, utils)
// Log the command failed execution
FinalCommandLog("Event not found", update, utils)
} else {
targetProperty := cmdArgs[2+offset]
switch targetProperty {
case "points":
// Get and check if the points value is an integer number
points, err := strconv.Atoi(cmdArgs[3+offset])
if err != nil {
// Respond with a message indicating that the points value is not valid
SendParameterNotValidMessage("points", "un numero intero", update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Update the Event.Points value
events.Events.Map[eventKey] = &events.Event{Time: event.Time, Name: event.Name, Points: points, Enabled: event.Enabled, Effects: event.Effects, Activation: event.Activation, Partecipations: event.Partecipations}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("Event.Points", update, data, utils)
// Log the /update command executed successfully
FinalCommandLog("Event.Points updated", update, utils)
SuccessResponseLog(update, utils)
}
case "enabled":
// Get and check if the enabled value is a boolean
enabled, err := strconv.ParseBool(cmdArgs[3+offset])
if err != nil {
// Respond with a message indicating that the enabled value is not valid
SendParameterNotValidMessage("enabled", "un booleano", update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Update the Event.Enabled value
events.Events.Map[eventKey] = &events.Event{Time: event.Time, Name: event.Name, Points: event.Points, Enabled: enabled, Effects: event.Effects, Activation: event.Activation, Partecipations: event.Partecipations}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("Event.Enabled", update, data, utils)
// Log the command executed successfully
FinalCommandLog("Event.Enabled updated", update, utils)
SuccessResponseLog(update, utils)
}
case "effects":
// Get and check if the effects value is a slice of strings
effectsNames, err := types.ParseSlice(cmdArgs[3+offset])
if err != nil {
// Respond with a message indicating that the effects value is not valid
SendParameterNotValidMessage("effects", "una lista di effetti validi", update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Get and check if the effects value is a slice of existing effects
effects := make([]*structs.Effect, 0)
wrongEffect := ""
for _, effectName := range effectsNames {
if _, ok := structs.Effects[effectName]; !ok {
wrongEffect = effectName
break
}
effects = append(effects, structs.Effects[effectName])
}
if wrongEffect == "" {
// Update the Event.Effects value
events.Events.Map[eventKey] = &events.Event{Time: event.Time, Name: event.Name, Points: event.Points, Enabled: event.Enabled, Effects: effects, Activation: event.Activation, Partecipations: event.Partecipations}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("Event.Effects", update, data, utils)
// Log the command executed successfully
FinalCommandLog("Event.Effects updated", update, utils)
SuccessResponseLog(update, utils)
} else {
// Respond with a message indicating that the effect does not exist
SendEntityNotFoundMessage("Effetto", wrongEffect, update, data, utils)
// Log the command failed execution
FinalCommandLog("Effect not found", update, utils)
}
}
default:
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/update <\"event\"|\"user\"> <event|user> <\"points\"|\"enabled\"|\"effects\"|\"points\"|\"partecipations\"|\"wins\"|\"effects\"> <points|enabled|effects|points|partecipations|wins|effects>"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
}
if cmdSuccess && (flag == "-s" || flag == "--save") {
//Save Events on file
eventsFile, err := json.MarshalIndent(events.Events, "", " ")
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
}).Error("Error while marshalling Events data")
}
err = os.WriteFile("files/events.json", eventsFile, 0644)
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
}).Error("Error while writing Events data")
}
}
}
case "user":
// Get and check if the user exists
username := cmdArgs[1+offset]
var userKey int64
for userID, user := range Users {
if user != nil && user.UserName == username {
userKey = userID
}
}
if user, ok := Users[userKey]; !ok {
// Respond with a message indicating that the user does not exist
SendEntityNotFoundMessage("Utente", username, update, data, utils)
// Log the command failed execution
FinalCommandLog("User not found", update, utils)
} else {
targetProperty := cmdArgs[2+offset]
switch targetProperty {
case "points":
// Get and check if the points value is an integer number
points, err := strconv.Atoi(cmdArgs[3+offset])
if err != nil {
// Respond with a message indicating that the points value is not valid
SendParameterNotValidMessage("points", "un numero intero", update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Update the User.TotalPoints value
Users[userKey] = &structs.User{UserName: user.UserName, TotalPoints: points, TotalEventPartecipations: user.TotalEventPartecipations, TotalEventWins: user.TotalEventWins, TotalChampionshipPartecipations: user.TotalChampionshipPartecipations, TotalChampionshipWins: user.TotalChampionshipWins}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("TotalPoints", update, data, utils)
// Log the command executed successfully
FinalCommandLog("User.TotalPoints updated", update, utils)
SuccessResponseLog(update, utils)
}
case "partecipations":
// Get and check if the partecipations value is an integer number >= 0
partecipations, err := strconv.Atoi(cmdArgs[3+offset])
if err != nil || partecipations < 0 {
// Respond with a message indicating that the partecipations value is not valid
SendParameterNotValidMessage("partecipations", "un numero intero positivo", update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Update the User.TotalEventPartecipations value
Users[userKey] = &structs.User{UserName: user.UserName, TotalPoints: user.TotalPoints, TotalEventPartecipations: partecipations, TotalEventWins: user.TotalEventWins, TotalChampionshipPartecipations: user.TotalChampionshipPartecipations, TotalChampionshipWins: user.TotalChampionshipWins}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("TotalEventPartecipations", update, data, utils)
// Log the command executed successfully
FinalCommandLog("User.TotalEventPartecipations updated", update, utils)
SuccessResponseLog(update, utils)
}
case "wins":
// Get and check if the wins value is an integer number >= 0
wins, err := strconv.Atoi(cmdArgs[3+offset])
if err != nil || wins < 0 {
// Respond with a message indicating that the wins value is not valid
msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Parametro <wins> deve essere un numero intero positivo.")
SendMessage(msg, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Update the User.TotalEventWins value
Users[userKey] = &structs.User{UserName: user.UserName, TotalPoints: user.TotalPoints, TotalEventPartecipations: user.TotalEventPartecipations, TotalEventWins: wins, TotalChampionshipPartecipations: user.TotalChampionshipPartecipations, TotalChampionshipWins: user.TotalChampionshipWins}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("TotalEventWins", update, data, utils)
// Log the command executed successfully
FinalCommandLog("User.TotalEventWins updated", update, utils)
SuccessResponseLog(update, utils)
}
case "effects":
// Get and check if the effects value is a slice of strings
effectsNames, err := types.ParseSlice(cmdArgs[3+offset])
if err != nil {
// Respond with a message indicating that the effects value is not valid
SendParameterNotValidMessage("effects", "una lista di effetti validi", update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
} else {
// Get and check if the effects value is a slice of existing effects
effects := make([]*structs.Effect, 0)
wrongEffect := ""
for _, effectName := range effectsNames {
if _, ok := structs.Effects[effectName]; !ok {
wrongEffect = effectName
break
}
effects = append(effects, structs.Effects[effectName])
}
if wrongEffect == "" {
// Update the User.Effects value
Users[userKey] = &structs.User{UserName: user.UserName, TotalPoints: user.TotalPoints, TotalEventPartecipations: user.TotalEventPartecipations, TotalEventWins: user.TotalEventWins, TotalChampionshipPartecipations: user.TotalChampionshipPartecipations, TotalChampionshipWins: user.TotalChampionshipWins, Effects: effects}
cmdSuccess = true
// Respond with command executed successfully
SendPropertyUpdatedMessage("User.Effects", update, data, utils)
// Log the command executed successfully
FinalCommandLog("User.Effects updated", update, utils)
SuccessResponseLog(update, utils)
} else {
// Respond with a message indicating that the effect does not exist
SendEntityNotFoundMessage("Effetto", wrongEffect, update, data, utils)
// Log the command failed execution
FinalCommandLog("Effect not found", update, utils)
}
}
default:
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/update <\"event\"|\"user\"> <event|user> <\"points\"|\"enabled\"|\"effects\"|\"points\"|\"partecipations\"|\"wins\"|\"effects\"> <points|enabled|effects|points|partecipations|wins|effects>"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
}
if cmdSuccess && (flag == "-s" || flag == "--save") {
//Save Users on file
file, err := json.MarshalIndent(Users, "", " ")
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
"note": "preoccupati",
}).Error("Error while marshalling data")
utils.Logger.Error(Users)
}
err = os.WriteFile("files/users.json", file, 0644)
if err != nil {
utils.Logger.WithFields(logrus.Fields{
"err": err,
"note": "preoccupati tanto",
}).Error("Error while writing data")
utils.Logger.Error(Users)
}
}
}
default:
// Respond with a message indicating that the command arguments are wrong
cmdSyntax := "/update <\"event\"|\"user\"> <event|user> <\"points\"|\"enabled\"|\"effects\"|\"points\"|\"partecipations\"|\"wins\"|\"effects\"> <points|enabled|effects|points|partecipations|wins|effects>"
SendWrongCommandSyntaxMessage(cmdSyntax, update, data, utils)
// Log the command failed execution
FinalCommandLog("Wrong command syntax", update, utils)
}
}
}
}
}
// Check if a user is considered bot-admin (saved in .env file)
func isAdmin(user *tgbotapi.User, utils types.Utils) bool {
adminUserIDStr := os.Getenv("TELEGRAM_ADMIN_ID")
if adminUserIDStr == "" {
utils.Logger.WithFields(logrus.Fields{
"env": "TELEGRAM_ADMIN_ID",
}).Panic("Env not set")
}
adminUserID, err := strconv.ParseInt(adminUserIDStr, 10, 64)