refactor: migrate from go-telegram-bot-api/v5 to go-telegram/bot
- Replaced tgbotapi with go-telegram/bot (zero-dependency, context-aware, Bot API 10.0) - All handler methods now accept context.Context; threading ctx through all sends/edits - Changed from function-based (NewMessage/NewEditMessageText/NewInlineKeyboardMarkup) to struct-param API (SendMessageParams/EditMessageTextParams/InlineKeyboardMarkup) - Added colored buttons: DEL buttons in calendar use Style: 'danger' (red) - Both polling and webhook modes preserved with new library patterns - Context-based shutdown (signal.NotifyContext) replaces stop channel
This commit is contained in:
147
cmd/bot/main.go
147
cmd/bot/main.go
@@ -1,17 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
|
||||
tgbot "github.com/go-telegram/bot"
|
||||
"github.com/go-telegram/bot/models"
|
||||
"github.com/joho/godotenv"
|
||||
|
||||
"worktimeBot/internal/bot"
|
||||
@@ -28,14 +28,6 @@ func main() {
|
||||
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)
|
||||
@@ -43,108 +35,61 @@ func main() {
|
||||
}
|
||||
|
||||
allowedUsers := parseAllowedUsers(os.Getenv("BOT_ALLOWED_USERS"))
|
||||
handler := bot.NewHandler(botAPI, dbStore, allowedUsers)
|
||||
|
||||
stop := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
var h *bot.Handler
|
||||
|
||||
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)
|
||||
dispatch := func(ctx context.Context, b *tgbot.Bot, update *models.Update) {
|
||||
if update.Message != nil {
|
||||
h.HandleMessage(ctx, update.Message)
|
||||
}
|
||||
if update.CallbackQuery != nil {
|
||||
h.HandleCallback(ctx, update.CallbackQuery)
|
||||
}
|
||||
|
||||
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") != ""],
|
||||
)
|
||||
b, err := tgbot.New(token, tgbot.WithDefaultHandler(dispatch))
|
||||
if err != nil {
|
||||
slog.Error("failed to create bot", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
h = bot.NewHandler(b, dbStore, allowedUsers)
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer cancel()
|
||||
|
||||
if url := os.Getenv("BOT_WEBHOOK_URL"); url != "" {
|
||||
startWebhook(ctx, b, h, url)
|
||||
} else {
|
||||
b.DeleteWebhook(ctx, &tgbot.DeleteWebhookParams{})
|
||||
go dailyReportScheduler(ctx, h, dbStore)
|
||||
slog.Info("bot started",
|
||||
"allowed_users", len(allowedUsers),
|
||||
"mode", "polling",
|
||||
)
|
||||
b.Start(ctx)
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
// startPolling runs the long-polling update loop, dispatching messages and callbacks to the handler.
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseAllowedUsers parses a comma-separated list of Telegram user IDs into a set.
|
||||
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
|
||||
}
|
||||
|
||||
// dailyReportScheduler runs a periodic ticker that triggers daily report checks every 30 seconds.
|
||||
func dailyReportScheduler(h *bot.Handler, store *db.Store, stop chan struct{}) {
|
||||
func dailyReportScheduler(ctx context.Context, h *bot.Handler, store *db.Store) {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
checkDailyReports(h, store)
|
||||
checkDailyReports(ctx, h, store)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// checkDailyReports iterates all users and sends a daily report to those whose report time has arrived.
|
||||
func checkDailyReports(h *bot.Handler, store *db.Store) {
|
||||
func checkDailyReports(ctx context.Context, h *bot.Handler, store *db.Store) {
|
||||
users, err := store.GetAllUsers()
|
||||
if err != nil {
|
||||
slog.Error("report scheduler: get users", "error", err)
|
||||
@@ -177,10 +122,28 @@ func checkDailyReports(h *bot.Handler, store *db.Store) {
|
||||
slog.Info("sending daily report",
|
||||
"user_id", u.ID, "chat_id", u.ChatID, "timezone", u.Timezone,
|
||||
)
|
||||
h.SendDailyReport(u.ID, u.ChatID)
|
||||
h.SendDailyReport(ctx, u.ID, u.ChatID)
|
||||
}
|
||||
}
|
||||
|
||||
// parseAllowedUsers parses a comma-separated list of Telegram user IDs into a set.
|
||||
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
|
||||
}
|
||||
|
||||
// getEnvDefault returns the environment variable value or a default if unset or empty.
|
||||
func getEnvDefault(key, defaultValue string) string {
|
||||
if val := os.Getenv(key); val != "" {
|
||||
|
||||
Reference in New Issue
Block a user