Files
aimaren/internal/notifier/telegram.go
T
2025-07-26 05:58:59 +00:00

54 lines
1.4 KiB
Go

package notifier
import (
"log"
"sync"
"git.pengzhan.dev/aimaren/internal/config"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
// TelegramNotifier no longer needs to store chat IDs.
type TelegramNotifier struct {
bot *tgbotapi.BotAPI
}
// NewTelegramNotifier is now simpler and only requires the token.
func NewTelegramNotifier(cfg config.Config) (*TelegramNotifier, error) {
bot, err := tgbotapi.NewBotAPI(cfg.Telegram.Token)
if err != nil {
return nil, err
}
return &TelegramNotifier{bot: bot}, nil
}
// Broadcast sends a message to all provided chat IDs in parallel.
func (t *TelegramNotifier) Broadcast(chatIDs []int64, message string) error {
var wg sync.WaitGroup
for _, id := range chatIDs {
wg.Add(1)
// Launch a goroutine for each message to send them concurrently.
go func(chatID int64) {
defer wg.Done()
msg := tgbotapi.NewMessage(chatID, message)
if _, err := t.bot.Send(msg); err != nil {
log.Printf("⚠️ Failed to send Telegram notification to chat ID %d: %v", chatID, err)
}
}(id)
}
// Wait for all messages to be sent before returning.
wg.Wait()
return nil
}
// SendTo sends a message to a single, specific chat ID.
// This is used by the bot-server for welcome messages.
func (t *TelegramNotifier) SendTo(chatID int64, message string) error {
msg := tgbotapi.NewMessage(chatID, message)
_, err := t.bot.Send(msg)
return err
}