You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Apps Script上传Drive视频至Slack DM异常排查

问题排查与解决方案

你遇到的核心问题是Slack未正确识别视频文件元数据,导致mimetype、filetype字段为空,media_display_type显示为unknown。这通常是因为调用Slack API时未传递关键文件元数据,或上传的文件数据格式不符合要求。以下是具体排查和修复步骤:

1. 检查files.getUploadURLExternal的请求参数

调用该接口时必须传递两个核心参数,Slack依赖它们识别文件类型:

  • filename:必须包含完整文件扩展名(如demo.mp4)
  • length:文件的精确字节大小,需与实际上传的文件字节数完全匹配

示例请求代码:

const SLACK_TOKEN = '你的Slack令牌';
const DRIVE_FILE_ID = 'Google Drive文件ID';
const TARGET_USER_ID = '目标用户Slack ID';

const driveFile = DriveApp.getFileById(DRIVE_FILE_ID);
const getUploadUrlOpts = {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${SLACK_TOKEN}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  payload: {
    filename: driveFile.getName(), // 确保带扩展名
    length: driveFile.getSize(),
    channels: TARGET_USER_ID // DM直接传用户ID
  }
};
const getUploadUrlRes = UrlFetchApp.fetch('https://slack.com/api/files.getUploadURLExternal', getUploadUrlOpts);
const uploadUrlData = JSON.parse(getUploadUrlRes.getContentText());

2. 正确上传Google Drive文件的二进制数据

从Drive获取文件时,需直接传递原始字节数据,并设置正确的Content-Type请求头:

const fileBlob = driveFile.getBlob();
const uploadOpts = {
  method: 'POST',
  headers: {
    'Content-Type': fileBlob.getContentType(), // 用Drive文件自带的mimetype
    'Content-Length': fileBlob.getBytes().length
  },
  payload: fileBlob.getBytes()
};
UrlFetchApp.fetch(uploadUrlData.upload_url, uploadOpts);

3. 完善files.completeUploadExternal的参数

调用该接口时,需明确指定文件的mimetype和title,帮助Slack确认文件类型:

const completeOpts = {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${SLACK_TOKEN}`,
    'Content-Type': 'application/json'
  },
  payload: JSON.stringify({
    files: [{
      id: uploadUrlData.file_id,
      title: driveFile.getName(),
      mimetype: fileBlob.getContentType()
    }],
    channels: TARGET_USER_ID
  })
};
const completeRes = UrlFetchApp.fetch('https://slack.com/api/files.completeUploadExternal', completeOpts);

关键注意事项

  • 确保Slack应用已授权files:write和chat:write权限
  • 文件名扩展名必须与实际文件类型匹配(如.mp4对应video/mp4,.mov对应video/quicktime)
  • 上传的字节数必须与length参数完全一致,否则Slack无法正确解析文件
  • 目标用户ID可通过Slack的users.list接口获取,或从客户端用户资料中复制

内容的提问来源于stack exchange,提问作者Cliper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:07:42