download.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package telegram
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. )
  9. // downloadFileId download file with fileID, return the filepath and blob.
  10. func (b *Bot) downloadFileID(ctx context.Context, fileID string) (string, []byte, error) {
  11. file, err := b.GetFile(ctx, fileID)
  12. if err != nil {
  13. return "", nil, err
  14. }
  15. blob, err := b.downloadFilepath(ctx, file.FilePath)
  16. if err != nil {
  17. return "", nil, err
  18. }
  19. return file.FilePath, blob, nil
  20. }
  21. // downloadFilepath download file with filepath, you can get filepath by calling GetFile.
  22. func (b *Bot) downloadFilepath(ctx context.Context, filePath string) ([]byte, error) {
  23. apiURL, err := b.apiURL(ctx)
  24. if err != nil {
  25. return nil, err
  26. }
  27. idx := strings.LastIndex(apiURL, "/bot")
  28. if idx < 0 {
  29. return nil, ErrInvalidToken
  30. }
  31. fileURL := apiURL[:idx] + "/file" + apiURL[idx:]
  32. resp, err := http.Get(fileURL + "/" + filePath)
  33. if err != nil {
  34. return nil, fmt.Errorf("fail to http.Get: %s", err)
  35. }
  36. defer resp.Body.Close()
  37. body, err := io.ReadAll(resp.Body)
  38. if err != nil {
  39. return nil, fmt.Errorf("fail to io.ReadAll: %s", err)
  40. }
  41. return body, nil
  42. }