From 90832e6b00ff05c070f49840d1b962adde4559f5 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Mon, 4 May 2026 16:43:11 +0300 Subject: [PATCH] Added proxy connection for tg bot client --- core/config/config-types.go | 7 +- core/lib/external/tg_bot/client.go | 68 --- core/lib/external/tg_bot/example.go | 70 --- core/lib/external/tg_bot/keyboard_builders.go | 213 -------- core/lib/external/tg_bot/methods.go | 512 ------------------ core/lib/external/tg_bot/types.go | 201 ------- core/lib/external/tg_bot/utils.go | 24 - core/lib/external/tgkit/client.go | 182 +++++++ core/lib/external/tgkit/err.go | 25 + core/lib/external/tgkit/keyboard.go | 163 ++++++ core/lib/external/tgkit/media.go | 180 ++++++ core/lib/external/tgkit/message.go | 87 +++ core/lib/external/tgkit/types.go | 57 ++ service/telegram_service/cmd/app.go | 11 +- .../telegram_service/common/update/0_init.go | 2 +- .../telegram_service/common/update/update.go | 2 +- .../handlers/approval/notify.go | 14 +- .../scheduler/delegation_checker.go | 2 +- service/telegram_service/types/types.go | 5 +- 19 files changed, 724 insertions(+), 1101 deletions(-) delete mode 100644 core/lib/external/tg_bot/client.go delete mode 100644 core/lib/external/tg_bot/example.go delete mode 100644 core/lib/external/tg_bot/keyboard_builders.go delete mode 100644 core/lib/external/tg_bot/methods.go delete mode 100644 core/lib/external/tg_bot/types.go delete mode 100644 core/lib/external/tg_bot/utils.go create mode 100644 core/lib/external/tgkit/client.go create mode 100644 core/lib/external/tgkit/err.go create mode 100644 core/lib/external/tgkit/keyboard.go create mode 100644 core/lib/external/tgkit/media.go create mode 100644 core/lib/external/tgkit/message.go create mode 100644 core/lib/external/tgkit/types.go diff --git a/core/config/config-types.go b/core/config/config-types.go index 8aa1245..acb581e 100644 --- a/core/config/config-types.go +++ b/core/config/config-types.go @@ -20,8 +20,11 @@ type DatabaseConfig struct { // TelegramConfig конфигурация Telegram type TelegramConfig struct { - BotToken string `yaml:"bot_token"` - WebAppUrl string `yaml:"web_app_url"` + BotToken string `yaml:"bot_token"` + WebAppUrl string `yaml:"web_app_url"` + ProxyURL string `yaml:"proxy_url"` + ProxyUsername string `yaml:"proxy_username"` + ProxyPassword string `yaml:"proxy_password"` } // ServiceConfig конфигурация сервиса diff --git a/core/lib/external/tg_bot/client.go b/core/lib/external/tg_bot/client.go deleted file mode 100644 index 7fc3dbc..0000000 --- a/core/lib/external/tg_bot/client.go +++ /dev/null @@ -1,68 +0,0 @@ -package telegram - -import ( - "context" - "errors" - tg "github.com/temoon/telegram-bots-api" - "sync" - "time" - - "github.com/sirupsen/logrus" -) - -type TgBotClient struct { - bot *tg.Bot - config *BotConfig - ctx context.Context -} - -var ( - onceTgBotClient sync.Once - tgBotClientInstance *TgBotClient -) - -func NewTgBotClient(config *BotConfig) (*TgBotClient, error) { - if config == nil || config.BotKey == "" { - return nil, errors.New("failed to init TgBotClient: Api key is nil") - } - - var initErr error - onceTgBotClient.Do(func() { - bot := tg.NewBot(tg.BotOpts{ - Token: config.BotKey, - Timeout: 30 * time.Second, - Env: tg.EnvProduction, - }) - - if bot == nil { - initErr = errors.New("failed to create bot instance") - return - } - - tgBotClientInstance = &TgBotClient{ - bot: bot, - config: config, - ctx: context.Background(), - } - - logrus.Info("✅ Telegram BOT API success connected") - }) - - if initErr != nil { - return nil, initErr - } - - return tgBotClientInstance, nil -} - -func (c *TgBotClient) GetBot() *tg.Bot { - return c.bot -} - -func (c *TgBotClient) WithContext(ctx context.Context) *TgBotClient { - return &TgBotClient{ - bot: c.bot, - config: c.config, - ctx: ctx, - } -} diff --git a/core/lib/external/tg_bot/example.go b/core/lib/external/tg_bot/example.go deleted file mode 100644 index 2be7303..0000000 --- a/core/lib/external/tg_bot/example.go +++ /dev/null @@ -1,70 +0,0 @@ -package telegram - -import "io" - -func main() { - // Инициализация - client, _ := NewTgBotClient(&BotConfig{ - BotKey: "YOUR_BOT_TOKEN", - }) - - // Отправка сообщения с inline-клавиатурой - client.SendMessage(MessageParams{ - ChatID: 123456789, - Text: "Выберите действие:", - ParseMode: ParseModeHTML, - ReplyMarkup: NewInlineKeyboard(). - AddRow( - NewInlineButton("✅ Принять", "accept"), - NewInlineButton("❌ Отклонить", "reject"), - ). - AddRow( - NewInlineButtonURL("📖 Документация", "https://example.com"), - ). - Build(), - }) - - // Отправка документа - file := io.Reader(nil) // io.Reader с файлом - client.SendDocument(DocumentParams{ - ChatID: 123456789, - Document: file, - Caption: "Ваш документ готов", - ParseMode: ParseModeHTML, - FileName: "report.pdf", - }) - - // Reply-клавиатура - client.SendMessage(MessageParams{ - ChatID: 123456789, - Text: "Выберите из меню:", - ReplyMarkup: NewReplyKeyboard(). - AddRow( - NewReplyButton("📋 Согласования"), - NewReplyButton("📂 Мои заявки"), - ). - AddRow(NewReplyButton("⚙️ Настройки")). - SetPlaceholder("Выберите команду..."). - Build(), - }) - - // Редактирование сообщения - client.EditMessageText(EditMessageTextParams{ - ChatID: 123456789, - MessageID: 987654321, - Text: "Обновлённый текст", - ParseMode: ParseModeHTML, - }) - - // Удаление сообщения - client.DeleteMessage(DeleteMessageParams{ - ChatID: 123456789, - MessageID: 987654321, - }) - - // Ответ на callback - client.AnswerCallbackQuery("callback_id", "Принято!", false) - - // Chat action - client.SendChatAction(123456789, ChatActionTyping) -} diff --git a/core/lib/external/tg_bot/keyboard_builders.go b/core/lib/external/tg_bot/keyboard_builders.go deleted file mode 100644 index b3673a3..0000000 --- a/core/lib/external/tg_bot/keyboard_builders.go +++ /dev/null @@ -1,213 +0,0 @@ -package telegram - -import ( - tg "github.com/temoon/telegram-bots-api" -) - -// ============ INLINE KEYBOARD ============ - -type InlineKeyboardBuilder struct { - rows [][]tg.InlineKeyboardButton -} - -func NewInlineKeyboard() *InlineKeyboardBuilder { - return &InlineKeyboardBuilder{ - rows: make([][]tg.InlineKeyboardButton, 0), - } -} - -func (kb *InlineKeyboardBuilder) AddRow(buttons ...tg.InlineKeyboardButton) *InlineKeyboardBuilder { - kb.rows = append(kb.rows, buttons) - return kb -} - -func (kb *InlineKeyboardBuilder) Build() tg.InlineKeyboardMarkup { - return tg.InlineKeyboardMarkup{ - InlineKeyboard: kb.rows, - } -} - -// NewInlineButton создаёт кнопку с callback data -func NewInlineButton(text, callbackData string) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - CallbackData: &callbackData, - } -} - -// NewInlineButtonURL создаёт кнопку с URL -func NewInlineButtonURL(text, url string) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - Url: &url, - } -} - -// NewInlineButtonWebApp создаёт кнопку WebApp -func NewInlineButtonWebApp(text string, webApp tg.WebAppInfo) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - WebApp: &webApp, - } -} - -// NewInlineButtonLogin создаёт кнопку Login -func NewInlineButtonLogin(text string, loginURL tg.LoginUrl) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - LoginUrl: &loginURL, - } -} - -// NewInlineButtonSwitchInlineQuery создаёт кнопку переключения на inline режим -func NewInlineButtonSwitchInlineQuery(text, query string) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - SwitchInlineQuery: &query, - } -} - -// NewInlineButtonSwitchInlineQueryCurrentChat создаёт кнопку переключения в текущем чате -func NewInlineButtonSwitchInlineQueryCurrentChat(text, query string) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - SwitchInlineQueryCurrentChat: &query, - } -} - -// NewInlineButtonGame создаёт кнопку игры -func NewInlineButtonGame(text string, callbackGame tg.CallbackGame) tg.InlineKeyboardButton { - return tg.InlineKeyboardButton{ - Text: text, - CallbackGame: &callbackGame, - } -} - -// NewInlineButtonPay создаёт кнопку оплаты -func NewInlineButtonPay(text string) tg.InlineKeyboardButton { - pay := true - return tg.InlineKeyboardButton{ - Text: text, - Pay: &pay, - } -} - -// ============ REPLY KEYBOARD ============ - -type ReplyKeyboardBuilder struct { - rows [][]tg.KeyboardButton - resize bool - oneTime bool - inputFieldPlaceholder string - selective bool - isPersistent bool -} - -func NewReplyKeyboard() *ReplyKeyboardBuilder { - return &ReplyKeyboardBuilder{ - rows: make([][]tg.KeyboardButton, 0), - resize: true, - } -} - -func (kb *ReplyKeyboardBuilder) AddRow(buttons ...tg.KeyboardButton) *ReplyKeyboardBuilder { - kb.rows = append(kb.rows, buttons) - return kb -} - -func (kb *ReplyKeyboardBuilder) SetResize(resize bool) *ReplyKeyboardBuilder { - kb.resize = resize - return kb -} - -func (kb *ReplyKeyboardBuilder) SetOneTime(oneTime bool) *ReplyKeyboardBuilder { - kb.oneTime = oneTime - return kb -} - -func (kb *ReplyKeyboardBuilder) SetPlaceholder(text string) *ReplyKeyboardBuilder { - kb.inputFieldPlaceholder = text - return kb -} - -func (kb *ReplyKeyboardBuilder) SetSelective(selective bool) *ReplyKeyboardBuilder { - kb.selective = selective - return kb -} - -func (kb *ReplyKeyboardBuilder) SetPersistent(persistent bool) *ReplyKeyboardBuilder { - kb.isPersistent = persistent - return kb -} - -func (kb *ReplyKeyboardBuilder) Build() tg.ReplyKeyboardMarkup { - markup := tg.ReplyKeyboardMarkup{ - Keyboard: kb.rows, - ResizeKeyboard: &kb.resize, - OneTimeKeyboard: &kb.oneTime, - InputFieldPlaceholder: &kb.inputFieldPlaceholder, - Selective: &kb.selective, - IsPersistent: &kb.isPersistent, - } - return markup -} - -// NewReplyButton создаёт обычную кнопку -func NewReplyButton(text string) tg.KeyboardButton { - return tg.KeyboardButton{ - Text: text, - } -} - -// NewReplyButtonContact создаёт кнопку запроса контакта -func NewReplyButtonContact(text string) tg.KeyboardButton { - requestContact := true - return tg.KeyboardButton{ - Text: text, - RequestContact: &requestContact, - } -} - -// NewReplyButtonLocation создаёт кнопку запроса локации -func NewReplyButtonLocation(text string) tg.KeyboardButton { - requestLocation := true - return tg.KeyboardButton{ - Text: text, - RequestLocation: &requestLocation, - } -} - -// NewReplyButtonPoll создаёт кнопку создания опроса -func NewReplyButtonPoll(text string, pollType string) tg.KeyboardButton { - return tg.KeyboardButton{ - Text: text, - RequestPoll: &tg.KeyboardButtonPollType{ - Type: &pollType, - }, - } -} - -// NewReplyButtonWebApp создаёт кнопку WebApp -func NewReplyButtonWebApp(text string, webApp tg.WebAppInfo) tg.KeyboardButton { - return tg.KeyboardButton{ - Text: text, - WebApp: &webApp, - } -} - -// RemoveKeyboard создаёт маркер для удаления клавиатуры -func RemoveKeyboard(selective bool) tg.ReplyKeyboardRemove { - return tg.ReplyKeyboardRemove{ - RemoveKeyboard: true, - Selective: &selective, - } -} - -// ForceReply создаёт маркер принудительного ответа -func ForceReply(placeholder string, selective bool) tg.ForceReply { - return tg.ForceReply{ - ForceReply: true, - InputFieldPlaceholder: &placeholder, - Selective: &selective, - } -} diff --git a/core/lib/external/tg_bot/methods.go b/core/lib/external/tg_bot/methods.go deleted file mode 100644 index 900fa21..0000000 --- a/core/lib/external/tg_bot/methods.go +++ /dev/null @@ -1,512 +0,0 @@ -package telegram - -import ( - tg "github.com/temoon/telegram-bots-api" - "github.com/temoon/telegram-bots-api/requests" -) - -func (c *TgBotClient) SendMessage(params MessageParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - req := &requests.SendMessage{ - ChatId: chatID, - Text: params.Text, - } - - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.Entities) > 0 { - req.Entities = params.Entities - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) SendPhoto(params PhotoParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - req := &requests.SendPhoto{ - ChatId: chatID, - Photo: c.prepareInputFile(params.Photo, params.ChatID, "photo"), - } - - if params.Caption != "" { - req.Caption = ¶ms.Caption - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.CaptionEntities) > 0 { - req.CaptionEntities = params.CaptionEntities - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) SendDocument(params DocumentParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - req := &requests.SendDocument{ - ChatId: chatID, - Document: c.prepareInputFile(params.Document, params.ChatID, params.FileName), - } - - if params.Thumbnail != nil { - thumbnail := c.prepareInputFile(params.Thumbnail, params.ChatID, "thumbnail") - req.Thumbnail = &thumbnail - } - if params.Caption != "" { - req.Caption = ¶ms.Caption - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.CaptionEntities) > 0 { - req.CaptionEntities = params.CaptionEntities - } - if params.DisableContentTypeDetection { - req.DisableContentTypeDetection = ¶ms.DisableContentTypeDetection - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) SendVideo(params VideoParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - req := &requests.SendVideo{ - ChatId: chatID, - Video: c.prepareInputFile(params.Video, params.ChatID, "video"), - } - - if params.Duration != 0 { - req.Duration = ¶ms.Duration - } - if params.Width != 0 { - req.Width = ¶ms.Width - } - if params.Height != 0 { - req.Height = ¶ms.Height - } - if params.Thumbnail != nil { - thumbnail := c.prepareInputFile(params.Thumbnail, params.ChatID, "thumbnail") - req.Thumbnail = &thumbnail - } - if params.Caption != "" { - req.Caption = ¶ms.Caption - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.CaptionEntities) > 0 { - req.CaptionEntities = params.CaptionEntities - } - if params.SupportsStreaming { - req.SupportsStreaming = ¶ms.SupportsStreaming - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) SendAudio(params AudioParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - - req := &requests.SendAudio{ - ChatId: chatID, - Audio: c.prepareInputFile(params.Audio, params.ChatID, "audio"), - } - - if params.Caption != "" { - req.Caption = ¶ms.Caption - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.CaptionEntities) > 0 { - req.CaptionEntities = params.CaptionEntities - } - if params.Duration != 0 { - req.Duration = ¶ms.Duration - } - if params.Performer != "" { - req.Performer = ¶ms.Performer - } - if params.Title != "" { - req.Title = ¶ms.Title - } - if params.Thumbnail != nil { - thumbnail := c.prepareInputFile(params.Thumbnail, params.ChatID, "thumbnail") - req.Thumbnail = &thumbnail - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) SendLocation(params LocationParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - - req := &requests.SendLocation{ - ChatId: chatID, - Latitude: params.Latitude, - Longitude: params.Longitude, - } - - if params.HorizontalAccuracy != 0 { - req.HorizontalAccuracy = ¶ms.HorizontalAccuracy - } - if params.LivePeriod != 0 { - req.LivePeriod = ¶ms.LivePeriod - } - if params.Heading != 0 { - req.Heading = ¶ms.Heading - } - if params.ProximityAlertRadius != 0 { - req.ProximityAlertRadius = ¶ms.ProximityAlertRadius - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) EditMessageText(params EditMessageTextParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - - req := &requests.EditMessageText{ - Text: params.Text, - } - - if params.ChatID != 0 { - req.ChatId = &chatID - req.MessageId = ¶ms.MessageID - } - if params.InlineMessageID != "" { - req.InlineMessageId = ¶ms.InlineMessageID - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.Entities) > 0 { - req.Entities = params.Entities - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - if msg, ok := result.(*tg.Message); ok { - return msg, nil - } - - return nil, nil -} - -func (c *TgBotClient) EditMessageCaption(params EditMessageCaptionParams) (*tg.Message, error) { - req := &requests.EditMessageCaption{} - chatID := tg.NewChatId(params.ChatID, "") - - if params.ChatID != 0 { - req.ChatId = &chatID - req.MessageId = ¶ms.MessageID - } - if params.InlineMessageID != "" { - req.InlineMessageId = ¶ms.InlineMessageID - } - if params.Caption != "" { - req.Caption = ¶ms.Caption - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.CaptionEntities) > 0 { - req.CaptionEntities = params.CaptionEntities - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - if msg, ok := result.(*tg.Message); ok { - return msg, nil - } - - return nil, nil -} - -func (c *TgBotClient) EditMessageReplyMarkup(params EditMessageReplyMarkupParams) (*tg.Message, error) { - req := &requests.EditMessageReplyMarkup{} - chatID := tg.NewChatId(params.ChatID, "") - - if params.ChatID != 0 { - req.ChatId = &chatID - req.MessageId = ¶ms.MessageID - } - if params.InlineMessageID != "" { - req.InlineMessageId = ¶ms.InlineMessageID - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - if msg, ok := result.(*tg.Message); ok { - return msg, nil - } - - return nil, nil -} - -func (c *TgBotClient) DeleteMessage(params DeleteMessageParams) (bool, error) { - chatID := tg.NewChatId(params.ChatID, "") - - req := &requests.DeleteMessage{ - ChatId: chatID, - MessageId: params.MessageID, - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return false, err - } - - return result.(bool), nil -} - -func (c *TgBotClient) ForwardMessage(params ForwardMessageParams) (*tg.Message, error) { - chatID := tg.NewChatId(params.ChatID, "") - fromChatID := tg.NewChatId(params.FromChatID, "") - - req := &requests.ForwardMessage{ - ChatId: chatID, - FromChatId: fromChatID, - MessageId: params.MessageID, - } - - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.Message), nil -} - -func (c *TgBotClient) CopyMessage(params CopyMessageParams) (*tg.MessageId, error) { - chatID := tg.NewChatId(params.ChatID, "") - fromChatID := tg.NewChatId(params.FromChatID, "") - - req := &requests.CopyMessage{ - ChatId: chatID, - FromChatId: fromChatID, - MessageId: params.MessageID, - } - - if params.Caption != "" { - req.Caption = ¶ms.Caption - } - if params.ParseMode != "" { - req.ParseMode = ¶ms.ParseMode - } - if len(params.CaptionEntities) > 0 { - req.CaptionEntities = params.CaptionEntities - } - if params.DisableNotification { - req.DisableNotification = ¶ms.DisableNotification - } - if params.ProtectContent { - req.ProtectContent = ¶ms.ProtectContent - } - if params.ReplyMarkup != nil { - req.ReplyMarkup = params.ReplyMarkup - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.MessageId), nil -} - -// ============ CALLBACK QUERIES ============ - -func (c *TgBotClient) AnswerCallbackQuery(callbackQueryID string, text string, showAlert bool) error { - req := &requests.AnswerCallbackQuery{ - CallbackQueryId: callbackQueryID, - } - - if text != "" { - req.Text = &text - } - if showAlert { - req.ShowAlert = &showAlert - } - - _, err := req.Call(c.ctx, c.bot) - return err -} - -// ============ ФАЙЛЫ ============ - -func (c *TgBotClient) GetFile(fileID string) (*tg.File, error) { - req := &requests.GetFile{ - FileId: fileID, - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.(*tg.File), nil -} - -func (c *TgBotClient) GetFileURL(fileID string) (string, error) { - file, err := c.GetFile(fileID) - if err != nil { - return "", err - } - - if file.FilePath == nil { - return "", nil - } - - return "https://api.telegram.org/file/bot" + c.config.BotKey + "/" + *file.FilePath, nil -} - -// ============ UPDATES ============ - -func (c *TgBotClient) GetUpdates(params GetUpdatesParams) ([]tg.Update, error) { - req := &requests.GetUpdates{} - - if params.Offset != 0 { - req.Offset = ¶ms.Offset - } - if params.Limit != 0 { - req.Limit = ¶ms.Limit - } - if params.Timeout != 0 { - req.Timeout = ¶ms.Timeout - } - if len(params.AllowedUpdates) > 0 { - req.AllowedUpdates = params.AllowedUpdates - } - - result, err := req.Call(c.ctx, c.bot) - if err != nil { - return nil, err - } - - return result.([]tg.Update), nil -} - -// ============ CHAT ACTIONS ============ - -func (c *TgBotClient) SendChatAction(chatID int64, action string) error { - chatId := tg.NewChatId(chatID, "") - - req := &requests.SendChatAction{ - ChatId: chatId, - Action: action, - } - - _, err := req.Call(c.ctx, c.bot) - return err -} diff --git a/core/lib/external/tg_bot/types.go b/core/lib/external/tg_bot/types.go deleted file mode 100644 index 3542786..0000000 --- a/core/lib/external/tg_bot/types.go +++ /dev/null @@ -1,201 +0,0 @@ -package telegram - -import tg "github.com/temoon/telegram-bots-api" - -type BotConfig struct { - BotKey string - ApiURL string -} - -// ParseMode константы -const ( - ParseModeHTML = tg.ParseModeHTML - ParseModeMarkdown = tg.ParseModeMarkdown - ParseModeMarkdownV2 = tg.ParseModeMarkdownV2 -) - -// ChatAction константы -const ( - ChatActionTyping = tg.ChatActionTyping - ChatActionUploadPhoto = tg.ChatActionUploadPhoto - ChatActionRecordVideo = tg.ChatActionRecordVideo - ChatActionUploadVideo = tg.ChatActionUploadVideo - ChatActionRecordAudio = tg.ChatActionRecordAudio - ChatActionUploadAudio = tg.ChatActionUploadAudio - ChatActionUploadDocument = tg.ChatActionUploadDocument - ChatActionFindLocation = tg.ChatActionFindLocation - ChatActionRecordVideoNote = tg.ChatActionRecordVideoNote - ChatActionUploadVideoNote = tg.ChatActionUploadVideoNote -) - -// MessageParams параметры для отправки сообщения -type MessageParams struct { - ChatID int64 - Text string - ParseMode string - Entities []tg.MessageEntity - DisableWebPagePreview bool - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} // InlineKeyboardMarkup или ReplyKeyboardMarkup -} - -// PhotoParams параметры для отправки фото -type PhotoParams struct { - ChatID int64 - Photo interface{} // InputFile, string (file_id), или io.Reader - Caption string - ParseMode string - CaptionEntities []tg.MessageEntity - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} -} - -// DocumentParams параметры для отправки документа -type DocumentParams struct { - ChatID int64 - Document interface{} // InputFile, string (file_id), или io.Reader - Thumbnail interface{} - Caption string - ParseMode string - CaptionEntities []tg.MessageEntity - DisableContentTypeDetection bool - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} - FileName string -} - -// VideoParams параметры для отправки видео -type VideoParams struct { - ChatID int64 - Video interface{} - Duration int64 - Width int64 - Height int64 - Thumbnail interface{} - Caption string - ParseMode string - CaptionEntities []tg.MessageEntity - SupportsStreaming bool - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} -} - -// AudioParams параметры для отправки аудио -type AudioParams struct { - ChatID int64 - Audio interface{} - Caption string - ParseMode string - CaptionEntities []tg.MessageEntity - Duration int64 - Performer string - Title string - Thumbnail interface{} - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} -} - -// LocationParams параметры для отправки геолокации -type LocationParams struct { - ChatID int64 - Latitude float64 - Longitude float64 - HorizontalAccuracy float64 - LivePeriod int64 - Heading int64 - ProximityAlertRadius int64 - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} -} - -// EditMessageTextParams параметры для редактирования текста -type EditMessageTextParams struct { - ChatID int64 - MessageID int64 - InlineMessageID string - Text string - ParseMode string - Entities []tg.MessageEntity - DisableWebPagePreview bool - ReplyMarkup *tg.InlineKeyboardMarkup -} - -// EditMessageCaptionParams параметры для редактирования подписи -type EditMessageCaptionParams struct { - ChatID int64 - MessageID int64 - InlineMessageID string - Caption string - ParseMode string - CaptionEntities []tg.MessageEntity - ReplyMarkup *tg.InlineKeyboardMarkup -} - -// EditMessageReplyMarkupParams параметры для редактирования клавиатуры -type EditMessageReplyMarkupParams struct { - ChatID int64 - MessageID int64 - InlineMessageID string - ReplyMarkup *tg.InlineKeyboardMarkup -} - -// DeleteMessageParams параметры для удаления сообщения -type DeleteMessageParams struct { - ChatID int64 - MessageID int64 -} - -// ForwardMessageParams параметры для пересылки сообщения -type ForwardMessageParams struct { - ChatID int64 - FromChatID int64 - MessageID int64 - DisableNotification bool - ProtectContent bool -} - -// CopyMessageParams параметры для копирования сообщения -type CopyMessageParams struct { - ChatID int64 - FromChatID int64 - MessageID int64 - Caption string - ParseMode string - CaptionEntities []tg.MessageEntity - DisableNotification bool - ProtectContent bool - ReplyToMessageID int64 - AllowSendingWithoutReply bool - ReplyMarkup interface{} -} - -// GetFileParams параметры для получения файла -type GetFileParams struct { - FileID string -} - -// GetUpdatesParams параметры для получения обновлений -type GetUpdatesParams struct { - Offset int64 - Limit int64 - Timeout int64 - AllowedUpdates []string -} diff --git a/core/lib/external/tg_bot/utils.go b/core/lib/external/tg_bot/utils.go deleted file mode 100644 index 3a6eb89..0000000 --- a/core/lib/external/tg_bot/utils.go +++ /dev/null @@ -1,24 +0,0 @@ -package telegram - -import ( - tg "github.com/temoon/telegram-bots-api" - "io" -) - -func (c *TgBotClient) prepareInputFile(file interface{}, chatID int64, defaultName string) tg.InputFile { - switch v := file.(type) { - case string: - // File ID или URL - return tg.NewInputFile(v, nil, "") - case io.Reader: - // Reader с файлом - if defaultName == "" { - defaultName = "file" - } - return tg.NewInputFile("", v, defaultName) - case tg.InputFile: - return v - default: - return tg.InputFile{} - } -} diff --git a/core/lib/external/tgkit/client.go b/core/lib/external/tgkit/client.go new file mode 100644 index 0000000..ba34607 --- /dev/null +++ b/core/lib/external/tgkit/client.go @@ -0,0 +1,182 @@ +package tgkit + +import ( + "crypto/tls" + "fmt" + "github.com/sirupsen/logrus" + "net/http" + "net/url" + "sync" + "time" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "golang.org/x/net/proxy" +) + +// Client — основной клиент библиотеки +type Client struct { + bot *tgbotapi.BotAPI + timeout time.Duration +} + +// ClientConfig — конфигурация клиента +type ClientConfig struct { + Token string + Proxy *ProxyConfig + Timeout time.Duration // по умолчанию 30s + Debug bool +} + +var ( + mu sync.Mutex + instance *Client +) + +func GetClient(cfg ClientConfig) (*Client, error) { + if instance != nil { + return instance, nil + } + + mu.Lock() + defer mu.Unlock() + + if instance != nil { + return instance, nil + } + + client, err := newClient(cfg) + if err != nil { + return nil, err + } + + instance = client + return instance, nil +} + +// New создаёт нового клиента +func newClient(cfg ClientConfig) (*Client, error) { + if cfg.Token == "" { + return nil, fmt.Errorf("tgkit: token is required") + } + if cfg.Timeout == 0 { + cfg.Timeout = 30 * time.Second + } + + if cfg.Proxy != nil { + logrus.Debugf("tgkit: proxy is configured: url: %s, username: %s, pass: %s", cfg.Proxy.URL, cfg.Proxy.Username, cfg.Proxy.Password) + } + httpClient, err := buildHTTPClient(cfg.Proxy, cfg.Timeout) + if err != nil { + return nil, fmt.Errorf("tgkit: build http client: %w", err) + } + + bot, err := tgbotapi.NewBotAPIWithClient(cfg.Token, tgbotapi.APIEndpoint, httpClient) + if err != nil { + return nil, fmt.Errorf("tgkit: init bot: %w", err) + } + + bot.Debug = cfg.Debug + + return &Client{ + bot: bot, + timeout: cfg.Timeout, + }, nil +} + +// NewFromExisting оборачивает существующий *tgbotapi.BotAPI +// Используется для постепенной миграции без переписывания всего кода +func NewFromExisting(bot *tgbotapi.BotAPI) *Client { + return &Client{bot: bot, timeout: 30 * time.Second} +} + +// Bot возвращает сырой *tgbotapi.BotAPI для обратной совместимости +func (c *Client) Bot() *tgbotapi.BotAPI { + return c.bot +} + +// Self возвращает информацию о боте +func (c *Client) Self() tgbotapi.User { + return c.bot.Self +} + +// GetUpdates возвращает канал обновлений +func (c *Client) GetUpdates(timeout int) tgbotapi.UpdatesChannel { + u := tgbotapi.NewUpdate(0) + u.Timeout = timeout + return c.bot.GetUpdatesChan(u) +} + +// AnswerCallback отвечает на callback query +func (c *Client) AnswerCallback(callbackID string, text string) error { + cb := tgbotapi.NewCallback(callbackID, text) + _, err := c.bot.Request(cb) + return err +} + +// DeleteMessage удаляет сообщение +func (c *Client) DeleteMessage(chatID int64, messageID int) error { + _, err := c.bot.Request(tgbotapi.NewDeleteMessage(chatID, messageID)) + return err +} + +// GetFileDirectURL возвращает прямую ссылку на файл +func (c *Client) GetFileDirectURL(fileID string) (string, error) { + return c.bot.GetFileDirectURL(fileID) +} + +// Request выполняет произвольный запрос к API (для edge cases) +func (c *Client) Request(cfg tgbotapi.Chattable) (*tgbotapi.APIResponse, error) { + return c.bot.Request(cfg) +} + +// buildHTTPClient создаёт http.Client с поддержкой прокси +func buildHTTPClient(proxyCfg *ProxyConfig, timeout time.Duration) (*http.Client, error) { + transport := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: false}, + } + + if proxyCfg != nil && proxyCfg.URL != "" { + proxyURL, err := url.Parse(proxyCfg.URL) + if err != nil { + return nil, fmt.Errorf("parse proxy url: %w", err) + } + + scheme := proxyURL.Scheme + + switch scheme { + case "socks5", "socks5h": + var auth *proxy.Auth + + if proxyCfg.Username != "" { + auth = &proxy.Auth{ + User: proxyCfg.Username, + Password: proxyCfg.Password, + } + } else if proxyURL.User != nil { + pass, _ := proxyURL.User.Password() + auth = &proxy.Auth{ + User: proxyURL.User.Username(), + Password: pass, + } + } + + dialer, err := proxy.SOCKS5("tcp", proxyURL.Host, auth, proxy.Direct) + if err != nil { + return nil, fmt.Errorf("create socks5 dialer: %w", err) + } + + transport.Dial = dialer.Dial //nolint:staticcheck + + case "http", "https": + transport.Proxy = http.ProxyURL(proxyURL) + + default: + return nil, fmt.Errorf("unsupported proxy scheme: %s", scheme) + } + } + + return &http.Client{ + Transport: transport, + Timeout: timeout, + }, nil +} diff --git a/core/lib/external/tgkit/err.go b/core/lib/external/tgkit/err.go new file mode 100644 index 0000000..c6207e0 --- /dev/null +++ b/core/lib/external/tgkit/err.go @@ -0,0 +1,25 @@ +package tgkit + +import "fmt" + +type ErrSend struct { + ChatID int64 + Reason string +} + +func (e *ErrSend) Error() string { + return fmt.Sprintf("tgkit: send to chat %d failed: %s", e.ChatID, e.Reason) +} + +type ErrNilBot struct{} + +func (e *ErrNilBot) Error() string { + return "tgkit: bot client is nil" +} + +func wrapSendErr(chatID int64, err error) error { + if err == nil { + return nil + } + return &ErrSend{ChatID: chatID, Reason: err.Error()} +} diff --git a/core/lib/external/tgkit/keyboard.go b/core/lib/external/tgkit/keyboard.go new file mode 100644 index 0000000..84d0503 --- /dev/null +++ b/core/lib/external/tgkit/keyboard.go @@ -0,0 +1,163 @@ +package tgkit + +import ( + "fmt" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +// ───────────────────────────────────────────── +// Inline-клавиатура +// ───────────────────────────────────────────── + +// InlineKeyboard — построитель inline-клавиатуры +type InlineKeyboard struct { + rows [][]tgbotapi.InlineKeyboardButton +} + +// NewInlineKeyboard создаёт пустой построитель +func NewInlineKeyboard() *InlineKeyboard { + return &InlineKeyboard{} +} + +// Row добавляет ряд кнопок +func (kb *InlineKeyboard) Row(buttons ...InlineButton) *InlineKeyboard { + var row []tgbotapi.InlineKeyboardButton + for _, btn := range buttons { + row = append(row, btn.build()) + } + kb.rows = append(kb.rows, row) + return kb +} + +// Build возвращает готовую клавиатуру +func (kb *InlineKeyboard) Build() tgbotapi.InlineKeyboardMarkup { + return tgbotapi.NewInlineKeyboardMarkup(kb.rows...) +} + +// InlineButton — кнопка inline-клавиатуры +type InlineButton struct { + label string + style ButtonStyle + callback string + url string +} + +// Btn создаёт кнопку с callback +func Btn(label, callback string) InlineButton { + return InlineButton{label: label, callback: callback} +} + +// BtnStyled создаёт кнопку с визуальным стилем (эмодзи) и callback +func BtnStyled(style ButtonStyle, label, callback string) InlineButton { + return InlineButton{label: label, style: style, callback: callback} +} + +// BtnURL создаёт кнопку-ссылку +func BtnURL(label, url string) InlineButton { + return InlineButton{label: label, url: url} +} + +// WithStyle задаёт стиль кнопке +func (b InlineButton) WithStyle(style ButtonStyle) InlineButton { + b.style = style + return b +} + +func (b InlineButton) build() tgbotapi.InlineKeyboardButton { + text := string(b.style) + b.label + if b.url != "" { + return tgbotapi.NewInlineKeyboardButtonURL(text, b.url) + } + return tgbotapi.NewInlineKeyboardButtonData(text, b.callback) +} + +// ───────────────────────────────────────────── +// Reply-клавиатура (постоянные кнопки) +// ───────────────────────────────────────────── + +// ReplyKeyboard — построитель reply-клавиатуры +type ReplyKeyboard struct { + rows [][]tgbotapi.KeyboardButton + resize bool + oneTime bool +} + +// NewReplyKeyboard создаёт пустой построитель +func NewReplyKeyboard() *ReplyKeyboard { + return &ReplyKeyboard{resize: true} +} + +// Row добавляет ряд текстовых кнопок +func (kb *ReplyKeyboard) Row(labels ...string) *ReplyKeyboard { + var row []tgbotapi.KeyboardButton + for _, label := range labels { + row = append(row, tgbotapi.NewKeyboardButton(label)) + } + kb.rows = append(kb.rows, row) + return kb +} + +// OneTime скрывает клавиатуру после нажатия +func (kb *ReplyKeyboard) OneTime() *ReplyKeyboard { + kb.oneTime = true + return kb +} + +// NoResize отключает авторесайз +func (kb *ReplyKeyboard) NoResize() *ReplyKeyboard { + kb.resize = false + return kb +} + +// Build возвращает готовую клавиатуру +func (kb *ReplyKeyboard) Build() tgbotapi.ReplyKeyboardMarkup { + markup := tgbotapi.NewReplyKeyboard(kb.rows...) + markup.ResizeKeyboard = kb.resize + markup.OneTimeKeyboard = kb.oneTime + return markup +} + +// RemoveKeyboard убирает reply-клавиатуру +func RemoveKeyboard() tgbotapi.ReplyKeyboardRemove { + return tgbotapi.NewRemoveKeyboard(false) +} + +// ───────────────────────────────────────────── +// Готовые шаблоны клавиатур +// ───────────────────────────────────────────── + +// ConfirmKeyboard — клавиатура Да/Нет +func ConfirmKeyboard(yesCallback, noCallback string) tgbotapi.InlineKeyboardMarkup { + return NewInlineKeyboard(). + Row( + BtnStyled(ButtonStyleSuccess, "Да", yesCallback), + BtnStyled(ButtonStyleDanger, "Нет", noCallback), + ). + Build() +} + +// BackKeyboard — одна кнопка "← Назад" +func BackKeyboard(callback string) tgbotapi.InlineKeyboardMarkup { + return NewInlineKeyboard(). + Row(BtnStyled(ButtonStyleBack, "Назад", callback)). + Build() +} + +// PaginationRow — ряд кнопок пагинации +func PaginationRow(page, totalPages int, prevCallback, nextCallback, noopCallback string) []tgbotapi.InlineKeyboardButton { + var row []tgbotapi.InlineKeyboardButton + + if page > 0 { + row = append(row, Btn("←", prevCallback).build()) + } + + row = append(row, tgbotapi.NewInlineKeyboardButtonData( + fmt.Sprintf("%d / %d", page+1, totalPages), noopCallback, + )) + + if page < totalPages-1 { + row = append(row, Btn("→", nextCallback).build()) + } + + return row +} diff --git a/core/lib/external/tgkit/media.go b/core/lib/external/tgkit/media.go new file mode 100644 index 0000000..2fd0c07 --- /dev/null +++ b/core/lib/external/tgkit/media.go @@ -0,0 +1,180 @@ +package tgkit + +import ( + "encoding/base64" + "fmt" + "io" + "net/http" + "os" + + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// SendPhoto отправляет фото по URL, пути к файлу или base64 +func (c *Client) SendPhoto(chatID int64, source string, caption string, opts ...MessageOptions) (*SentMessage, error) { + var photo tgbotapi.RequestFileData + + switch { + case isURL(source): + photo = tgbotapi.FileURL(source) + case isBase64(source): + data, err := base64.StdEncoding.DecodeString(source) + if err != nil { + return nil, fmt.Errorf("tgkit: decode base64: %w", err) + } + photo = tgbotapi.FileBytes{Name: "photo.jpg", Bytes: data} + default: + photo = tgbotapi.FilePath(source) + } + + msg := tgbotapi.NewPhoto(chatID, photo) + msg.Caption = caption + msg.ParseMode = "HTML" + + if len(opts) > 0 && opts[0].ReplyMarkup != nil { + msg.ReplyMarkup = opts[0].ReplyMarkup + } + + sent, err := c.bot.Send(msg) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + + return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil +} + +// SendDocument отправляет документ +func (c *Client) SendDocument(chatID int64, data []byte, fileName string, caption string, opts ...MessageOptions) (*SentMessage, error) { + doc := tgbotapi.NewDocument(chatID, tgbotapi.FileBytes{ + Name: fileName, + Bytes: data, + }) + doc.Caption = caption + doc.ParseMode = "HTML" + + if len(opts) > 0 && opts[0].ReplyMarkup != nil { + doc.ReplyMarkup = opts[0].ReplyMarkup + } + + sent, err := c.bot.Send(doc) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + + return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil +} + +// SendDocumentFromBase64 отправляет документ из base64-строки +func (c *Client) SendDocumentFromBase64(chatID int64, base64Data string, fileName string, caption string, opts ...MessageOptions) (*SentMessage, error) { + data, err := base64.StdEncoding.DecodeString(base64Data) + if err != nil { + return nil, fmt.Errorf("tgkit: decode base64: %w", err) + } + return c.SendDocument(chatID, data, fileName, caption, opts...) +} + +// SendSticker отправляет стикер по fileID +func (c *Client) SendSticker(chatID int64, fileID string) (*SentMessage, error) { + sticker := tgbotapi.NewSticker(chatID, tgbotapi.FileID(fileID)) + sent, err := c.bot.Send(sticker) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + return &SentMessage{MessageID: sent.MessageID, ChatID: sent.Chat.ID}, nil +} + +// SendMediaGroup отправляет группу медиафайлов (альбом) +func (c *Client) SendMediaGroup(chatID int64, files []MediaFile) error { + if len(files) == 0 { + return nil + } + + var media []interface{} + for i, f := range files { + photo := tgbotapi.NewInputMediaPhoto(tgbotapi.FileBytes{ + Name: f.FileName, + Bytes: f.Data, + }) + if i == 0 && f.Caption != "" { + photo.Caption = f.Caption + photo.ParseMode = "HTML" + } + media = append(media, photo) + } + + mediaGroup := tgbotapi.NewMediaGroup(chatID, media) + _, err := c.bot.Request(mediaGroup) + return err +} + +// DownloadFile скачивает файл из Telegram по fileID, возвращает байты +func (c *Client) DownloadFile(fileID string) ([]byte, string, error) { + fileURL, err := c.bot.GetFileDirectURL(fileID) + if err != nil { + return nil, "", fmt.Errorf("tgkit: get file url: %w", err) + } + + resp, err := http.Get(fileURL) //nolint:gosec + if err != nil { + return nil, "", fmt.Errorf("tgkit: download file: %w", err) + } + defer resp.Body.Close() + + data, err := io.ReadAll(resp.Body) + if err != nil { + return nil, "", fmt.Errorf("tgkit: read file: %w", err) + } + + // Извлекаем имя файла из URL + fileName := extractFileName(fileURL) + return data, fileName, nil +} + +// DownloadFileAsBase64 скачивает файл и возвращает base64 +func (c *Client) DownloadFileAsBase64(fileID string) (string, string, error) { + data, fileName, err := c.DownloadFile(fileID) + if err != nil { + return "", "", err + } + return base64.StdEncoding.EncodeToString(data), fileName, nil +} + +// MustSendDocument отправляет документ, логирует ошибку +func (c *Client) MustSendDocument(chatID int64, data []byte, fileName, caption string, opts ...MessageOptions) { + if _, err := c.SendDocument(chatID, data, fileName, caption, opts...); err != nil { + logrus.Warnf("tgkit.MustSendDocument: chatID=%d file=%s err=%v", chatID, fileName, err) + } +} + +// MediaFile — структура для SendMediaGroup +type MediaFile struct { + Data []byte + FileName string + Caption string +} + +func isURL(s string) bool { + return len(s) > 4 && (s[:4] == "http" || s[:5] == "https") +} + +func isBase64(s string) bool { + if len(s) < 4 { + return false + } + _, err := base64.StdEncoding.DecodeString(s[:4]) + return err == nil && len(s)%4 == 0 +} + +func extractFileName(fileURL string) string { + for i := len(fileURL) - 1; i >= 0; i-- { + if fileURL[i] == '/' { + return fileURL[i+1:] + } + } + return "file" +} + +func readFile(path string) ([]byte, error) { + return os.ReadFile(path) //nolint:gosec +} diff --git a/core/lib/external/tgkit/message.go b/core/lib/external/tgkit/message.go new file mode 100644 index 0000000..c049e35 --- /dev/null +++ b/core/lib/external/tgkit/message.go @@ -0,0 +1,87 @@ +package tgkit + +import ( + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" + "github.com/sirupsen/logrus" +) + +// Send отправляет текстовое сообщение +func (c *Client) Send(chatID int64, text string, opts ...MessageOptions) (*SentMessage, error) { + if c.bot == nil { + return nil, &ErrNilBot{} + } + + msg := tgbotapi.NewMessage(chatID, text) + msg.ParseMode = "HTML" // дефолт + + if len(opts) > 0 { + opt := opts[0] + if opt.ParseMode != "" { + msg.ParseMode = string(opt.ParseMode) + } + if opt.ReplyMarkup != nil { + msg.ReplyMarkup = opt.ReplyMarkup + } + msg.DisableWebPagePreview = opt.DisablePreview + msg.DisableNotification = opt.Silent + } + + sent, err := c.bot.Send(msg) + if err != nil { + return nil, wrapSendErr(chatID, err) + } + + return &SentMessage{ + MessageID: sent.MessageID, + ChatID: sent.Chat.ID, + Date: sent.Time(), + }, nil +} + +// MustSend отправляет сообщение, логирует ошибку но не возвращает её. +// Используется когда ошибка некритична (уведомление). +func (c *Client) MustSend(chatID int64, text string, opts ...MessageOptions) { + if _, err := c.Send(chatID, text, opts...); err != nil { + logrus.Warnf("tgkit.MustSend: chatID=%d err=%v", chatID, err) + } +} + +// EditText редактирует текст существующего сообщения +func (c *Client) EditText(chatID int64, messageID int, text string, opts ...MessageOptions) error { + edit := tgbotapi.NewEditMessageText(chatID, messageID, text) + edit.ParseMode = "HTML" + + if len(opts) > 0 && opts[0].ParseMode != "" { + edit.ParseMode = string(opts[0].ParseMode) + } + + _, err := c.bot.Request(edit) + return err +} + +// EditKeyboard заменяет клавиатуру у существующего сообщения +func (c *Client) EditKeyboard(chatID int64, messageID int, keyboard tgbotapi.InlineKeyboardMarkup) error { + edit := tgbotapi.NewEditMessageReplyMarkup(chatID, messageID, keyboard) + _, err := c.bot.Request(edit) + return err +} + +// WithKeyboard — хелпер для построения MessageOptions с клавиатурой +func WithKeyboard(markup interface{}) MessageOptions { + return MessageOptions{ReplyMarkup: markup} +} + +// WithInline — хелпер для inline-клавиатуры +func WithInline(kb *InlineKeyboard) MessageOptions { + return MessageOptions{ReplyMarkup: kb.Build()} +} + +// WithReply — хелпер для reply-клавиатуры +func WithReply(kb *ReplyKeyboard) MessageOptions { + return MessageOptions{ReplyMarkup: kb.Build()} +} + +// WithSilent — хелпер для тихой отправки +func WithSilent() MessageOptions { + return MessageOptions{Silent: true} +} diff --git a/core/lib/external/tgkit/types.go b/core/lib/external/tgkit/types.go new file mode 100644 index 0000000..a4065d4 --- /dev/null +++ b/core/lib/external/tgkit/types.go @@ -0,0 +1,57 @@ +package tgkit + +import "time" + +// ParseMode — режим форматирования текста +type ParseMode string + +const ( + ParseModeHTML ParseMode = "HTML" + ParseModeMarkdown ParseMode = "MarkdownV2" + ParseModePlain ParseMode = "" +) + +// ButtonColorStyle — стили цветов кнопок +type ButtonColorStyle string + +const ( + ButtonColorStyleDanger ButtonColorStyle = "danger" // красная + ButtonColorStyleSuccess ButtonColorStyle = "success" // зеленая + ButtonColorStylePrimary ButtonColorStyle = "primary" // синяя +) + +// ButtonStyle — визуальный стиль кнопки (через эмодзи) +type ButtonStyle string + +const ( + ButtonStyleDefault ButtonStyle = "" + ButtonStyleSuccess ButtonStyle = "✅ " + ButtonStyleDanger ButtonStyle = "❌ " + ButtonStyleWarning ButtonStyle = "⚠️ " + ButtonStyleInfo ButtonStyle = "ℹ️ " + ButtonStylePrimary ButtonStyle = "🔵 " + ButtonStyleBack ButtonStyle = "← " + ButtonStyleForward ButtonStyle = "→ " +) + +// MessageOptions — опции отправки сообщения +type MessageOptions struct { + ParseMode ParseMode + ReplyMarkup interface{} + DisablePreview bool + Silent bool +} + +// ProxyConfig — настройки прокси +type ProxyConfig struct { + URL string // socks5://user:pass@host:port или http://host:port + Username string + Password string +} + +// SentMessage — результат отправки +type SentMessage struct { + MessageID int + ChatID int64 + Date time.Time +} diff --git a/service/telegram_service/cmd/app.go b/service/telegram_service/cmd/app.go index be27840..953fa28 100644 --- a/service/telegram_service/cmd/app.go +++ b/service/telegram_service/cmd/app.go @@ -2,7 +2,7 @@ package main import ( configcore "bitrix_balancer_api/core/config" - "bitrix_balancer_api/core/lib/external/telegram" + "bitrix_balancer_api/core/lib/external/tgkit" clientcontrollers "bitrix_balancer_api/core/lib/internally/client-controllers" tgupdatehandler "bitrix_balancer_api/telegram_service/common/update" "bitrix_balancer_api/telegram_service/scheduler" @@ -57,8 +57,11 @@ func getClientsExternal() (clientcontrollers.ClientsExternal, error) { } func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontrollers.ClientsExternal) (*types.InternalProviderControl, error) { - tgBotClient, err := telegram.NewTgBotClient(&telegram.BotConfig{ - BotKey: cfg.Telegram.BotToken, + tgKitClient, err := tgkit.GetClient(tgkit.ClientConfig{ + Token: cfg.Telegram.BotToken, + Proxy: &tgkit.ProxyConfig{ + URL: cfg.Telegram.ProxyURL, + }, }) if err != nil { return nil, err @@ -68,7 +71,7 @@ func initInternalProvider(cfg *configcore.Config, clientsExternal clientcontroll Config: cfg, Database: clientsExternal.DB, RedisClient: clientsExternal.Redis, - TGBotClient: tgBotClient, + TGBotClient: tgKitClient, }, nil } diff --git a/service/telegram_service/common/update/0_init.go b/service/telegram_service/common/update/0_init.go index 67caa75..7b80554 100644 --- a/service/telegram_service/common/update/0_init.go +++ b/service/telegram_service/common/update/0_init.go @@ -46,7 +46,7 @@ func NewUpdateHandler(ipc *types.InternalProviderControl) *UpdateHandler { func (s *UpdateHandler) broadcastBotUpdated() { ctx := context.Background() - bot := s.ipc.TGBotClient.GetBot() + bot := s.ipc.TGBotClient.Bot() users, _, err := s.ipc.Database.User.GetUsersListDB(ctx, typescore.ListDbOptions{}) if err != nil { diff --git a/service/telegram_service/common/update/update.go b/service/telegram_service/common/update/update.go index 133f9a4..4fc995c 100644 --- a/service/telegram_service/common/update/update.go +++ b/service/telegram_service/common/update/update.go @@ -10,7 +10,7 @@ import ( ) func (s *UpdateHandler) GetUpdateTelegram() { - bot := s.ipc.TGBotClient.GetBot() + bot := s.ipc.TGBotClient.Bot() u := tgbotapi.NewUpdate(0) u.Timeout = 10 diff --git a/service/telegram_service/handlers/approval/notify.go b/service/telegram_service/handlers/approval/notify.go index a6d1f62..aace569 100644 --- a/service/telegram_service/handlers/approval/notify.go +++ b/service/telegram_service/handlers/approval/notify.go @@ -33,11 +33,21 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec } topicName := "—" + topicCategory := "—" if approval.TopicID != nil { topic, _ := h.ipc.Database.ApprovalTopic.GetApprovalTopicByIDDB(ctx, *approval.TopicID) if topic != nil && topic.Name != nil { topicName = *topic.Name } + if topic != nil && topic.CategoryID != nil { + approvalCategory, err := h.ipc.Database.ApprovalTopicCategory.GetApprovalTopicCategoryByIDDB(ctx, *topic.CategoryID) + if err != nil { + logrus.Errorf("get approval topic category error: %v", err) + } + if approvalCategory != nil && approvalCategory.Name != nil { + topicCategory = *approvalCategory.Name + } + } } content := "—" @@ -53,10 +63,10 @@ func (h *Handler) notifyExecutor(bot *tgbotapi.BotAPI, ctx context.Context, exec text := fmt.Sprintf( "📋 Новая задача по заявке #%d\n\n"+ "👤 Инициатор: %s\n"+ - "📋 Тема: %s\n"+ + "📋 Тема: %s: %s\n"+ "📝 Текст заявки: %s\n\n"+ "🎯 Задача:\n%s", - *approval.ID, initiatorName, topicName, content, taskText, + *approval.ID, initiatorName, topicCategory, topicName, content, taskText, ) // Добавляем комментарии diff --git a/service/telegram_service/scheduler/delegation_checker.go b/service/telegram_service/scheduler/delegation_checker.go index b0c13a2..f48220c 100644 --- a/service/telegram_service/scheduler/delegation_checker.go +++ b/service/telegram_service/scheduler/delegation_checker.go @@ -32,7 +32,7 @@ func (dc *DelegationChecker) Start() { func (dc *DelegationChecker) checkDelegations() { ctx := context.Background() - bot := dc.ipc.TGBotClient.GetBot() + bot := dc.ipc.TGBotClient.Bot() isActive := true delegations, _, err := dc.ipc.Database.ApprovalDelegation.GetApprovalDelegationsListDB(ctx, typescore.ListDbOptions{ diff --git a/service/telegram_service/types/types.go b/service/telegram_service/types/types.go index 3f60a73..d42782a 100644 --- a/service/telegram_service/types/types.go +++ b/service/telegram_service/types/types.go @@ -3,13 +3,14 @@ package types import ( configcore "bitrix_balancer_api/core/config" database "bitrix_balancer_api/core/db" - "bitrix_balancer_api/core/lib/external/telegram" + "bitrix_balancer_api/core/lib/external/tgkit" + redismodule "bitrix_balancer_api/core/lib/internally/redis" ) type InternalProviderControl struct { Config *configcore.Config RedisClient *redismodule.ModuleRedis - TGBotClient *telegram.TgBotClient + TGBotClient *tgkit.Client Database *database.ModuleDB }