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:
2026-06-24 14:56:50 +03:30
parent fb2d0ef7d1
commit 49c0e82bac
9 changed files with 581 additions and 580 deletions

View File

@@ -1,172 +1,174 @@
package bot
import (
"context"
"fmt"
"strconv"
"strings"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
bot "github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
"worktimeBot/internal/db"
)
// handleSetReportTime parses a HH:MM argument and updates the user's report time.
func (h *Handler) handleSetReportTime(msg *tgbotapi.Message) {
arg := msg.CommandArguments()
if arg == "" {
func (h *Handler) handleSetReportTime(ctx context.Context, msg *models.Message) {
args := ""
if len(msg.Text) > 16 { // "/setreporttime " is 15 chars
args = strings.TrimSpace(msg.Text[15:])
}
if args == "" {
user, err := h.getOrCreateUser(msg.Chat.ID)
if err != nil {
h.sendText(msg.Chat.ID, "Error loading profile")
h.sendText(ctx, msg.Chat.ID, "Error loading profile")
return
}
h.sendText(msg.Chat.ID, fmt.Sprintf("Current report time: %s\nUsage: /setreporttime HH:MM (24-hour)", user.ReportTime))
h.sendText(ctx, msg.Chat.ID, fmt.Sprintf("Current report time: %s\nUsage: /setreporttime HH:MM (24-hour)", user.ReportTime))
return
}
if len(arg) != 5 || arg[2] != ':' {
h.sendText(msg.Chat.ID, "Invalid format. Usage: /setreporttime HH:MM (24-hour)")
if len(args) != 5 || args[2] != ':' {
h.sendText(ctx, msg.Chat.ID, "Invalid format. Usage: /setreporttime HH:MM (24-hour)")
return
}
hours, err1 := strconv.Atoi(arg[:2])
mins, err2 := strconv.Atoi(arg[3:])
hours, err1 := strconv.Atoi(args[:2])
mins, err2 := strconv.Atoi(args[3:])
if err1 != nil || err2 != nil || hours < 0 || hours > 23 || mins < 0 || mins > 59 {
h.sendText(msg.Chat.ID, "Invalid time. Usage: /setreporttime HH:MM (24-hour)")
h.sendText(ctx, msg.Chat.ID, "Invalid time. Usage: /setreporttime HH:MM (24-hour)")
return
}
user, err := h.getOrCreateUser(msg.Chat.ID)
if err != nil {
h.sendText(msg.Chat.ID, "Error updating report time")
h.sendText(ctx, msg.Chat.ID, "Error updating report time")
return
}
user.ReportTime = arg
user.ReportTime = args
if err := h.DB.UpdateUser(user); err != nil {
h.sendText(msg.Chat.ID, "Error updating report time")
h.sendText(ctx, msg.Chat.ID, "Error updating report time")
return
}
h.sendText(msg.Chat.ID, fmt.Sprintf("Report time set to %s", arg))
h.sendText(ctx, msg.Chat.ID, fmt.Sprintf("Report time set to %s", args))
}
// handleAccentMsg shows the accent color picker.
func (h *Handler) handleAccentMsg(msg *tgbotapi.Message) {
func (h *Handler) handleAccentMsg(ctx context.Context, msg *models.Message) {
user, err := h.getOrCreateUser(msg.Chat.ID)
if err != nil {
h.sendText(msg.Chat.ID, "Error loading profile")
h.sendText(ctx, msg.Chat.ID, "Error loading profile")
return
}
text, kb := h.buildAccentKeyboard(user)
reply := tgbotapi.NewMessage(msg.Chat.ID, text)
reply.ReplyMarkup = &kb
h.Bot.Send(reply)
h.Bot.SendMessage(ctx, &bot.SendMessageParams{ChatID: msg.Chat.ID, Text: text, ReplyMarkup: &kb})
}
// handleSetTimezone validates and updates the user's IANA timezone.
func (h *Handler) handleSetTimezone(msg *tgbotapi.Message) {
arg := msg.CommandArguments()
if arg == "" {
func (h *Handler) handleSetTimezone(ctx context.Context, msg *models.Message) {
args := ""
if len(msg.Text) > 13 { // "/settimezone " is 12 chars
args = strings.TrimSpace(msg.Text[13:])
}
if args == "" {
user, err := h.getOrCreateUser(msg.Chat.ID)
if err != nil {
h.sendText(msg.Chat.ID, "Error loading profile")
h.sendText(ctx, msg.Chat.ID, "Error loading profile")
return
}
h.sendText(msg.Chat.ID, fmt.Sprintf("Current timezone: %s\nUsage: /settimezone <IANA timezone>\nExamples: Asia/Tehran, Europe/London, America/New_York", user.Timezone))
h.sendText(ctx, msg.Chat.ID, fmt.Sprintf("Current timezone: %s\nUsage: /settimezone <IANA timezone>\nExamples: Asia/Tehran, Europe/London, America/New_York", user.Timezone))
return
}
loc, err := time.LoadLocation(arg)
loc, err := time.LoadLocation(args)
if err != nil {
h.sendText(msg.Chat.ID, fmt.Sprintf("Invalid timezone: %s\nUse IANA format, e.g. Asia/Tehran, Europe/London", arg))
h.sendText(ctx, msg.Chat.ID, fmt.Sprintf("Invalid timezone: %s\nUse IANA format, e.g. Asia/Tehran, Europe/London", args))
return
}
user, err := h.getOrCreateUser(msg.Chat.ID)
if err != nil {
h.sendText(msg.Chat.ID, "Error loading profile")
h.sendText(ctx, msg.Chat.ID, "Error loading profile")
return
}
user.Timezone = arg
user.Timezone = args
if err := h.DB.UpdateUser(user); err != nil {
h.sendText(msg.Chat.ID, "Error saving timezone")
h.sendText(ctx, msg.Chat.ID, "Error saving timezone")
return
}
now := time.Now().In(loc)
h.sendText(msg.Chat.ID, fmt.Sprintf("Timezone set to %s (current time: %s)", arg, now.Format("15:04")))
h.sendText(ctx, msg.Chat.ID, fmt.Sprintf("Timezone set to %s (current time: %s)", args, now.Format("15:04")))
}
// settingsCallback shows the settings inline menu.
func (h *Handler) settingsCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) settingsCallback(ctx context.Context, chatID int64, msgID int, callbackID string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
}
text, kb := h.buildSettingsKeyboard(user)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}
// buildSettingsKeyboard returns the settings menu text and inline keyboard.
func (h *Handler) buildSettingsKeyboard(user *db.User) (string, tgbotapi.InlineKeyboardMarkup) {
func (h *Handler) buildSettingsKeyboard(user *db.User) (string, models.InlineKeyboardMarkup) {
reportStatus := "disabled"
if user.ReportEnabled {
reportStatus = "enabled"
}
rows := [][]tgbotapi.InlineKeyboardButton{
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(fmt.Sprintf("Timezone: %s", user.Timezone), "timezone"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(fmt.Sprintf("Accent: %s", user.ExportAccent), "accent"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(fmt.Sprintf("Calendar: %s", user.Calendar), "caltype"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(fmt.Sprintf("Report: %s", reportStatus), "reporttoggle"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(fmt.Sprintf("Report time: %s", user.ReportTime), "reporttime"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("History", "history"),
),
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Back to Menu", "back_menu"),
),
rows := [][]models.InlineKeyboardButton{
{{Text: fmt.Sprintf("Timezone: %s", user.Timezone), CallbackData: "timezone"}},
{{Text: fmt.Sprintf("Accent: %s", user.ExportAccent), CallbackData: "accent"}},
{{Text: fmt.Sprintf("Calendar: %s", user.Calendar), CallbackData: "caltype"}},
{{Text: fmt.Sprintf("Report: %s", reportStatus), CallbackData: "reporttoggle"}},
{{Text: fmt.Sprintf("Report time: %s", user.ReportTime), CallbackData: "reporttime"}},
{{Text: "History", CallbackData: "history"}},
{{Text: "Back to Menu", CallbackData: "back_menu"}},
}
return "Settings:", tgbotapi.NewInlineKeyboardMarkup(rows...)
return "Settings:", models.InlineKeyboardMarkup{InlineKeyboard: rows}
}
// accentCallback shows the accent color picker (inline edit).
func (h *Handler) accentCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) accentCallback(ctx context.Context, chatID int64, msgID int, callbackID string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
}
text, kb := h.buildAccentKeyboard(user)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}
// timezoneCallback shows the current timezone and instructions to change it.
func (h *Handler) timezoneCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) timezoneCallback(ctx context.Context, chatID int64, msgID int, callbackID string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
}
text := fmt.Sprintf("Current timezone: %s\n\nUse /settimezone <name> to change it.\nExamples: Asia/Tehran, Europe/London, America/New_York", user.Timezone)
kb := tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Back to Settings", "back_settings"),
),
)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
kb := models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{
{{Text: "Back to Settings", CallbackData: "back_settings"}},
},
}
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}
// buildAccentKeyboard returns the accent color picker keyboard.
func (h *Handler) buildAccentKeyboard(user *db.User) (string, tgbotapi.InlineKeyboardMarkup) {
func (h *Handler) buildAccentKeyboard(user *db.User) (string, models.InlineKeyboardMarkup) {
type accentOption struct {
name string
color string
@@ -177,25 +179,25 @@ func (h *Handler) buildAccentKeyboard(user *db.User) (string, tgbotapi.InlineKey
{"rose", "Pink"},
{"catppuccin", "Purple"},
}
rows := [][]tgbotapi.InlineKeyboardButton{}
rows := [][]models.InlineKeyboardButton{}
for _, a := range accents {
label := fmt.Sprintf("%s (%s)", a.name, a.color)
if a.name == user.ExportAccent {
label = "> " + label
}
rows = append(rows, tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(label, "accent_"+a.name),
))
rows = append(rows, []models.InlineKeyboardButton{
{Text: label, CallbackData: "accent_" + a.name},
})
}
rows = append(rows, tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Back to Settings", "back_settings"),
))
return "Select accent color:", tgbotapi.NewInlineKeyboardMarkup(rows...)
rows = append(rows, []models.InlineKeyboardButton{
{Text: "Back to Settings", CallbackData: "back_settings"},
})
return "Select accent color:", models.InlineKeyboardMarkup{InlineKeyboard: rows}
}
// selectAccent sets the user's export accent color after validation.
func (h *Handler) selectAccent(chatID int64, msgID int, callbackID, name string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) selectAccent(ctx context.Context, chatID int64, msgID int, callbackID, name string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
@@ -208,87 +210,99 @@ func (h *Handler) selectAccent(chatID int64, msgID int, callbackID, name string)
if err := h.DB.UpdateUser(user); err != nil {
return
}
edit := tgbotapi.NewEditMessageText(chatID, msgID, fmt.Sprintf("Accent set to: %s", name))
kb := tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Back to Settings", "back_settings"),
),
)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
kb := models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{
{{Text: "Back to Settings", CallbackData: "back_settings"}},
},
}
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: fmt.Sprintf("Accent set to: %s", name),
ReplyMarkup: &kb,
})
}
// reportTimeCallback shows the current report time setting.
func (h *Handler) reportTimeCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) reportTimeCallback(ctx context.Context, chatID int64, msgID int, callbackID string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
}
text := fmt.Sprintf("Current report time: %s\nUse /setreporttime HH:MM to change it.", user.ReportTime)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
kb := tgbotapi.NewInlineKeyboardMarkup(
tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Back to Settings", "back_settings"),
),
)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
kb := models.InlineKeyboardMarkup{
InlineKeyboard: [][]models.InlineKeyboardButton{
{{Text: "Back to Settings", CallbackData: "back_settings"}},
},
}
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}
// backToSettings returns to the main settings menu.
func (h *Handler) backToSettings(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) backToSettings(ctx context.Context, chatID int64, msgID int, callbackID string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
}
text, kb := h.buildSettingsKeyboard(user)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}
// calTypeCallback shows the calendar type selector.
func (h *Handler) calTypeCallback(chatID int64, msgID int, callbackID string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) calTypeCallback(ctx context.Context, chatID int64, msgID int, callbackID string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
user, err := h.getOrCreateUser(chatID)
if err != nil {
return
}
text, kb := h.buildCalendarKeyboard(user)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}
// buildCalendarKeyboard returns the calendar type selector keyboard.
func (h *Handler) buildCalendarKeyboard(user *db.User) (string, tgbotapi.InlineKeyboardMarkup) {
func (h *Handler) buildCalendarKeyboard(user *db.User) (string, models.InlineKeyboardMarkup) {
cals := []string{"gregorian", "jalali", "hijri"}
calLabels := map[string]string{
"gregorian": "Gregorian",
"jalali": "Jalali",
"hijri": "Hijri",
}
rows := [][]tgbotapi.InlineKeyboardButton{}
rows := [][]models.InlineKeyboardButton{}
for _, c := range cals {
label := calLabels[c]
if c == user.Calendar {
label = "> " + label
}
rows = append(rows, tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData(label, "caltype_"+c),
))
rows = append(rows, []models.InlineKeyboardButton{
{Text: label, CallbackData: "caltype_" + c},
})
}
rows = append(rows, tgbotapi.NewInlineKeyboardRow(
tgbotapi.NewInlineKeyboardButtonData("Back to Settings", "back_settings"),
))
return "Select calendar type:", tgbotapi.NewInlineKeyboardMarkup(rows...)
rows = append(rows, []models.InlineKeyboardButton{
{Text: "Back to Settings", CallbackData: "back_settings"},
})
return "Select calendar type:", models.InlineKeyboardMarkup{InlineKeyboard: rows}
}
// selectCalendar sets the user's calendar after validation.
func (h *Handler) selectCalendar(chatID int64, msgID int, callbackID, name string) {
defer h.Bot.Request(tgbotapi.NewCallback(callbackID, ""))
func (h *Handler) selectCalendar(ctx context.Context, chatID int64, msgID int, callbackID, name string) {
h.Bot.AnswerCallbackQuery(ctx, &bot.AnswerCallbackQueryParams{CallbackQueryID: callbackID})
valid := map[string]bool{"gregorian": true, "jalali": true, "hijri": true}
if !valid[name] {
return
@@ -302,7 +316,10 @@ func (h *Handler) selectCalendar(chatID int64, msgID int, callbackID, name strin
return
}
text, kb := h.buildSettingsKeyboard(user)
edit := tgbotapi.NewEditMessageText(chatID, msgID, text)
edit.ReplyMarkup = &kb
h.Bot.Send(edit)
h.Bot.EditMessageText(ctx, &bot.EditMessageTextParams{
ChatID: chatID,
MessageID: msgID,
Text: text,
ReplyMarkup: &kb,
})
}