-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelegram.go
More file actions
1199 lines (1038 loc) · 39.7 KB
/
telegram.go
File metadata and controls
1199 lines (1038 loc) · 39.7 KB
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"
"os"
"regexp"
"strconv"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
openai "github.com/sashabaranov/go-openai"
)
type class struct {
Topic string
Date time.Time
MessageID int
}
var currentClass class
// InteractiveNewsSession stores the state of an interactive news session
type InteractiveNewsSession struct {
Step string // "topic_selection", "message_generation"
TopicCandidates []string // 3 topic candidates
SelectedTopic string // The chosen topic
GeneratedMessage string // The generated message
SourceMessages []string // Original messages for candidates
MessageID int // Bot's message ID for editing
}
var interactiveSessions map[int64]*InteractiveNewsSession // key: user ID
func init() {
interactiveSessions = make(map[int64]*InteractiveNewsSession)
}
func botGo() {
bot, err := tgbotapi.NewBotAPI(os.Getenv("BOT_TOKEN"))
if err != nil {
log.Panic(err)
}
me, err := bot.GetMe()
if err != nil {
log.Panicf("me: %#v \n", err)
}
name := me.UserName
bot.Debug = false
log.Printf("Authorized on account %s", bot.Self.UserName)
// Start class scheduler
startClassScheduler(bot)
// Start news scheduler
startNewsScheduler(bot)
u := tgbotapi.NewUpdate(-1) // Use -1 to get the latest updates and skip old ones
u.Timeout = 60
// Enable message_reaction updates to track RSVPs
u.AllowedUpdates = []string{"message", "edited_message", "callback_query", "message_reaction"}
log.Printf("[DEBUG] Requesting updates with offset %d and AllowedUpdates: %v", u.Offset, u.AllowedUpdates)
updates := bot.GetUpdatesChan(u)
for update := range updates {
log.Printf("[DEBUG] Received update ID %d - Message:%v EditedMsg:%v Callback:%v Reaction:%v",
update.UpdateID,
update.Message != nil,
update.EditedMessage != nil,
update.CallbackQuery != nil,
update.MessageReaction != nil)
// Handle message reactions
if update.MessageReaction != nil {
log.Printf("[DEBUG] Processing MessageReaction update")
handleMessageReactionUpdate(update.MessageReaction)
continue
}
// Handle callback queries (button clicks)
if update.CallbackQuery != nil {
handleInteractiveNewsCallback(bot, update.CallbackQuery)
continue
}
if update.Message == nil && update.EditedMessage == nil {
log.Printf("[DEBUG] Skipping update - no recognized content")
continue
}
var text string
var messg *tgbotapi.Message
isNewMessage := false
if update.Message != nil {
messg = update.Message
isNewMessage = true
}
if update.EditedMessage != nil {
messg = update.EditedMessage
}
text = messg.Text
if messg.Chat.IsGroup() || messg.Chat.IsSuperGroup() {
// Track user activity for all groups
if messg.From != nil && messg.From.UserName != "" {
err := trackUserActivity(messg.Chat.ID, messg.From.UserName)
if err != nil {
log.Printf("[ERROR] Failed to track activity: %v", err)
}
}
// Memory feature: process and store message if it's from the memory group
memoryGroupIDStr := os.Getenv("MEMORY_GROUP_ID")
if memoryGroupIDStr != "" {
memoryGroupID, err := getEnvInt64("MEMORY_GROUP_ID")
if err == nil && messg.Chat.ID == memoryGroupID && text != "" && !strings.HasPrefix(text, "/") {
go processMessageForMemory(messg)
}
}
// English review feature - randomly check NEW messages only (not edits) for major mistakes
minLength := getReviewMinLength()
if !isNewMessage && text != "" {
log.Printf("[DEBUG] Skipping review for edited message from user=%s, userID=%d",
messg.From.UserName, messg.From.ID)
}
if isNewMessage && text != "" && isReviewableMessage(text, minLength, messg.From.ID) && shouldReviewMessage() {
log.Printf("[REVIEW] Selected for review: user=%s, userID=%d, chatID=%d, msgID=%d, length=%d",
messg.From.UserName, messg.From.ID, messg.Chat.ID, messg.MessageID, len(text))
review, err := reviewEnglish(text)
if err == nil && review != "" {
log.Printf("[REVIEW] Sending review to chatID=%d, replyTo=%d",
messg.Chat.ID, messg.MessageID)
msg := tgbotapi.NewMessage(messg.Chat.ID, review)
msg.ReplyToMessageID = messg.MessageID
_, err = bot.Send(msg)
if err != nil {
log.Printf("[ERROR] Failed to send review: %v", err)
} else {
log.Printf("[REVIEW] Review sent successfully")
}
} else if err != nil {
log.Printf("[REVIEW] Review failed with error: %v", err)
} else {
log.Printf("[REVIEW] No review to send (no major mistakes or ambiguous response)")
}
}
}
if strings.HasPrefix(strings.ToUpper(text), "/HELP") {
answer := `Commands:
/idiom <term> - Show the definition from idioms.thefreedictionary.com
/stat - Show group activity statistics (admins only, 1/hour)
Mention me @` + name + ` to ask questions (reply to continue conversation)`
// Add optional features if enabled
if geminiClient != nil {
answer += `
Use "image: <prompt>" to generate images with AI`
}
answer += `
Use "read: <text>" to convert text to speech`
msg := tgbotapi.NewMessage(messg.Chat.ID, answer)
msg.ReplyToMessageID = messg.MessageID
_, err := bot.Send(msg)
if err != nil {
log.Printf("Send: %v ", err)
}
continue
}
// Handle /stat command
if strings.HasPrefix(strings.ToUpper(text), "/STAT") {
handleStatCommand(bot, messg)
continue
}
// Handle /class command (owner only)
if strings.HasPrefix(strings.ToUpper(text), "/CLASS ") {
if !isOwner(messg.From.ID) {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Only the bot owner can create classes.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
description := strings.TrimSpace(text[7:]) // Remove "/class "
description = sanitizeClassDescription(description)
if description == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Please provide a class description. Usage: /class <description>")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if there's already an active class
existingClass, err := getActiveClass()
if err != nil {
log.Printf("[ERROR] Failed to check for active class: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Error checking for existing classes.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
if existingClass != nil && !existingClass.Unpinned {
msg := tgbotapi.NewMessage(messg.Chat.ID,
fmt.Sprintf("There's already an active class scheduled: %s\nUse /cancelclass first if you want to replace it.",
existingClass.Description))
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
class, err := createClass(description)
if err != nil {
log.Printf("[ERROR] Failed to create class: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Failed to create class. Please try again.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
berlin, _ := time.LoadLocation("Europe/Berlin")
msg := tgbotapi.NewMessage(messg.Chat.ID,
fmt.Sprintf("✅ Class created!\n\nTopic: %s\nScheduled: %s\n\nAnnouncement will be posted soon.",
class.Description,
class.ScheduledTime.In(berlin).Format("Monday, January 2 at 15:04 MST")))
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Handle /cancelclass command (owner only)
if strings.HasPrefix(strings.ToUpper(text), "/CANCELCLASS") {
if !isOwner(messg.From.ID) {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Only the bot owner can cancel classes.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
class, err := getActiveClass()
if err != nil {
log.Printf("[ERROR] Failed to get active class: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Error checking for active classes.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
if class == nil {
msg := tgbotapi.NewMessage(messg.Chat.ID, "No active class to cancel.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
err = cancelClass(class.ID)
if err != nil {
log.Printf("[ERROR] Failed to cancel class: %v", err)
msg := tgbotapi.NewMessage(messg.Chat.ID, "Failed to cancel class.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Unpin the announcement if it was posted
if class.AnnouncementMessageID > 0 && !class.Unpinned {
groupID, _ := getClassGroupID()
unpinMessage(bot, groupID, class.AnnouncementMessageID)
}
msg := tgbotapi.NewMessage(messg.Chat.ID,
fmt.Sprintf("❌ Class cancelled: %s", class.Description))
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
if strings.HasPrefix(strings.ToUpper(text), "/IDIOM") {
split := strings.Split(text, " ")
answer := ""
if len(split) < 2 {
answer = "Please provide a term to search. Usage: /idiom <term>"
} else {
answer = getIdiom(strings.Join(split[1:], "+"))
if answer == "" {
answer = "Sorry, nothing found about " + strings.Join(split[1:], " ")
}
}
msg := tgbotapi.NewMessage(messg.Chat.ID, answer)
msg.ReplyToMessageID = messg.MessageID
_, err := bot.Send(msg)
if err != nil {
log.Printf("Send: %v ", err)
}
continue
}
// Handle /inews command (owner only, DM only) - Interactive news with confirmations
if strings.HasPrefix(strings.ToUpper(text), "/INEWS") {
// Check if it's a DM (private chat)
if !messg.Chat.IsPrivate() {
msg := tgbotapi.NewMessage(messg.Chat.ID, "This command only works in direct messages.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if user is owner
if !isOwner(messg.From.ID) {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Only the bot owner can use this command.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if memory group is set
if os.Getenv("MEMORY_GROUP_ID") == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (MEMORY_GROUP_ID not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if RANDOM_MESSAGE_PROMPT is set
if os.Getenv("RANDOM_MESSAGE_PROMPT") == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (RANDOM_MESSAGE_PROMPT not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Start interactive session
startInteractiveNewsSession(bot, messg.From.ID, messg.Chat.ID)
continue
}
// Handle /news command (owner only, DM only)
if strings.HasPrefix(strings.ToUpper(text), "/NEWS") {
// Check if it's a DM (private chat)
if !messg.Chat.IsPrivate() {
msg := tgbotapi.NewMessage(messg.Chat.ID, "This command only works in direct messages.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if user is owner
if !isOwner(messg.From.ID) {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Only the bot owner can use this command.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if memory group is set
if os.Getenv("MEMORY_GROUP_ID") == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (MEMORY_GROUP_ID not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if RANDOM_MESSAGE_PROMPT is set
if os.Getenv("RANDOM_MESSAGE_PROMPT") == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (RANDOM_MESSAGE_PROMPT not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Send "working on it" message
workingMsg := tgbotapi.NewMessage(messg.Chat.ID, "🔄 Testing random message feature...\n\n1. Getting random message from last 20 hours...")
sentWorking, _ := bot.Send(workingMsg)
// Step 1: Get random message
randomMessage, err := getRandomRecentMessage()
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to get random message: %v", err))
bot.Send(editMsg)
continue
}
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("✅ Got message (%.100s...)\n\n2. Extracting topic...", randomMessage))
bot.Send(editMsg)
// Step 2: Extract topic
topic, err := extractTopicFromMessage(randomMessage)
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to extract topic: %v", err))
bot.Send(editMsg)
continue
}
editMsg = tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("✅ Extracted topic: \"%s\"\n\n3. Generating random message...", topic))
bot.Send(editMsg)
// Step 3: Generate random message
generatedMessage, err := generateRandomMessage(topic)
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to generate message: %v", err))
bot.Send(editMsg)
continue
}
// Send final result
editMsg = tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
"✅ Test complete! Here's what would be posted:")
bot.Send(editMsg)
resultMsg := tgbotapi.NewMessage(messg.Chat.ID, generatedMessage)
bot.Send(resultMsg)
// Send debug info
debugMsg := tgbotapi.NewMessage(messg.Chat.ID,
fmt.Sprintf("📊 Debug info:\n• Topic: %s\n• Source message: %.100s...",
topic, randomMessage))
bot.Send(debugMsg)
// Reset alert state since /NEWS was used successfully
resetNewsFeature()
continue
}
// Handle /NEWSSTATUS command (owner only, DM only) - Check feature status
if strings.ToUpper(text) == "/NEWSSTATUS" {
// Check if it's a DM (private chat)
if !messg.Chat.IsPrivate() {
msg := tgbotapi.NewMessage(messg.Chat.ID, "This command only works in direct messages.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if user is owner
if !isOwner(messg.From.ID) {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Only the bot owner can use this command.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if memory group is set
if os.Getenv("MEMORY_GROUP_ID") == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (MEMORY_GROUP_ID not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Build status message
var status string
if newsLastAlertTime.IsZero() {
status = "🟢 Active - No alerts sent"
} else {
elapsed := time.Since(newsLastAlertTime)
if elapsed < newsAlertCooldown {
status = fmt.Sprintf("🔴 Disabled - Last alert: %s ago", elapsed.Round(time.Minute))
} else {
status = "🟡 Cooldown expired - Ready to re-enable"
}
}
schedulerStatus := "Running"
if newsScheduler == nil {
schedulerStatus = "Stopped"
}
msg := tgbotapi.NewMessage(messg.Chat.ID,
fmt.Sprintf("📊 News Feature Status\n\nStatus: %s\nScheduler: %s\n\nUse /NEWS to test and re-enable the feature.",
status, schedulerStatus))
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Handle /send_to_chan command (owner only, DM only) - Force send message to group
if strings.HasPrefix(strings.ToUpper(text), "/SEND_TO_CHAN") {
// Check if it's a DM (private chat)
if !messg.Chat.IsPrivate() {
msg := tgbotapi.NewMessage(messg.Chat.ID, "This command only works in direct messages.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if user is owner
if !isOwner(messg.From.ID) {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Only the bot owner can use this command.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if memory group is set
memoryGroupIDStr := os.Getenv("MEMORY_GROUP_ID")
if memoryGroupIDStr == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (MEMORY_GROUP_ID not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
memoryGroupID, err := strconv.ParseInt(memoryGroupIDStr, 10, 64)
if err != nil {
msg := tgbotapi.NewMessage(messg.Chat.ID, fmt.Sprintf("Invalid MEMORY_GROUP_ID: %v", err))
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Check if RANDOM_MESSAGE_PROMPT is set
if os.Getenv("RANDOM_MESSAGE_PROMPT") == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "Random message feature is not configured (RANDOM_MESSAGE_PROMPT not set).")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
// Send "working on it" message
workingMsg := tgbotapi.NewMessage(messg.Chat.ID, "🔄 Generating and sending message to group...\n\n1. Getting random message from last 20 hours...")
sentWorking, _ := bot.Send(workingMsg)
// Step 1: Get random message
randomMessage, err := getRandomRecentMessage()
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to get random message: %v", err))
bot.Send(editMsg)
continue
}
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("✅ Got message\n\n2. Extracting topic..."))
bot.Send(editMsg)
// Step 2: Extract topic
topic, err := extractTopicFromMessage(randomMessage)
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to extract topic: %v", err))
bot.Send(editMsg)
continue
}
editMsg = tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("✅ Extracted topic: \"%s\"\n\n3. Generating random message...", topic))
bot.Send(editMsg)
// Step 3: Generate random message
generatedMessage, err := generateRandomMessage(topic)
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to generate message: %v", err))
bot.Send(editMsg)
continue
}
editMsg = tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("✅ Generated message\n\n4. Sending to group..."))
bot.Send(editMsg)
// Step 4: Send to group
groupMsg := tgbotapi.NewMessage(memoryGroupID, generatedMessage)
sentGroupMsg, err := bot.Send(groupMsg)
if err != nil {
editMsg := tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("❌ Failed to send message to group: %v", err))
bot.Send(editMsg)
continue
}
// Step 5: Record the post
err = recordNewsPost(topic, "", sentGroupMsg.MessageID)
if err != nil {
log.Printf("[NEWS] Error recording news post: %v", err)
// Don't fail if database recording fails
}
// Send final success message
editMsg = tgbotapi.NewEditMessageText(messg.Chat.ID, sentWorking.MessageID,
fmt.Sprintf("✅ Message sent successfully!\n\n• Message ID: %d\n• Topic: %s", sentGroupMsg.MessageID, topic))
bot.Send(editMsg)
// Send a copy of what was sent
resultMsg := tgbotapi.NewMessage(messg.Chat.ID, fmt.Sprintf("Message sent to group:\n\n%s", generatedMessage))
bot.Send(resultMsg)
continue
}
if messg.From.ID == bot.Self.ID ||
update.EditedMessage != nil {
continue
}
// Handle custom topic input for interactive news session
if messg.Chat.IsPrivate() && text != "" && !strings.HasPrefix(text, "/") {
if session, exists := interactiveSessions[messg.From.ID]; exists && session.Step == "topic_selection" {
// User is providing a custom topic
customTopic := strings.TrimSpace(text)
if customTopic == "" {
msg := tgbotapi.NewMessage(messg.Chat.ID, "❌ Topic cannot be empty. Please try again or use /inews to restart.")
msg.ReplyToMessageID = messg.MessageID
bot.Send(msg)
continue
}
session.SelectedTopic = customTopic
session.Step = "message_generation"
// Acknowledge custom topic
ackMsg := tgbotapi.NewMessage(messg.Chat.ID, fmt.Sprintf("✅ Custom topic received: \"%s\"\n\n🔄 Generating message...", customTopic))
bot.Send(ackMsg)
// Generate message
generatedMessage, err := generateRandomMessage(customTopic)
if err != nil {
errorMsg := tgbotapi.NewMessage(messg.Chat.ID, fmt.Sprintf("❌ Failed to generate message: %v", err))
bot.Send(errorMsg)
delete(interactiveSessions, messg.From.ID)
continue
}
session.GeneratedMessage = generatedMessage
// Show generated message with options (truncate if too long)
const maxPreviewLength = 3500 // Leave room for formatting and buttons
previewMessage := generatedMessage
truncated := false
if len(generatedMessage) > maxPreviewLength {
previewMessage = generatedMessage[:maxPreviewLength] + "..."
truncated = true
}
messageText := fmt.Sprintf("✅ Generated message:\n\n%s", previewMessage)
if truncated {
messageText += "\n\n⚠️ Message preview truncated. Full message will be sent to channel."
}
messageText += "\n\n━━━━━━━━━━━━━━━━\nWhat would you like to do?"
keyboard := tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("📤 Send to Channel", "inews:send"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("🔄 Regenerate", "inews:regenerate"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("❌ Cancel", "inews:cancel"),
),
)
msgWithKeyboard := tgbotapi.NewMessage(messg.Chat.ID, messageText)
msgWithKeyboard.ReplyMarkup = keyboard
_, err = bot.Send(msgWithKeyboard)
if err != nil {
log.Printf("[INEWS] Failed to send message with keyboard for user %d: %v", messg.From.ID, err)
errorMsg := tgbotapi.NewMessage(messg.Chat.ID, fmt.Sprintf("❌ Failed to display message: %v", err))
bot.Send(errorMsg)
delete(interactiveSessions, messg.From.ID)
continue
}
log.Printf("[INEWS] Custom topic used by user %d: %s", messg.From.ID, customTopic)
continue
}
}
// Handle replies to bot messages (conversation threading)
if messg.ReplyToMessage != nil && messg.ReplyToMessage.From.ID == bot.Self.ID {
// Check if this is a reply to a class questions request
repliedMsgID := messg.ReplyToMessage.MessageID
targetClass, err := getClassByQuestionsRequestMessageID(repliedMsgID)
if err != nil {
log.Printf("[ERROR] Failed to check for class questions request: %v", err)
}
if targetClass != nil {
// This IS a reply to our request!
if isOwner(messg.From.ID) {
log.Printf("[CLASS] Received owner reply to questions request for class ID=%d. Pinning...", targetClass.ID)
err := pinMessage(bot, messg.Chat.ID, messg.MessageID)
if err != nil {
log.Printf("[ERROR] Failed to pin questions reply: %v", err)
} else {
ack := tgbotapi.NewMessage(messg.Chat.ID, "✅ Pinned! Thanks for the questions/link.")
ack.ReplyToMessageID = messg.MessageID
bot.Send(ack)
}
// Stop further processing for this message
continue
}
}
}
if client != nil && messg.ReplyToMessage != nil && messg.ReplyToMessage.From.ID == bot.Self.ID {
// User is replying to a bot message - check if it's part of a conversation
parentMessageID := messg.ReplyToMessage.MessageID
if _, exists := conversationCache.GetMessage(parentMessageID); exists {
// This is a conversation continuation
log.Printf("[INFO] Conversation continuation detected: user %d replying to message %d",
messg.From.ID, parentMessageID)
// Get system prompt from conversation root
systemPrompt := conversationCache.GetSystemPrompt(parentMessageID)
if systemPrompt == "" {
systemPrompt = "You are a helpful assistant. Provide clear and concise answers."
}
// Build conversation history (last 5 exchanges)
history := conversationCache.BuildConversationHistory(parentMessageID, 5)
// Get GPT answer with conversation context
txt, err := getGPTAnswerWithHistory(text, systemPrompt, history)
if err != nil {
log.Printf("Conversation GPT error: %v", err)
txt = "Sorry, I couldn't process your message."
}
// Send response
msg := tgbotapi.NewMessage(messg.Chat.ID, txt)
msg.ReplyToMessageID = messg.MessageID
sentMsg, err := bot.Send(msg)
if err != nil {
log.Printf("Send: %v ", err)
} else {
// Store user message in conversation tree
conversationCache.AddMessage(&ConversationNode{
MessageID: messg.MessageID,
ParentID: parentMessageID,
ChatID: messg.Chat.ID,
UserID: int(messg.From.ID),
Text: text,
Role: "user",
SystemPrompt: systemPrompt,
Timestamp: time.Now(),
})
// Store bot response in conversation tree
conversationCache.AddMessage(&ConversationNode{
MessageID: sentMsg.MessageID,
ParentID: messg.MessageID,
ChatID: messg.Chat.ID,
UserID: int(bot.Self.ID),
Text: txt,
Role: "assistant",
SystemPrompt: systemPrompt,
Timestamp: time.Now(),
})
}
continue
}
}
// Handle GPT questions when bot is mentioned (but not "read:" or "image:" prefix)
if client != nil && strings.Contains(strings.ToUpper(text), strings.ToUpper(name)) {
upperText := strings.ToUpper(text)
// Skip if this is a "read:" or "image:" request
isRead := strings.HasPrefix(upperText, "READ:") || strings.Contains(upperText, " READ:")
isImage := strings.HasPrefix(upperText, "IMAGE:") || strings.Contains(upperText, " IMAGE:")
if !isRead && !isImage {
// Extract question and remove bot mention
question := regexp.MustCompile(`(?i)@`+name).ReplaceAllLiteralString(text, "")
question = strings.TrimSpace(question)
if question != "" {
log.Printf("GPT request: %s", question)
systemPrompt := os.Getenv("GPT_SYSTEM_PROMPT")
if systemPrompt == "" {
systemPrompt = "You are a helpful assistant. Provide clear and concise answers."
}
// Check if we should enable memory tool for this chat/user
var txt string
var err error
if shouldEnableMemoryTool(messg.Chat.ID, messg.From.ID) {
log.Printf("[INFO] Enabling memory search tool for chat %d, user %d", messg.Chat.ID, messg.From.ID)
tools := []openai.Tool{getSearchChatHistoryTool()}
txt, err = getGPTAnswerWithSystemAndTools(question, systemPrompt, tools)
} else {
txt, err = getGPTAnswerWithSystem(question, systemPrompt)
}
if err != nil {
log.Printf("GPT error: %v", err)
txt = "Sorry, I couldn't process your question."
}
msg := tgbotapi.NewMessage(messg.Chat.ID, txt)
msg.ReplyToMessageID = messg.MessageID
sentMsg, err := bot.Send(msg)
if err != nil {
log.Printf("Send: %v ", err)
} else {
// Store initial question and answer in conversation tree
conversationCache.AddMessage(&ConversationNode{
MessageID: messg.MessageID,
ParentID: 0, // Root message
ChatID: messg.Chat.ID,
UserID: int(messg.From.ID),
Text: question,
Role: "user",
SystemPrompt: systemPrompt,
Timestamp: time.Now(),
})
conversationCache.AddMessage(&ConversationNode{
MessageID: sentMsg.MessageID,
ParentID: messg.MessageID,
ChatID: messg.Chat.ID,
UserID: int(bot.Self.ID),
Text: txt,
Role: "assistant",
SystemPrompt: systemPrompt,
Timestamp: time.Now(),
})
}
continue
}
}
}
// Handle "image:" prefix for image generation (only if Gemini is enabled)
upperText := strings.ToUpper(text)
if geminiClient != nil && (strings.HasPrefix(upperText, "IMAGE:") || strings.Contains(upperText, " IMAGE:")) {
// Extract prompt after "image:"
imageIdx := strings.Index(upperText, "IMAGE:")
if imageIdx != -1 {
prompt := strings.TrimSpace(text[imageIdx+6:]) // Skip "image:"
// Remove bot mention if present
prompt = regexp.MustCompile(`(?i)@`+name).ReplaceAllLiteralString(prompt, "")
prompt = strings.TrimSpace(prompt)
if prompt != "" {
log.Printf("[%s] Image generation request: %s\n", messg.From.UserName, prompt)
imageData, err := generateImage(prompt)
if err != nil {
log.Printf("[ERROR] Image generation failed: %v", err)
errorMsg := tgbotapi.NewMessage(messg.Chat.ID, "Sorry, I couldn't generate the image. "+err.Error())
errorMsg.ReplyToMessageID = messg.MessageID
bot.Send(errorMsg)
} else {
photoMsg := tgbotapi.NewPhoto(messg.Chat.ID, tgbotapi.FileBytes{
Name: "generated_image.png",
Bytes: imageData.Bytes(),
})
photoMsg.ReplyToMessageID = messg.MessageID
photoMsg.Caption = "Generated: " + prompt
_, err = bot.Send(photoMsg)
if err != nil {
log.Printf("[ERROR] Failed to send image: %v", err)
}
}
}
}
continue
}
// Handle "read:" prefix for text-to-speech
if strings.HasPrefix(upperText, "READ:") || strings.Contains(upperText, " READ:") {
// Extract text after "read:"
readIdx := strings.Index(upperText, "READ:")
if readIdx != -1 {
textToRead := strings.TrimSpace(text[readIdx+5:]) // Skip "read:"
// Remove bot mention if present
textToRead = regexp.MustCompile(`(?i)@`+name).ReplaceAllLiteralString(textToRead, "")
textToRead = strings.TrimSpace(textToRead)
if textToRead != "" {
log.Printf("[%s] TTS request: %s\n", messg.From.UserName, textToRead)
res := makeSpeech(textToRead)
if res != nil {
file := tgbotapi.FileReader{
Name: "filename",
Reader: res,
}
msg := tgbotapi.NewVoice(messg.Chat.ID, file)
msg.ReplyToMessageID = messg.MessageID
_, err = bot.Send(msg)
if err != nil {
log.Printf("Send: %v ", err)
}
}
}
}
continue
}
}
}
// startInteractiveNewsSession starts an interactive news generation session
func startInteractiveNewsSession(bot *tgbotapi.BotAPI, userID int64, chatID int64) {
// Send initial message
msg := tgbotapi.NewMessage(chatID, "🔄 Starting interactive news session...\n\nGetting 3 random messages from last 20 hours...")
sentMsg, err := bot.Send(msg)
if err != nil {
log.Printf("[INEWS] Failed to send initial message: %v", err)
return
}
// Get 3 random messages and extract topics
var topicCandidates []string
var sourceMessages []string
for i := 0; i < 3; i++ {
randomMessage, err := getRandomRecentMessage()
if err != nil {
editMsg := tgbotapi.NewEditMessageText(chatID, sentMsg.MessageID,
fmt.Sprintf("❌ Failed to get random message: %v", err))
bot.Send(editMsg)
return
}
topic, err := extractTopicFromMessage(randomMessage)
if err != nil {
editMsg := tgbotapi.NewEditMessageText(chatID, sentMsg.MessageID,
fmt.Sprintf("❌ Failed to extract topic from message %d: %v", i+1, err))
bot.Send(editMsg)
return
}
topicCandidates = append(topicCandidates, topic)
sourceMessages = append(sourceMessages, randomMessage)
// Update progress
editMsg := tgbotapi.NewEditMessageText(chatID, sentMsg.MessageID,
fmt.Sprintf("🔄 Processing... (%d/3 topics extracted)", i+1))
bot.Send(editMsg)
}
// Create session
session := &InteractiveNewsSession{
Step: "topic_selection",
TopicCandidates: topicCandidates,
SourceMessages: sourceMessages,
MessageID: sentMsg.MessageID,
}
interactiveSessions[userID] = session
// Show topic selection with buttons
messageText := "✅ Found 3 topic candidates!\n\nPlease select a topic:\n\n"
for i, topic := range topicCandidates {
messageText += fmt.Sprintf("%d. %s\n", i+1, topic)
}
messageText += "\nOr send me your own custom topic as a text message."
keyboard := tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("1️⃣ "+topicCandidates[0], "inews:topic:0"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("2️⃣ "+topicCandidates[1], "inews:topic:1"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("3️⃣ "+topicCandidates[2], "inews:topic:2"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("❌ Cancel", "inews:cancel"),
),
)
editMsg := tgbotapi.NewEditMessageTextAndMarkup(chatID, sentMsg.MessageID, messageText, keyboard)
bot.Send(editMsg)
log.Printf("[INEWS] Started interactive session for user %d with topics: %v", userID, topicCandidates)
}
// showGeneratedMessageWithButtons shows the generated message with action buttons
// It truncates the message if it's too long to fit in a single Telegram message
func showGeneratedMessageWithButtons(bot *tgbotapi.BotAPI, chatID int64, messageID int, generatedMessage string, actionText string) error {
const maxPreviewLength = 3500 // Leave room for formatting and buttons (Telegram limit is 4096)
previewMessage := generatedMessage
truncated := false
if len(generatedMessage) > maxPreviewLength {
previewMessage = generatedMessage[:maxPreviewLength] + "..."
truncated = true
}