v0.5.1

미디어 저장

마지막 업데이트


각 플랫폼의 Save 메서드는 받은 파일을 디렉터리에 다운로드하고 저장된 경로를 반환합니다.

시그니처


  1. // core/telegram — fileID는 Input.Photo[i].FileID 또는 Input.Document.FileID에서 가져옴
  2. func (b *Bot) Save(ctx context.Context, fileID, dir string) (string, error)
  3. // core/discord — Input.Attachments의 항목 하나
  4. func (b *Bot) Save(ctx context.Context, att *discordgo.MessageAttachment, dir string) (string, error)
  5. // core/line — image, video, audio, file 메시지의 Input.MessageID
  6. func (b *Bot) Save(ctx context.Context, messageID, dir string) (string, error)

플랫폼별 동작


TelegramDiscordLINE
크기 상한20 MiB(Bot API getFile 제한)25 MiB50 MiB(라이브러리 제한)
다운로드 전 크기 확인GetFile → FileSizeatt.SizeContentLength
다운로드http.DefaultClient로 FileDownloadLinkhttp.DefaultClient로 att.URLGetMessageContent 스트림
확장자Telegram의 file_path에서att.Filename에서응답의 Content-Type에서

공통 단계


  1. 빈 인자(fileID / att / att.URL / messageID, 그리고 dir)를 거부합니다.
  2. 보고된 크기가 상한을 넘으면 다운로드 전에 파일을 거부합니다.
  3. HTTP 상태가 200이 아니면(Telegram, Discord) 본문을 최대 8 KiB 포함해 http <code>: <body>를 반환합니다.
  4. os.MkdirAll(dir, 0755)로 dir을 만듭니다.
  5. dir 안의 임시 파일 <uuid>.*.tmp로 스트리밍하며 최대 상한 + 1바이트까지 읽습니다. 상한보다 많은 데이터가 오면(보고된 크기가 없거나 틀린 경우) 임시 파일을 삭제하고 오류를 반환합니다. 상한을 넘는 파일을 잘라서 저장하는 일은 없습니다.
  6. 임시 파일 이름을 <uuid><ext>로 바꾸고 전체 경로를 반환합니다.

파일 이름은 go-pkg/utils가 만든 v4 UUID입니다. UUID가 비어 있으면(난수 소스 실패) 오류로 반환됩니다. Telegram/Discord의 원래 파일 이름은 유지되지 않으며, LINE file 메시지의 원래 이름은 Input.FileName에 있습니다.

LINE 확장자 매핑


image/jpeg → .jpg, image/png → .png, image/gif → .gif, image/webp → .webp, video/mp4 → .mp4, audio/mp4와 audio/x-m4a → .m4a, audio/aac → .aac, application/pdf → .pdf. 그 밖의 타입은 mime.ExtensionsByType의 첫 번째 확장자를 사용하고, 알 수 없는 타입에는 확장자가 붙지 않습니다.

예시


  1. bot.Reply(func(ctx context.Context, in discord.Input) string {
  2. for _, att := range in.Attachments {
  3. path, err := bot.Save(ctx, att, "./uploads")
  4. if err != nil {
  5. return "save failed: " + err.Error()
  6. }
  7. log.Println("saved", path)
  8. }
  9. return ""
  10. })

관련 페이지