download.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package telegram
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. )
  8. // downloadFileId download file with fileID, return the filepath and blob.
  9. func (r *Robot) downloadFileID(ctx context.Context, fileID string) (string, []byte, error) {
  10. file, err := r.GetFile(ctx, fileID)
  11. if err != nil {
  12. return "", nil, err
  13. }
  14. blob, err := r.downloadFilepath(ctx, file.FilePath)
  15. if err != nil {
  16. return "", nil, err
  17. }
  18. return file.FilePath, blob, nil
  19. }
  20. // downloadFilepath download file with filepath, you can get filepath by calling GetFile.
  21. func (r *Robot) downloadFilepath(ctx context.Context, filePath string) ([]byte, error) {
  22. token := r.handler.RobotToken(ctx)
  23. if token == "" {
  24. return nil, ErrNoToken
  25. }
  26. uri := "https://api.telegram.org/file/bot" + token + "/" + filePath
  27. resp, err := http.Get(uri)
  28. if err != nil {
  29. return nil, fmt.Errorf("fail to http.Get: %s", err)
  30. }
  31. defer resp.Body.Close()
  32. body, err := io.ReadAll(resp.Body)
  33. if err != nil {
  34. return nil, fmt.Errorf("fail to io.ReadAll: %s", err)
  35. }
  36. return body, nil
  37. }