feat: add Telegram bot with notifications and scheduler
This commit is contained in:
74
internal/bot/bot.go
Normal file
74
internal/bot/bot.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package bot
|
||||
|
||||
import (
|
||||
"log"
|
||||
"sync"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
"github.com/daniil/homelab-api/internal/repository"
|
||||
)
|
||||
|
||||
type Bot struct {
|
||||
api *tgbotapi.BotAPI
|
||||
userRepo *repository.UserRepository
|
||||
taskRepo *repository.TaskRepository
|
||||
habitRepo *repository.HabitRepository
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func New(token string, userRepo *repository.UserRepository, taskRepo *repository.TaskRepository, habitRepo *repository.HabitRepository) (*Bot, error) {
|
||||
if token == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
api, err := tgbotapi.NewBotAPI(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Printf("Telegram bot authorized on account %s", api.Self.UserName)
|
||||
|
||||
return &Bot{
|
||||
api: api,
|
||||
userRepo: userRepo,
|
||||
taskRepo: taskRepo,
|
||||
habitRepo: habitRepo,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (b *Bot) Start() {
|
||||
if b == nil || b.api == nil {
|
||||
return
|
||||
}
|
||||
|
||||
u := tgbotapi.NewUpdate(0)
|
||||
u.Timeout = 60
|
||||
|
||||
updates := b.api.GetUpdatesChan(u)
|
||||
|
||||
for update := range updates {
|
||||
if update.Message == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
go b.handleMessage(update.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bot) SendMessage(chatID int64, text string) error {
|
||||
if b == nil || b.api == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
msg := tgbotapi.NewMessage(chatID, text)
|
||||
msg.ParseMode = "HTML"
|
||||
_, err := b.api.Send(msg)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *Bot) GetAPI() *tgbotapi.BotAPI {
|
||||
if b == nil {
|
||||
return nil
|
||||
}
|
||||
return b.api
|
||||
}
|
||||
Reference in New Issue
Block a user