Files
worktimeBot/cmd/bot/main.go

107 lines
2.1 KiB
Go

package main
import (
"log"
"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() {
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 {
log.Fatal(err)
}
dbStore, err := db.NewStore(dbPath)
if err != nil {
log.Fatal(err)
}
allowedUsers := parseAllowedUsers(os.Getenv("BOT_ALLOWED_USERS"))
handler := bot.NewHandler(botAPI, dbStore, allowedUsers)
webhookURL := os.Getenv("BOT_WEBHOOK_URL")
if webhookURL != "" {
startWebhook(botAPI, handler, webhookURL)
} else {
if _, err := botAPI.Request(tgbotapi.DeleteWebhookConfig{}); err != nil {
log.Printf("DeleteWebhook: %v", err)
}
// Daily report scheduler
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
}
}
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)
}
time.Sleep(time.Until(next))
chatIDStr, err := store.GetSetting("chat_id")
if err != nil {
continue
}
chatID, err := strconv.ParseInt(chatIDStr, 10, 64)
if err != nil {
continue
}
h.SendDailyReport(chatID)
}
}
func getEnvDefault(key, defaultValue string) string {
if val := os.Getenv(key); val != "" {
return val
}
return defaultValue
}