- Add chat_id to events, settings, and days_off for per-user data - Add proper graceful shutdown (signal handling, WaitGroup) - Separate polling and webhook modes with goroutine management - Add schema migration from single-user to multi-user schema - Refactor handlers with shared actionFunc pattern (msg + callback) - Fix schema path for Docker deployment (/app/db/schema.sql) - Remove emoji from output text for cleaner formatting
165 lines
3.5 KiB
Go
165 lines
3.5 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{}) {
|
|
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)
|
|
|
|
select {
|
|
case <-stop:
|
|
return
|
|
case <-time.After(time.Until(next)):
|
|
}
|
|
|
|
chatIDStr, err := store.GetSetting(0, "report_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
|
|
}
|