verification/internal/client/telegram.go

85 lines
1.8 KiB
Go
Raw Normal View History

2023-06-12 14:19:10 +00:00
package client
import (
"bytes"
2024-02-11 18:22:37 +00:00
_ "embed"
"fmt"
2023-06-12 14:19:10 +00:00
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"go.uber.org/zap"
"penahub.gitlab.yandexcloud.net/backend/verification/internal/models"
2023-06-12 14:19:10 +00:00
"text/template"
)
2024-02-11 18:22:37 +00:00
//go:embed assets/new_verification.txt
var NewVerification string
//go:embed assets/updated_verification.txt
var UpdatedVerification string
type Deps struct {
Logger *zap.Logger
Bot *tgbotapi.BotAPI
ChatID int64
StagingURL string
2023-06-12 14:19:10 +00:00
}
2024-02-11 18:22:37 +00:00
type Telegram struct {
logger *zap.Logger
bot *tgbotapi.BotAPI
chatID int64
stagingURL string
2023-06-12 14:19:10 +00:00
}
2024-02-11 18:22:37 +00:00
func NewTelegram(deps Deps) *Telegram {
return &Telegram{logger: deps.Logger, bot: deps.Bot, chatID: deps.ChatID, stagingURL: deps.StagingURL}
}
2023-06-12 14:19:10 +00:00
2024-02-11 18:22:37 +00:00
func (t *Telegram) SendVerification(data *models.Verification, url string, isUpdate bool) error {
var tplPath string
2023-06-12 14:19:10 +00:00
if isUpdate {
2024-02-11 18:22:37 +00:00
tplPath = UpdatedVerification
} else {
tplPath = NewVerification
2023-06-12 14:19:10 +00:00
}
2024-02-11 18:22:37 +00:00
var userURL string
if url == t.stagingURL {
2024-02-11 19:34:15 +00:00
userURL = fmt.Sprintf("%s/users/%s", t.stagingURL, data.UserID)
2024-02-11 18:22:37 +00:00
} else {
userURL = fmt.Sprintf("https://admin.pena/users/%s", data.UserID)
}
tpl, err := template.New("verification_template").Parse(tplPath)
2023-06-12 14:19:10 +00:00
if err != nil {
2024-02-11 18:22:37 +00:00
return fmt.Errorf("error parsing template: %w", err)
2023-06-12 14:19:10 +00:00
}
var text bytes.Buffer
2024-02-11 18:22:37 +00:00
toTG := models.ToTelegram{
ID: data.ID,
UserID: data.UserID,
UserURL: userURL,
Accepted: data.Accepted,
Status: data.Status,
UpdatedAt: data.UpdatedAt,
Comment: data.Comment,
Files: data.Files,
TaxNumber: data.TaxNumber,
}
err = tpl.Execute(&text, toTG)
2023-06-12 14:19:10 +00:00
if err != nil {
2024-02-11 18:22:37 +00:00
return fmt.Errorf("error executing template: %w", err)
2023-06-12 14:19:10 +00:00
}
msg := tgbotapi.NewMessage(t.chatID, text.String())
_, err = t.bot.Send(msg)
if err != nil {
2024-02-11 18:22:37 +00:00
return fmt.Errorf("error sending message: %w", err)
2023-06-12 14:19:10 +00:00
}
return nil
}