Debian Codegraph @

pkg/services/chat/telegram/telegram.go

raw
1 package telegram
2
3 import (
4 "errors"
5 "fmt"
6 "net/url"
7
8 "github.com/nicholas-fedor/shoutrrr/pkg/format"
9 "github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
10 "github.com/nicholas-fedor/shoutrrr/pkg/types"
11 )
12
13 // Service sends notifications to configured Telegram chats.
14 type Service struct {
15 standard.Standard
16
17 Config *Config
18 pkr format.PropKeyResolver
19 }
20
21 // apiFormat defines the Telegram API endpoint template.
22 const (
23 apiFormat = "https://api.telegram.org/bot%s/%s"
24 maxlength = 4096
25 )
26
27 // ErrMessageTooLong indicates that the message exceeds the maximum allowed length.
28 var (
29 ErrMessageTooLong = errors.New("Message exceeds the max length")
30 )
31
32 // GetConfig returns the current configuration for the service.
33 func (s *Service) GetConfig() *Config {
34 return s.Config
35 }
36
37 // GetID returns the identifier for this service.
38 func (s *Service) GetID() string {
39 return Scheme
40 }
41
42 // Initialize configures the service with a URL and logger.
43 func (s *Service) Initialize(serviceURL *url.URL, logger types.StdLogger) error {
44 s.SetLogger(logger)
45 s.Config = &Config{
46 Preview: true,
47 Notification: true,
48 }
49 s.pkr = format.NewPropKeyResolver(s.Config)
50
51 if err := s.Config.setURL(&s.pkr, serviceURL); err != nil {
52 return err
53 }
54
55 return nil
56 }
57
58 // Send delivers a notification message to Telegram.
59 func (s *Service) Send(message string, params *types.Params) error {
60 if len(message) > maxlength {
61 return ErrMessageTooLong
62 }
63
64 config := *s.Config
65 if err := s.pkr.UpdateConfigFromParams(&config, params); err != nil {
66 return fmt.Errorf("updating config from params: %w", err)
67 }
68
69 return s.sendMessageForChatIDs(message, &config)
70 }
71
72 // sendMessageForChatIDs sends the message to all configured chat IDs.
73 func (s *Service) sendMessageForChatIDs(message string, config *Config) error {
74 for _, chat := range s.Config.Chats {
75 if err := sendMessageToAPI(message, chat, config); err != nil {
76 return err
77 }
78 }
79
80 return nil
81 }
82
83 // sendMessageToAPI sends a message to the Telegram API for a specific chat.
84 func sendMessageToAPI(message, chat string, config *Config) error {
85 client := &Client{token: config.Token}
86 payload := createSendMessagePayload(message, chat, config)
87 _, err := client.SendMessage(&payload)
88
89 return err
90 }