feat: Inital commit
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
package notifier
|
||||
|
||||
// Notifier defines the interface for sending notifications.
|
||||
type Notifier interface {
|
||||
// Broadcast sends a message to a given list of chat IDs.
|
||||
Broadcast(chatIDs []int64, message string) error
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user