package main import ( "log/slog" "net/http" "os" "strconv" "strings" "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) slog.Info("bot started", "bot_user", botAPI.Self.UserName, "allowed_users", len(allowedUsers), "polling", true, ) webhookURL := os.Getenv("BOT_WEBHOOK_URL") if webhookURL != "" { startWebhook(botAPI, handler, webhookURL) } else { if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil { slog.Error("delete webhook", "error", err) } go dailyReportScheduler(handler, dbStore) u := tgbotapi.NewUpdate(0) u.Timeout = 30 updates := botAPI.GetUpdatesChan(u) for update := range updates { 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) { for { now := time.Now() next := time.Date(now.Year(), now.Month(), now.Day(), 23, 0, 0, 0, now.Location()) if now.After(next) { next = next.AddDate(0, 0, 1) } slog.Info("daily report scheduler", "next_run", next) time.Sleep(time.Until(next)) chatIDStr, err := store.GetSetting("chat_id") if err != nil { slog.Error("daily report: chat_id not found") continue } chatID, err := strconv.ParseInt(chatIDStr, 10, 64) if err != nil { slog.Error("daily report: invalid chat_id", "value", chatIDStr) continue } slog.Info("sending daily report", "chat_id", chatID) h.SendDailyReport(chatID) } } func getEnvDefault(key, defaultValue string) string { if val := os.Getenv(key); val != "" { return val } return defaultValue }