使用的编程语言是 Google Apps Script 中的 JavaScript。
我想将 Google Drive 中存储的视频文件上传到 Slack。
我想给某人发一条私信。
这是代码:
function myFunction() {
let token = "Slack_Bot_User_Outh_Token"
let bot_token = "Slack_User_Outh_Token"
let user_id = "slack_user_id"
let user_channel_original_id = get_user_channel_id(token, user_id)
let file_info = DriveApp.getFileById("Drive_file_id")
let slack_file_uploaded_id = get_upload_url(token, file_info)
post_slack_to_person(token, slack_file_uploaded_id, user_channel_original_id)
}
function get_user_channel_id(token, user_id) {
let slack_conversion_url = "https://slack.com/api/conversations.open"
let options = {
"method": "post",
"payload": {
"token": token,
"users": user_id
}
}
let res = UrlFetchApp.fetch(slack_conversion_url, options)
let user_channel_id = JSON.parse(res.getContentText()).channel.id
return user_channel_id
}
function get_upload_url(token, file_info) {
let send_toslack_url = "https://slack.com/api/files.getUploadURLExternal"
let options = {
"method": "get",
"payload": {
"token": token,
"filename": file_info,
"length": file_info.getSize().toString(),
}
}
let res = UrlFetchApp.fetch(send_toslack_url, options)
return JSON.parse(res).file_id
}
function post_slack_to_person(token, file_id, channel_id) {
let post_directmessages = "https://slack.com/api/files.completeUploadExternal"
let options = {
"method": "post",
"headers": {
"Authorization": "Bearer " + token,
},
"contentType": "application/json",
"payload": JSON.stringify(
{
files: [
{
"id": file_id,
}
],
"channel_id": channel_id,
},
)
}
let res = UrlFetchApp.fetch(post_directmessages, options)
Logger.log(res)
return res
}
这是回应。
{
"ok": true, "files": [
{
"id": "I can't show you",
"created": 1716643818,
"timestamp": 1716643818,
"name": "TEST.mp4",
"title": "TEST.mp4",
"mimetype": "",
"filetype": "",
"pretty_type": "",
"user": "I can't show you",
"user_team": "I can't show you",
"editable": false,
"size": 13659221,
"mode": "hosted",
"is_external": false,
"external_type": "",
"is_public": false,
"public_url_shared": false,
"display_as_bot": false,
"username": "",
"url_private": "I can't show you",
"url_private_download": "I can't show you",
"media_display_type": "unknown",
"permalink": "I can't show you",
"permalink_public": "I can't show you",
"comments_count": 0,
"is_starred": false,
"shares": {},
"channels": [],
"groups": [],
"ims": [],
"has_more_shares": false,
"has_rich_preview": false,
"file_access": "visible"
}
],
"warning": "missing_charset",
"response_metadata": {
"warnings": [
"missing_charset"
]
}
}
文档:https://api.slack.com/methods/files.completeUploadExternalhttps://api.slack.com/methods/files.getUploadURLExternal
files.getUploadURL外部响应有
upload_url
和 file_id
。
使用 files.completeUploadExternal 之前,请向
upload_url
发送 POST 请求以及您的文件
# python code
res = req.post(
url=upload_url,
headers={"Authorization": f"Bearer {slack_bot_token}"},
files=files,
)