-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmain.go
More file actions
2518 lines (2139 loc) · 73.5 KB
/
main.go
File metadata and controls
2518 lines (2139 loc) · 73.5 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
/*
* Copyright (C) 2025 Micr0Byte <micr0@micr0.dev>
* Licensed under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 (AGPLv3)
*/
package main
import (
"Altbot/dashboard"
"bufio"
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
"golang.org/x/image/webp"
"golang.org/x/net/html"
"golang.org/x/text/cases"
"golang.org/x/text/language"
genai "google.golang.org/genai"
openai "github.com/sashabaranov/go-openai"
"github.com/mattn/go-mastodon"
"github.com/nfnt/resize"
)
// Version of the bot
const Version = "2.6"
// AsciiArt is the ASCII art for the bot
const AsciiArt = ` _ _ _ _ _
/_\ | | |_| |__ ___| |_
/ _ \| | _| '_ / _ \ _|
/_/ \_\_|\__|_.__\___/\__|`
const Motto = "アクセシビリティロボット"
type Config struct {
Server struct {
MastodonServer string `toml:"mastodon_server"`
ClientSecret string `toml:"client_secret"`
AccessToken string `toml:"access_token"`
Username string `toml:"username"`
} `toml:"server"`
LLM struct {
Provider string `toml:"provider"`
OllamaModel string `toml:"ollama_model"`
OllamaKeepAlive string `toml:"ollama_keep_alive"`
OllamaTranslationModel string `toml:"ollama_translation_model"`
OllamaTranslationKeepAlive string `toml:"ollama_translation_keep_alive"`
UseTranslationLayer bool `toml:"use_translation_layer"`
PromptAddition string `toml:"prompt_additional_instructions"`
PromptOverride string `toml:"prompt_override"`
} `toml:"llm"`
TransformersServerArgs struct {
Port int `toml:"port"`
Model string `toml:"model"`
Device string `toml:"device"`
MaxMemory float64 `toml:"max_memory"`
TorchDtype string `toml:"torch_dtype"`
} `toml:"transformers"`
Gemini struct {
Model string `toml:"model"`
APIKey string `toml:"api_key"`
Temperature float32 `toml:"temperature"`
TopK int32 `toml:"top_k"`
HarassmentThreshold string `toml:"harassment_threshold"`
HateSpeechThreshold string `toml:"hate_speech_threshold"`
SexuallyExplicitThreshold string `toml:"sexually_explicit_threshold"`
DangerousContentThreshold string `toml:"dangerous_content_threshold"`
} `toml:"gemini"`
Openai struct {
BaseURL string `toml:"base_url"`
Model string `toml:"model"`
APIKey string `toml:"api_key"`
} `toml:"openai"`
Localization struct {
DefaultLanguage string `toml:"default_language"`
} `toml:"localization"`
DNI struct {
Tags []string `toml:"tags"`
IgnoreBots bool `toml:"ignore_bots"`
} `toml:"dni"`
ImageProcessing struct {
DownscaleWidth uint `toml:"downscale_width"`
MaxSizeMB uint `toml:"max_size_mb"`
} `toml:"image_processing"`
VideoProcessing struct {
MaxSizeMB uint `toml:"max_size_mb"`
NumFramesPerSecond float64 `toml:"num_frames_per_second"`
MaxFrames int `toml:"max_frames"`
} `toml:"video_processing"`
Behavior struct {
ReplyVisibility string `toml:"reply_visibility"`
FollowBack bool `toml:"follow_back"`
AskForConsent bool `toml:"ask_for_consent"`
PrivacyPolicyURL string `toml:"privacy_policy_url"`
} `toml:"behavior"`
WeeklySummary struct {
Enabled bool `toml:"enabled"`
PostDay string `toml:"post_day"`
PostTime string `toml:"post_time"`
MessageTemplate string `toml:"message_template"`
Tips []string `toml:"tips"`
} `toml:"weekly_summary"`
API struct {
Enabled bool `toml:"enabled"`
Port int `toml:"port"`
MonthlyLimit int `toml:"monthly_limit"`
KofiVerificationToken string `toml:"kofi_verification_token"`
KofiShopItemCode string `toml:"kofi_shop_item_code"`
KofiTierName string `toml:"kofi_tier_name"`
PostmarkToken string `toml:"postmark_token"`
PostmarkFromEmail string `toml:"postmark_from_email"`
} `toml:"api"`
Metrics struct {
Enabled bool `toml:"enabled"`
DashboardEnabled bool `toml:"dashboard_enabled"`
DashboardPort int `toml:"dashboard_port"`
} `toml:"metrics"`
PowerMetrics struct {
Enabled bool `toml:"enabled"`
GPUWatts float64 `toml:"gpu_watts"`
} `toml:"power_metrics"`
RateLimit struct {
Enabled bool `toml:"enabled"`
MaxRequestsPerMinute int `toml:"max_requests_per_user_per_minute"`
MaxRequestsPerHour int `toml:"max_requests_per_user_per_hour"`
NewAccountMaxRequestsPerMinute int `toml:"new_account_max_requests_per_minute"`
NewAccountMaxRequestsPerHour int `toml:"new_account_max_requests_per_hour"`
NewAccountPeriodDays int `toml:"new_account_period_days"`
ShadowBanThreshold int `toml:"shadow_ban_threshold"`
AdminContactHandle string `toml:"admin_contact_handle"`
} `toml:"rate_limit"`
AltTextReminders struct {
Enabled bool `toml:"enabled"`
ReminderTime int `toml:"reminder_time"`
} `toml:"alt_text_reminders"`
Profile struct {
Enabled bool `toml:"enabled"`
OverrideFeildCount bool `toml:"override_field_count"`
Fields []string `toml:"fields"`
} `toml:"profile"`
}
const (
// Colors
Blue = "\033[34m"
Pink = "\033[38;5;219m"
Green = "\033[32m"
Red = "\033[31m"
Yellow = "\033[33m"
Reset = "\033[0m"
Cyan = "\033[36m"
White = "\033[37m"
)
var defaultConfig Config
var config Config
var client *genai.Client
var geminiModelName string
var geminiGenerationConfig *genai.GenerateContentConfig
var ctx context.Context
var botAcct mastodon.Account
var consentRequests = make(map[mastodon.ID]ConsentRequest)
var videoProcessingCapability = false
var audioProcessingCapability = false
var rateLimiter *RateLimiter
var processingIDs = make(map[mastodon.ID]bool)
var processingIDsMu sync.Mutex
var metricsManager *MetricsManager
var llmProvider LLMProvider
var openaiClient *openai.Client
var openaiModel string
const (
sourceURL = "https://github.com/micr0-dev/Altbot"
donateURL = "https://ko-fi.com/micr0byte"
creator = "@micr0@wetdry.world"
)
var devMode bool
func main() {
setupFlag := flag.Bool("setup", false, "Run the setup wizard")
adminCmd := flag.Bool("admin", false, "Run admin command")
devFlag := flag.Bool("dev", false, "Run in development mode (print to terminal instead of posting)")
flag.Parse()
devMode = *devFlag
// Handle admin commands and exit
if *adminCmd {
args := flag.Args()
RunAdminCommand(args)
return
}
// Load default configuration from example.config.toml
if _, err := toml.DecodeFile("example.config.toml", &defaultConfig); err != nil {
log.Fatalf("Error loading default config from example.config.toml: %v", err)
}
// Check if config.toml exists, if not, create it by copying example.config.toml
if _, err := os.Stat("config.toml"); os.IsNotExist(err) {
if devMode {
// In dev mode, use example.config.toml directly without running setup wizard
log.Println("config.toml not found. Using example.config.toml for dev mode...")
if err := copyConfig("example.config.toml", "config.toml", 5); err != nil {
log.Fatalf("Error creating default config.toml: %v", err)
}
} else {
if err := copyConfig("example.config.toml", "config.toml", 5); err != nil {
log.Fatalf("Error creating default config.toml: %v", err)
}
log.Println("config.toml not found. Running setup wizard...")
*setupFlag = true
}
}
if *setupFlag && !devMode {
runSetupWizard("config.toml")
}
// Load configuration from config.toml
if _, err := toml.DecodeFile("config.toml", &config); err != nil {
log.Fatalf("Error loading config.toml: %v", err)
}
// Compare config with defaultConfig and print warnings or custom settings
customSettingsCount := compareConfigs(defaultConfig, config)
if config.Server.MastodonServer == "https://mastodon.example.com" && !devMode {
log.Fatal("Please configure the Mastodon server in config.toml")
}
var err error
llmProvider, err = NewLLMProvider(config)
if err != nil {
log.Fatalf("Error initializing LLM provider: %v", err)
}
defer llmProvider.Close()
// Set video/audio processing capability based on provider
switch config.LLM.Provider {
case "transformers":
// Transformers server management is now handled by the TransformersProvider
// in setupTransformersProvider, so we don't need to manually check/start it here
// Just set capability flag
videoProcessingCapability = true
// Log that we're using the Transformers provider
fmt.Printf("%s Using Transformers provider with model %s\n",
Yellow, config.TransformersServerArgs.Model)
case "ollama":
err := checkOllamaModel()
if err != nil {
log.Fatalf("Error checking Ollama model: %v", err)
}
case "gemini":
// Gemini supports video/audio processing
videoProcessingCapability = true
audioProcessingCapability = true
case "openai":
// Not yet implemented
videoProcessingCapability = false
audioProcessingCapability = false
default:
log.Fatalf("Unsupported LLM provider: %s", config.LLM.Provider)
}
err = loadLocalizations()
if err != nil {
log.Fatalf("Error loading localizations: %v", err)
}
// Print the version and art
fmt.Printf("%s%s%s%s%s\n", Cyan, AsciiArt, Pink, Motto, Reset)
fmt.Printf("%sAltbot%s v%s (%s)\n", Cyan, Reset, Version, config.LLM.Provider)
if devMode {
fmt.Printf("%s[DEV MODE]%s Interactive testing mode - no Mastodon connection\n", Yellow, Reset)
}
checkForUpdates()
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
// Print capabilities
if videoProcessingCapability {
fmt.Printf("%s Video Processing: %v\n", getStatusSymbol(true), videoProcessingCapability)
} else {
fmt.Printf("%s Video Processing: Unsupported by LLM\n", getStatusSymbol(false))
}
if audioProcessingCapability {
fmt.Printf("%s Audio Processing: %v\n", getStatusSymbol(true), audioProcessingCapability)
} else {
fmt.Printf("%s Audio Processing: Unsupported by LLM\n", getStatusSymbol(false))
}
PromptAdditionState = config.LLM.PromptAddition != ""
if PromptOverrideState {
fmt.Printf("%s Prompt Override: Set to \"%.30s...\"\n", getStatusSymbol(true), config.LLM.PromptOverride)
} else if PromptAdditionState {
fmt.Printf("%s Prompt Additional Instructions: Set to \"%.30s...\"\n", getStatusSymbol(true), config.LLM.PromptAddition)
} else {
fmt.Printf("%s Default Prompts: %s\n", getStatusSymbol(true), "Loaded")
}
// Set up Gemini AI model (needed for dev mode too if using gemini)
err = Setup(config.Gemini.APIKey)
if err != nil && !devMode {
log.Fatal(err)
}
// Set up Open AI compatible model (needed for dev mode too if using openai)
err = openaiSetup(config.Openai.APIKey)
if err != nil && !devMode {
log.Fatal(err)
}
// In dev mode, skip all Mastodon-related initialization
if devMode {
fmt.Printf("%s %d Custom settings loaded\n", getStatusSymbol(customSettingsCount > 0), customSettingsCount)
fmt.Println("\n-----------------------------------")
runDevMode()
return
}
c := mastodon.NewClient(&mastodon.Config{
Server: config.Server.MastodonServer,
ClientSecret: config.Server.ClientSecret,
AccessToken: config.Server.AccessToken,
})
// Fetch and verify the bot account ID
_, err = fetchAndVerifyBotAccountID(c)
if err != nil {
log.Fatalf("Error fetching bot account ID: %v", err)
}
fmt.Printf("%s %d Custom settings loaded\n\n", getStatusSymbol(customSettingsCount > 0), customSettingsCount)
fmt.Printf("%s Mastodon Connection: %s\n", getStatusSymbol(true), config.Server.MastodonServer)
if config.Profile.Enabled {
if err := updateBotProfile(c, config); err != nil {
fmt.Printf("%s Warning: Failed to update profile fields: %v\n", Yellow, err)
}
} else {
fmt.Printf("%s Dynamic Profile Fields: %s\n", getStatusSymbol(false), "Disabled")
}
// Connect to Mastodon streaming API
ws := c.NewWSClient()
events, err := ws.StreamingWSUser(ctx)
if err != nil {
log.Fatalf("Error connecting to streaming API: %v", err)
}
if config.WeeklySummary.Enabled {
go startWeeklySummaryScheduler(c)
fmt.Printf("%s Weekly Summary: %vs %v\n", getStatusSymbol(config.WeeklySummary.Enabled), config.WeeklySummary.PostDay, config.WeeklySummary.PostTime)
} else {
fmt.Printf("%s Weekly Summary: %v\n", getStatusSymbol(config.WeeklySummary.Enabled), config.WeeklySummary.Enabled)
}
if config.AltTextReminders.Enabled {
go checkAltTextPeriodically(c, 1*time.Minute, time.Duration(config.AltTextReminders.ReminderTime)*time.Minute)
fmt.Printf("%s Alt Text Reminders: %v mins\n", getStatusSymbol(config.AltTextReminders.Enabled), config.AltTextReminders.ReminderTime)
} else {
fmt.Printf("%s Alt Text Reminders: %v\n", getStatusSymbol(config.AltTextReminders.Enabled), config.AltTextReminders.Enabled)
}
// Initialize the rate limiter
rateLimiter = NewRateLimiter()
if config.RateLimit.Enabled {
// Load rate limiter state from file
if err := rateLimiter.LoadFromFile("ratelimiter.json"); err != nil {
log.Fatalf("Error loading rate limiter state: %v", err)
}
// Reset minute counts every minute
go func() {
for {
time.Sleep(1 * time.Minute)
rateLimiter.ResetMinuteCounts()
}
}()
// Reset hour counts every hour
go func() {
for {
time.Sleep(1 * time.Hour)
rateLimiter.ResetHourCounts()
}
}()
}
// Start a goroutine for periodic cleanup of old reply entries
go cleanupOldEntries()
if err := loadConsentRequestsFromFile("consent_requests.json"); err != nil {
log.Fatalf("Error loading consent requests: %v", err)
}
go func() {
for {
time.Sleep(1 * time.Hour)
cleanupOldConsentRequests()
}
}()
fmt.Printf("%s GDPR Consent System: ", getStatusSymbol(true))
// Initialize GDPR consent database
if err := InitializeConsentDatabase(); err != nil {
log.Fatalf("Error initializing GDPR consent database: %v", err)
}
// Initialize pending GDPR requests (for PixelFed and similar platforms)
if err := InitializePendingGDPRRequests(); err != nil {
log.Printf("Warning: Error loading pending GDPR requests: %v", err)
}
// Start cleanup routine for expired GDPR requests
StartGDPRCleanupRoutine()
fmt.Printf("%s Legacy Consent System: %v\n", getStatusSymbol(config.Behavior.AskForConsent), config.Behavior.AskForConsent)
// Start metrics manager
metricsManager = NewMetricsManager(config.Metrics.Enabled, "metrics.json", 10*time.Second)
defer metricsManager.stop()
fmt.Printf("%s Metrics Collection: %v\n", getStatusSymbol(config.Metrics.Enabled), config.Metrics.Enabled)
if config.Metrics.DashboardEnabled {
dashboard.StartDashboard("metrics.json", config.Metrics.DashboardPort)
fmt.Printf("%s Metrics Dashboard: %s\n", getStatusSymbol(true), "http://localhost:"+strconv.Itoa(config.Metrics.DashboardPort))
} else {
fmt.Printf("%s Metrics Dashboard: %v\n", getStatusSymbol(false), config.Metrics.DashboardEnabled)
}
if config.API.Enabled {
if err := InitAPIKeyStore("api_keys.json"); err != nil {
log.Fatalf("Error initializing API key store: %v", err)
}
StartAPIServer(config.API.Port, config.API.MonthlyLimit)
}
fmt.Printf("%s Public API: %v\n", getStatusSymbol(config.API.Enabled), config.API.Enabled)
// Display power metrics status if using a local model
if config.LLM.Provider != "gemini" {
powerMetricsStatus := fmt.Sprintf("%v (%.1f watts)", config.PowerMetrics.Enabled, config.PowerMetrics.GPUWatts)
fmt.Printf("%s Power Consumption Metrics: %s\n", getStatusSymbol(config.PowerMetrics.Enabled), powerMetricsStatus)
}
fmt.Println("\n-----------------------------------")
fmt.Println("Connected to streaming API. All systems operational. Waiting for mentions and follows...")
// Main event loop
for event := range events {
switch e := event.(type) {
case *mastodon.NotificationEvent:
switch e.Notification.Type {
case "mention": // Get the ID of the status being replied to
if "@"+e.Notification.Account.Acct == config.RateLimit.AdminContactHandle {
handleAdminReply(c, e.Notification.Status, rateLimiter)
}
if parentStatusRef := e.Notification.Status.InReplyToID; parentStatusRef != nil {
var parentStatusID mastodon.ID
// Convert the parent status ID to the correct type
switch typedID := parentStatusRef.(type) {
case string:
parentStatusID = mastodon.ID(typedID)
case mastodon.ID:
parentStatusID = typedID
}
// Fetch the parent status
parentStatus, err := c.GetStatus(ctx, parentStatusID)
if parentStatus == nil {
log.Printf("Error fetching parent status: %v", err)
break
}
if err != nil {
handleMention(c, e.Notification)
}
// Get the grandparent status ID (the status that the parent was replying to)
grandparentStatusRef := parentStatus.InReplyToID
var grandparentStatusID mastodon.ID
// Convert the grandparent status ID to the correct type
switch typedID := grandparentStatusRef.(type) {
case string:
grandparentStatusID = mastodon.ID(typedID)
case mastodon.ID:
grandparentStatusID = typedID
}
// Check if this is a response to a consent request
if _, isConsentRequest := consentRequests[grandparentStatusID]; isConsentRequest {
handleConsentResponse(c, grandparentStatusID, e.Notification.Status)
} else {
// Check if this might be a GDPR consent response
isGDPRConsent := HandleGDPRConsentResponse(c, e.Notification.Status)
if !isGDPRConsent {
handleMention(c, e.Notification)
}
}
} else {
handleMention(c, e.Notification)
}
case "follow":
handleFollow(c, e.Notification)
}
case *mastodon.UpdateEvent:
handleUpdate(c, e.Status)
case *mastodon.ErrorEvent:
log.Printf("Error event: %v", e.Error())
case *mastodon.DeleteEvent:
handleDeleteEvent(c, e.ID)
}
}
}
// fetchAndVerifyBotAccountID fetches and prints the bot account details to verify the account ID
func fetchAndVerifyBotAccountID(c *mastodon.Client) (mastodon.ID, error) {
acct, err := c.GetAccountCurrentUser(ctx)
if err != nil {
return "", err
}
fmt.Printf("Bot Account ID: %s, Username: %s\n\n", acct.ID, acct.Acct)
botAcct = *acct
return acct.ID, nil
}
// Setup initializes the Gemini AI model with the provided API key
func Setup(apiKey string) error {
if ctx == nil {
ctx = context.Background()
}
if config.LLM.Provider != "gemini" {
return nil
}
if client == nil {
var err error
client, err = genai.NewClient(ctx, &genai.ClientConfig{
APIKey: apiKey,
Backend: genai.BackendGeminiAPI,
})
if err != nil {
return err
}
}
if geminiModelName == "" {
geminiModelName = config.Gemini.Model
}
if geminiGenerationConfig == nil {
geminiGenerationConfig = cloneGenerateContentConfig(&genai.GenerateContentConfig{
Temperature: genai.Ptr(config.Gemini.Temperature),
TopK: genai.Ptr(float32(config.Gemini.TopK)),
})
}
return nil
}
// Setup initializes the Open AI compatible endpoint with the provided API key
func openaiSetup(apiKey string) error {
if ctx == nil {
ctx = context.Background()
}
if config.LLM.Provider != "openai" {
return nil
}
// Create OpenAI compatible client configuration
openaiConfig := openai.DefaultConfig(config.Openai.APIKey)
if config.Openai.BaseURL != "" {
openaiConfig.BaseURL = config.Openai.BaseURL
} else {
openaiConfig.BaseURL = "https://api.openai.com/v1"
}
if config.Openai.Model != "" {
openaiModel = config.Openai.Model
} else {
openaiModel = "gpt-4o-mini"
}
// Create client
if openaiClient == nil {
openaiClient = openai.NewClientWithConfig(openaiConfig)
}
return nil
}
// handleMention processes incoming mentions and generates alt-text descriptions
func handleMention(c *mastodon.Client, notification *mastodon.Notification) {
if isDNI(¬ification.Account) {
return
}
originalStatus := notification.Status.InReplyToID
if originalStatus == nil {
return
}
var originalStatusID mastodon.ID
switch id := originalStatus.(type) {
case string:
originalStatusID = mastodon.ID(id)
case mastodon.ID:
originalStatusID = id
default:
log.Printf("Unexpected type for InReplyToID: %T", originalStatus)
}
status, err := c.GetStatus(ctx, originalStatusID)
if err != nil {
log.Printf("Error fetching original status: %v", err)
return
}
//Check if the original status has any media attachments
if len(status.MediaAttachments) == 0 {
return
}
// Skip if this status is already being processed
processingIDsMu.Lock()
if processingIDs[originalStatusID] {
processingIDsMu.Unlock()
log.Printf("Already processing status %s, skipping duplicate request", originalStatusID)
return
}
processingIDs[originalStatusID] = true
processingIDsMu.Unlock()
defer func() {
processingIDsMu.Lock()
delete(processingIDs, originalStatusID)
processingIDsMu.Unlock()
}()
// Check if the person who mentioned the bot is the OP
if status.Account.ID == notification.Account.ID {
userID := string(notification.Account.ID)
// If user hasn't provided GDPR consent, request it first
if !HasUserConsent(userID) {
log.Printf("User %s has not provided GDPR consent, requesting it", notification.Account.Acct)
_, err := RequestGDPRConsent(c, userID, notification.Account.Acct, notification.Status.Language, notification.Status.ID, false)
if err != nil {
log.Printf("Error requesting GDPR consent: %v", err)
}
return
}
generateAndPostAltText(c, status, notification.Status.ID)
} else if !config.Behavior.AskForConsent {
generateAndPostAltText(c, status, notification.Status.ID)
} else {
requestConsent(c, status, notification)
}
}
// requestConsent asks the original poster for consent to generate alt text
func requestConsent(c *mastodon.Client, status *mastodon.Status, notification *mastodon.Notification) {
// Check if every image in the post already has a Alt text
hasAltText := true
for _, attachment := range status.MediaAttachments {
if attachment.Description == "" && (attachment.Type == "image" || ((attachment.Type == "video" || attachment.Type == "gifv" && videoProcessingCapability) || (attachment.Type == "audio" && audioProcessingCapability))) {
hasAltText = false
}
}
if hasAltText {
return
}
// Check if the original poster has already been asked for consent
if _, ok := consentRequests[status.ID]; ok {
return
}
consentRequests[status.ID] = ConsentRequest{
RequestID: notification.Status.ID,
Timestamp: time.Now(),
}
message := fmt.Sprintf("@%s "+getLocalizedString(notification.Status.Language, "consentRequest", "response"), status.Account.Acct, notification.Account.Acct)
// Dev mode: print to terminal instead of posting
if devMode {
fmt.Printf("\n%s[DEV MODE - Would post consent request]%s\n", Yellow, Reset)
fmt.Printf(" To: @%s\n", status.Account.Acct)
fmt.Printf(" Visibility: unlisted\n")
fmt.Printf(" Content: %s\n", message)
fmt.Println("---")
return
}
_, err := c.PostStatus(ctx, &mastodon.Toot{
Status: message,
InReplyToID: status.ID,
Visibility: "unlisted", // Don't clutter followers' timelines with consent requests
Language: notification.Status.Language,
})
if err != nil {
log.Printf("Error posting consent request: %v", err)
}
if err := saveConsentRequestsToFile("consent_requests.json"); err != nil {
log.Printf("Error saving consent requests: %v", err)
}
}
// handleConsentResponse processes the consent response from the original poster
func handleConsentResponse(c *mastodon.Client, ID mastodon.ID, consentStatus *mastodon.Status) {
originalStatusID := ID
status, err := c.GetStatus(ctx, originalStatusID)
if err != nil {
log.Printf("Error fetching original status for ID %s: %v", originalStatusID, err)
return
}
if consentStatus.Account.Acct != status.Account.Acct {
log.Printf("Unauthorized consent response from: %s, expected: %s", consentStatus.Account.Acct, status.Account.Acct)
return
}
// Clean up HTML content to extract plain text
plainTextContent := stripHTMLTags(consentStatus.Content)
log.Printf("Cleaned consent content: %q from user: %s", plainTextContent, consentStatus.Account.Acct)
if plainTextContent == "" {
log.Printf("No content in consent response from: %s", consentStatus.Account.Acct)
return
}
// Split content into words and check the last word
consentResponse := strings.Fields(plainTextContent)
if len(consentResponse) == 0 {
log.Printf("Empty content after stripping HTML.")
return
}
lastWord := strings.ToLower(consentResponse[len(consentResponse)-1])
log.Printf("Extracted last word: %q from cleaned content", lastWord)
if lastWord == "y" || lastWord == "yes" {
log.Printf("Consent granted by the original poster: %s", consentStatus.Account.Acct)
generateAndPostAltText(c, status, consentStatus.ID)
metricsManager.logConsentRequest(string(status.Account.ID), true)
} else {
log.Printf("Consent denied based on last word: %q from user: %s", lastWord, consentStatus.Account.Acct)
metricsManager.logConsentRequest(string(status.Account.ID), false)
}
delete(consentRequests, originalStatusID)
log.Printf("Removed consent request for ID %s after processing", originalStatusID)
if err := saveConsentRequestsToFile("consent_requests.json"); err != nil {
log.Printf("Error saving consent requests: %v", err)
}
}
// isDNI checks if an account meets the Do Not Interact (DNI) conditions
func isDNI(account *mastodon.Account) bool {
dniList := config.DNI.Tags
if account.Acct == config.Server.Username {
return true
} else if account.Bot && config.DNI.IgnoreBots {
return true
}
for _, tag := range dniList {
if strings.Contains(account.Note, tag) {
return true
}
}
return false
}
// handleFollow processes new follows and follows back
func handleFollow(c *mastodon.Client, notification *mastodon.Notification) {
userID := string(notification.Account.ID)
// Check if the user has already provided GDPR consent
if !HasUserConsent(userID) {
// Send a welcome message with GDPR consent request
log.Printf("New follower %s, sending GDPR consent request", notification.Account.Acct)
// Now send the GDPR consent request as a reply to our welcome message
_, err := RequestGDPRConsent(c, userID, notification.Account.Acct, "en", mastodon.ID(""), true) // Hardcoded to English cuz we don't have the user's language
if err != nil {
log.Printf("Error requesting GDPR consent: %v", err)
}
}
if config.Behavior.FollowBack {
_, err := c.AccountFollow(ctx, notification.Account.ID)
if err != nil {
log.Printf("Error following back: %v", err)
return
}
LogEvent("new_follower")
metricsManager.logFollow(string(notification.Account.ID))
fmt.Printf("Followed back: %s\n", notification.Account.Acct)
}
}
// handleUpdate processes new posts and generates alt-text descriptions if missing
func handleUpdate(c *mastodon.Client, status *mastodon.Status) {
if status.Account.Acct == config.Server.Username {
return
}
userID := string(status.Account.ID)
for _, attachment := range status.MediaAttachments {
if attachment.Type == "image" || ((attachment.Type == "video" || attachment.Type == "gifv" && videoProcessingCapability) || (attachment.Type == "audio" && audioProcessingCapability)) {
if attachment.Description == "" {
if !HasUserConsent(userID) {
// Send a GDPR consent request
_, err := RequestGDPRConsent(c, userID, status.Account.Acct, status.Language, status.ID, false)
if err != nil {
log.Printf("Error requesting GDPR consent: %v", err)
}
return
}
generateAndPostAltText(c, status, status.ID)
break
} else {
LogEventWithUsername("human_written_alt_text", status.Account.Acct)
}
}
}
}
// generateAndPostAltText generates alt-text for images and posts it as a reply
func generateAndPostAltText(c *mastodon.Client, status *mastodon.Status, replyToID mastodon.ID) {
replyPost, err := c.GetStatus(ctx, replyToID)
if err != nil {
log.Printf("Error fetching reply status: %v", err)
return
}
metricsManager.logRequest(string(replyPost.Account.ID))
var wg sync.WaitGroup
var mu sync.Mutex
var responses []string
sucessCount := 0
altTextGenerated := false
altTextAlreadyExists := false
// Track total processing time for power calculation
var totalProcessingTimeMs int64
var isLocalModel bool = config.LLM.Provider != "gemini"
for _, attachment := range status.MediaAttachments {
wg.Add(1)
go func(attachment mastodon.Attachment) {
defer wg.Done()
var altText string
var err error
start := time.Now()
// Check if the user has exceeded their rate limit
if !rateLimiter.Increment(c, string(replyPost.Account.ID)) {
log.Printf("User @%s has exceeded their rate limit", replyPost.Account.Acct)
metricsManager.logRateLimitHit(string(replyPost.Account.ID))
mu.Lock()
responses = append(responses, getLocalizedString(replyPost.Language, "altTextError", "response"))
mu.Unlock()
return
}
if attachment.Type == "image" && attachment.Description == "" {
altText, err = generateImageAltText(attachment.URL, replyPost.Language)
} else if (attachment.Type == "video" || attachment.Type == "gifv") && videoProcessingCapability && attachment.Description == "" {
altText, err = generateVideoAltText(attachment.URL, replyPost.Language)
} else if attachment.Type == "audio" && audioProcessingCapability && attachment.Description == "" {
altText, err = generateAudioAltText(attachment.URL, replyPost.Language)
} else if attachment.Description != "" {
if !altTextGenerated && !altTextAlreadyExists {
mu.Lock()
responses = append(responses, getLocalizedString(replyPost.Language, "imageAlreadyHasAltText", "response"))
mu.Unlock()
altTextAlreadyExists = true
}
return
} else if videoProcessingCapability && audioProcessingCapability {
mu.Lock()
responses = append(responses, getLocalizedString(replyPost.Language, "unsupportedFile", "response"))
mu.Unlock()
return
}
if err != nil {
log.Printf("Error generating alt-text: %v", err)
sucessCount -= 1
altText = getLocalizedString(replyPost.Language, "altTextError", "response")
} else if altText == "" {
log.Printf("Error generating alt-text: Empty response")
sucessCount -= 1
altText = getLocalizedString(replyPost.Language, "altTextError", "response")
}
elapsed := time.Since(start).Milliseconds()
mu.Lock()
responses = append(responses, altText)
totalProcessingTimeMs += elapsed
mu.Unlock()
sucessCount += 1
// Log metrics for successful generation
metricsManager.logSuccessfulGeneration(string(replyPost.Account.ID), attachment.Type, elapsed, replyPost.Language)
}(attachment)
}
wg.Wait()
altTextGenerated = sucessCount > 0
// Combine all responses with a separator
combinedResponse := strings.Join(responses, "\n―\n")
// Prepare the content warning for the reply
contentWarning := status.SpoilerText
if contentWarning != "" && !strings.HasPrefix(contentWarning, "re:") {
contentWarning = "re: " + contentWarning
}
// Add mention to the original poster at the start
combinedResponse = fmt.Sprintf("@%s %s", replyPost.Account.Acct, combinedResponse)
// Add provider attribution
if altTextGenerated {
combinedResponse = fmt.Sprintf("%s\n\n%s", getProviderAttribution(config, replyPost.Language), combinedResponse)
}