File: telegram.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.8.17-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,332 kB
  • sloc: sh: 61; makefile: 5
file content (89 lines) | stat: -rw-r--r-- 2,346 bytes parent folder | download
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
package telegram

import (
	"errors"
	"fmt"
	"net/url"

	"github.com/nicholas-fedor/shoutrrr/pkg/format"
	"github.com/nicholas-fedor/shoutrrr/pkg/services/standard"
	"github.com/nicholas-fedor/shoutrrr/pkg/types"
)

// apiFormat defines the Telegram API endpoint template.
const (
	apiFormat = "https://api.telegram.org/bot%s/%s"
	maxlength = 4096
)

// ErrMessageTooLong indicates that the message exceeds the maximum allowed length.
var (
	ErrMessageTooLong = errors.New("Message exceeds the max length")
)

// Service sends notifications to configured Telegram chats.
type Service struct {
	standard.Standard
	Config *Config
	pkr    format.PropKeyResolver
}

// Send delivers a notification message to Telegram.
func (service *Service) Send(message string, params *types.Params) error {
	if len(message) > maxlength {
		return ErrMessageTooLong
	}

	config := *service.Config
	if err := service.pkr.UpdateConfigFromParams(&config, params); err != nil {
		return fmt.Errorf("updating config from params: %w", err)
	}

	return service.sendMessageForChatIDs(message, &config)
}

// Initialize configures the service with a URL and logger.
func (service *Service) Initialize(configURL *url.URL, logger types.StdLogger) error {
	service.SetLogger(logger)
	service.Config = &Config{
		Preview:      true,
		Notification: true,
	}
	service.pkr = format.NewPropKeyResolver(service.Config)

	if err := service.Config.setURL(&service.pkr, configURL); err != nil {
		return err
	}

	return nil
}

// GetID returns the identifier for this service.
func (service *Service) GetID() string {
	return Scheme
}

// sendMessageForChatIDs sends the message to all configured chat IDs.
func (service *Service) sendMessageForChatIDs(message string, config *Config) error {
	for _, chat := range service.Config.Chats {
		if err := sendMessageToAPI(message, chat, config); err != nil {
			return err
		}
	}

	return nil
}

// GetConfig returns the current configuration for the service.
func (service *Service) GetConfig() *Config {
	return service.Config
}

// sendMessageToAPI sends a message to the Telegram API for a specific chat.
func sendMessageToAPI(message string, chat string, config *Config) error {
	client := &Client{token: config.Token}
	payload := createSendMessagePayload(message, chat, config)
	_, err := client.SendMessage(&payload)

	return err
}