Files
pulse-api/internal/bot/bot.go

92 lines
1.7 KiB
Go

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.CallbackQuery != nil {
go b.handleCallback(update.CallbackQuery)
continue
}
if update.Message != nil {
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) SendMessageWithKeyboard(chatID int64, text string, keyboard *tgbotapi.InlineKeyboardMarkup) error {
if b == nil || b.api == nil {
return nil
}
msg := tgbotapi.NewMessage(chatID, text)
msg.ParseMode = "HTML"
if keyboard != nil {
msg.ReplyMarkup = keyboard
}
_, err := b.api.Send(msg)
return err
}
func (b *Bot) GetAPI() *tgbotapi.BotAPI {
if b == nil {
return nil
}
return b.api
}