Files
worktimeBot/cmd/bot/main.go

186 lines
3.7 KiB
Go

package main
import (
"log/slog"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/joho/godotenv"
"worktimeBot/internal/bot"
"worktimeBot/internal/db"
)
func main() {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelInfo,
})))
godotenv.Load()
token := os.Getenv("BOT_TOKEN")
dbPath := getEnvDefault("DB_PATH", "db.sqlite3")
httpClient := http.DefaultClient
botAPI, err := tgbotapi.NewBotAPIWithClient(token, tgbotapi.APIEndpoint, httpClient)
if err != nil {
slog.Error("failed to create bot API", "error", err)
os.Exit(1)
}
dbStore, err := db.NewStore(dbPath)
if err != nil {
slog.Error("failed to open database", "path", dbPath, "error", err)
os.Exit(1)
}
allowedUsers := parseAllowedUsers(os.Getenv("BOT_ALLOWED_USERS"))
handler := bot.NewHandler(botAPI, dbStore, allowedUsers)
stop := make(chan struct{})
var wg sync.WaitGroup
if url := os.Getenv("BOT_WEBHOOK_URL"); url != "" {
wg.Add(1)
go func() {
defer wg.Done()
startWebhook(botAPI, handler, url)
}()
} else {
if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil {
slog.Error("delete webhook", "error", err)
}
wg.Add(1)
go func() {
defer wg.Done()
dailyReportScheduler(handler, dbStore, stop)
}()
wg.Add(1)
go func() {
defer wg.Done()
startPolling(botAPI, handler, stop)
}()
}
slog.Info("bot started",
"bot_user", botAPI.Self.UserName,
"allowed_users", len(allowedUsers),
"mode", map[bool]string{true: "webhook", false: "polling"}[os.Getenv("BOT_WEBHOOK_URL") != ""],
)
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
s := <-sig
slog.Info("shutting down", "signal", s.String())
close(stop)
wg.Wait()
dbStore.Close()
}
func startPolling(botAPI *tgbotapi.BotAPI, handler *bot.Handler, stop chan struct{}) {
u := tgbotapi.NewUpdate(0)
u.Timeout = 30
updates := botAPI.GetUpdatesChan(u)
for {
select {
case <-stop:
return
case update, ok := <-updates:
if !ok {
return
}
if update.Message != nil {
handler.HandleMessage(update)
}
if update.CallbackQuery != nil {
handler.HandleCallback(update)
}
}
}
}
func parseAllowedUsers(raw string) map[int64]bool {
m := make(map[int64]bool)
for _, s := range strings.Split(raw, ",") {
s = strings.TrimSpace(s)
if s == "" {
continue
}
id, err := strconv.ParseInt(s, 10, 64)
if err == nil {
m[id] = true
} else {
slog.Warn("invalid user ID in BOT_ALLOWED_USERS", "value", s)
}
}
return m
}
func dailyReportScheduler(h *bot.Handler, store *db.Store, stop chan struct{}) {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
checkDailyReports(h, store)
}
}
}
func checkDailyReports(h *bot.Handler, store *db.Store) {
users, err := store.GetAllUsers()
if err != nil {
slog.Error("report scheduler: get users", "error", err)
return
}
now := time.Now().UTC()
for _, u := range users {
if !u.ReportEnabled || !u.IsActive {
continue
}
loc, err := time.LoadLocation(u.Timezone)
if err != nil {
continue
}
localNow := now.In(loc)
today := localNow.Format("2006-01-02")
currentHHMM := localNow.Format("15:04")
if currentHHMM != u.ReportTime {
continue
}
if u.LastReportDate != nil && *u.LastReportDate == today {
continue
}
slog.Info("sending daily report",
"user_id", u.ID, "chat_id", u.ChatID, "timezone", u.Timezone,
)
h.SendDailyReport(u.ID, u.ChatID)
}
}
func getEnvDefault(key, defaultValue string) string {
if val := os.Getenv(key); val != "" {
return val
}
return defaultValue
}