Files
gateway-telegram/internal/infrastructure/telegram/file_downloader.go

49 lines
1.1 KiB
Go

package telegram
import (
"context"
"fmt"
"io"
"net/http"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
type TelegramFileDownloader struct {
bot *tgbotapi.BotAPI
client *http.Client
}
func NewTelegramFileDownloader(bot *tgbotapi.BotAPI) *TelegramFileDownloader {
return &TelegramFileDownloader{
bot: bot,
client: &http.Client{},
}
}
func (d *TelegramFileDownloader) Download(ctx context.Context, fileID string) ([]byte, string, error) {
file, err := d.bot.GetFile(tgbotapi.FileConfig{FileID: fileID})
if err != nil {
return nil, "", fmt.Errorf("get file info: %w", err)
}
url := file.Link(d.bot.Token)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, "", fmt.Errorf("create download request: %w", err)
}
resp, err := d.client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("download file: %w", err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", fmt.Errorf("read file body: %w", err)
}
return data, "audio/ogg", nil
}