2023-07-01 17:00:48 +01:00
|
|
|
package notification
|
|
|
|
|
|
|
|
import (
|
2023-07-04 11:29:13 +01:00
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
|
2023-07-01 17:00:48 +01:00
|
|
|
"git.ctrlz.es/mgdelacroix/birthdaybot/model"
|
|
|
|
"github.com/charmbracelet/log"
|
2023-07-04 11:29:13 +01:00
|
|
|
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
2023-07-01 17:00:48 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type TelegramNotificationService struct {
|
|
|
|
logger *log.Logger
|
|
|
|
config *model.TelegramNotificationsConfig
|
2023-07-04 11:29:13 +01:00
|
|
|
bot *tgbotapi.BotAPI
|
2023-07-01 17:00:48 +01:00
|
|
|
}
|
|
|
|
|
2023-07-04 11:29:13 +01:00
|
|
|
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)
|
|
|
|
|
2023-07-01 17:00:48 +01:00
|
|
|
return &TelegramNotificationService{
|
|
|
|
logger: logger,
|
|
|
|
config: config,
|
2023-07-04 11:29:13 +01:00
|
|
|
bot: bot,
|
|
|
|
}, nil
|
2023-07-01 17:00:48 +01:00
|
|
|
}
|
2023-07-01 17:03:15 +01:00
|
|
|
|
|
|
|
func (tns *TelegramNotificationService) Notify(birthday *model.Birthday) error {
|
2023-07-04 11:29:13 +01:00
|
|
|
// ToDo: introduce templates here
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2023-07-01 17:03:15 +01:00
|
|
|
return nil
|
|
|
|
}
|