64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
package notification
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"strconv"
|
|
"text/template"
|
|
|
|
"git.ctrlz.es/mgdelacroix/birthdaybot/model"
|
|
"github.com/charmbracelet/log"
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
|
)
|
|
|
|
type TelegramNotificationService struct {
|
|
logger *log.Logger
|
|
config *model.TelegramNotificationsConfig
|
|
bot *tgbotapi.BotAPI
|
|
}
|
|
|
|
func NewTelegramNotificationService(logger *log.Logger, config *model.TelegramNotificationsConfig) (*TelegramNotificationService, error) {
|
|
bot, err := tgbotapi.NewBotAPI(config.BotToken)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot create bot: %w", err)
|
|
}
|
|
|
|
botUser, err := bot.GetMe()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("cannot get bot information: %w", err)
|
|
}
|
|
|
|
logger.Info("telegram bot initialized", "id", botUser.ID, "username", botUser.UserName)
|
|
|
|
return &TelegramNotificationService{
|
|
logger: logger,
|
|
config: config,
|
|
bot: bot,
|
|
}, nil
|
|
}
|
|
|
|
func (tns *TelegramNotificationService) Notify(birthday *model.Birthday, template *template.Template) error {
|
|
var msgText string
|
|
if template != nil {
|
|
var stringBuffer bytes.Buffer
|
|
if err := template.Execute(&stringBuffer, birthday.ToMap()); err != nil {
|
|
return fmt.Errorf("cannot execute template for birthday: %w", err)
|
|
}
|
|
|
|
msgText = stringBuffer.String()
|
|
} else {
|
|
msgText = fmt.Sprintf("It's %s's birthday! You can reach them out at %s or %s", birthday.Name, birthday.Email, birthday.Phone)
|
|
}
|
|
|
|
chatID, err := strconv.Atoi(tns.config.ChannelID)
|
|
if err != nil {
|
|
return fmt.Errorf("cannot parse ChannelID: %w", err)
|
|
}
|
|
|
|
msg := tgbotapi.NewMessage(int64(chatID), msgText)
|
|
if _, err := tns.bot.Send(msg); err != nil {
|
|
return fmt.Errorf("error sending message: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|