2023-05-26 04:43:51 +03:00
|
|
|
package telegram
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2023-05-29 08:29:21 +03:00
|
|
|
"strings"
|
2023-05-26 04:43:51 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// downloadFileId download file with fileID, return the filepath and blob.
|
2023-05-29 14:49:05 +03:00
|
|
|
func (b *Bot) downloadFileID(ctx context.Context, fileID string) (string, []byte, error) {
|
|
|
|
file, err := b.GetFile(ctx, fileID)
|
2023-05-26 04:43:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
2023-05-29 14:49:05 +03:00
|
|
|
blob, err := b.downloadFilepath(ctx, file.FilePath)
|
2023-05-26 04:43:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return "", nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return file.FilePath, blob, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// downloadFilepath download file with filepath, you can get filepath by calling GetFile.
|
2023-05-29 14:49:05 +03:00
|
|
|
func (b *Bot) downloadFilepath(ctx context.Context, filePath string) ([]byte, error) {
|
|
|
|
apiURL, err := b.apiURL(ctx)
|
2023-05-29 08:29:21 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
idx := strings.LastIndex(apiURL, "/bot")
|
|
|
|
if idx < 0 {
|
|
|
|
return nil, ErrInvalidToken
|
2023-05-26 04:43:51 +03:00
|
|
|
}
|
|
|
|
|
2023-05-29 08:29:21 +03:00
|
|
|
fileURL := apiURL[:idx] + "/file" + apiURL[idx:]
|
|
|
|
|
|
|
|
resp, err := http.Get(fileURL + "/" + filePath)
|
2023-05-26 04:43:51 +03:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("fail to http.Get: %s", err)
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("fail to io.ReadAll: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return body, nil
|
|
|
|
}
|