telegram-notifier/notifier/sender/sender.go

62 lines
1.3 KiB
Go
Raw Normal View History

package sender
import (
"context"
"time"
2023-03-11 15:21:03 +00:00
"git.faercol.me/faercol/telegram-notifier/notifier/config"
"git.faercol.me/faercol/telegram-notifier/notifier/logger"
"github.com/ahugues/go-telegram-api/bot"
"github.com/ahugues/go-telegram-api/structs"
"github.com/sirupsen/logrus"
)
type Sender struct {
ctx context.Context
cancel context.CancelFunc
tgBot bot.Bot
tgChatID int64
timeGetter func() time.Time
errChan chan error
exitChan chan struct{}
msgChan <-chan string
logger *logrus.Logger
}
func (s *Sender) Run(ctx context.Context) {
s.ctx, s.cancel = context.WithCancel(ctx)
for {
select {
case msg := <-s.msgChan:
s.logger.Debug("Sending a new message")
s.tgBot.SendMessage(s.ctx, s.tgChatID, msg, structs.FormattingMarkdownV2)
case <-s.ctx.Done():
s.logger.Info("Stopping Telegram sender")
s.exitChan <- struct{}{}
return
}
}
}
func (s *Sender) ErrChan() <-chan error {
return s.errChan
}
func (s *Sender) Exit() <-chan struct{} {
return s.exitChan
}
func New(config *config.Config, msgChan <-chan string) *Sender {
tgBot := bot.New(config.Telegram.Token)
return &Sender{
tgBot: tgBot,
tgChatID: config.Telegram.ChannelID,
timeGetter: time.Now,
errChan: make(chan error, 10),
exitChan: make(chan struct{}, 1),
logger: &logger.L,
msgChan: msgChan,
}
}