Twitter Api v1.1 来自 Google 应用脚本的多部分请求(附加端点)总是给出错误

发布于 2025-01-16 15:43:58 字数 3817 浏览 3 评论 0 原文

在下面的函数中,我从 Twitter 收到了错误响应“错误请求”。

//param1 file === DriveApp.getFileById()
//param2 init === returned object of initTwitterUpload function
//param3 service === OAuth1.createService()
function appendTwitterUpload(file,init,service) {
  var blob = file.getBlob()
  var bytes = blob.getBytes()
  var base64Blob = Utilities.base64Encode(bytes)
  var metaData = {name: file.getName(),
    mimeType: file.getMimeType()}
  var baseUrl =  "https://upload.twitter.com/1.1/media/upload.json" //?command=APPEND&media_id=" 
    //Oauth1percentEncode(init["media_id_string"]) +  "&segment_index=" + Oauth1percentEncode(0);
  var options = {method:'POST',
                 contentType : 'multipart/form-data',
                 payload : {'command':'APPEND',
                            'media_id' : init["media_id"],
                            'segment_index': 0,
                           },
                 files:{'media': bytes},
                 muteHttpExceptions:true}
  var response = service.fetch(baseUrl,options);
  return JSON.parse(response.getContentText())
}

任何 Twitter 开发人员都在寻找错误,我发现了一个带有 Google 应用程序脚本的错误。我正在使用 OAuth 1.0a 身份验证并遵循 文档正确。我正在使用 Urlfetchapp 发布内容类型为 multipart/form-data 的有效负载。这里的服务参数只不过是带有所需身份验证标头的 urlfetchapp,可在 Oauth 1 库

在此处输入图像描述

/Twitter 文件上传 -初始化-->追加-->最终化/ initTwitterUpload 函数运行良好。服务参数是一个带有授权标头的 urlfetchapp,并与 oauth1 library(fetch)

我的 gs 文件中的其他函数:

function uploadTwitterMedia(mediaUrl){
    var file = DriveApp.getFileById(mediaUrl.replace("https://drive.google.com/open?id=",""))
    var initResponse = initTwitterUpload(mediaUrl,service)
    var appendResponse = appendTwitterUpload(file,initResponse,service)
    var finalizeResponse = finalizeTwitterUpload(initResponse,service)
    return initResponse["media_id_string"]
}

function initTwitterUpload(url,service){
  var file = DriveApp.getFileById(url.replace("https://drive.google.com/open?id=",""))
  var type = file.getMimeType()
  var size = file.getSize()
  var baseUrl =  "https://upload.twitter.com/1.1/media/upload.json?"
  var oauthParams = "command=INIT&total_bytes="+encodeURIComponent(size).replace(/\!/g, "%21")
  .replace(/\*/g, "%2A")
  .replace(/\'/g, "%27")
  .replace(/\(/g, "%28")
  .replace(/\)/g, "%29")+"&media_type="+encodeURIComponent(type).replace(/\!/g, "%21")
  .replace(/\*/g, "%2A")
  .replace(/\'/g, "%27")
  .replace(/\(/g, "%28")
  .replace(/\)/g, "%29")+"&media_category="+ Oauth1percentEncode("TWEET_IMAGE");
  var tweetUrl = baseUrl + oauthParams 
  var response = service.fetch(tweetUrl,{method:'POST'})
  return JSON.parse(response.getContentText())
}



function finalizeTwitterUpload(init,service){
  var baseUrl =  "https://upload.twitter.com/1.1/media/upload.json?"
  var params = "command=FINALIZE&media_id="+Oauth1percentEncode(init["media_id_string"])
  var tweetUrl = baseUrl + params 
  var response = service.fetch(tweetUrl,{method:'POST',
                                        muteHttpExceptions:true})
  return JSON.parse(response.getContentText())
}


function Oauth1percentEncode(text){
  text = encodeURIComponent(text).replace(/\!/g, "%21").replace(/\*/g, "%2A").replace(/\'/g, "%27")
  .replace(/\(/g, "%28");
  return text
}

此外,statusTwitterUpload 函数未按预期工作,它给出的响应为“找不到页面”。

In the below function, I got an error response from Twitter as "Bad request".

//param1 file === DriveApp.getFileById()
//param2 init === returned object of initTwitterUpload function
//param3 service === OAuth1.createService()
function appendTwitterUpload(file,init,service) {
  var blob = file.getBlob()
  var bytes = blob.getBytes()
  var base64Blob = Utilities.base64Encode(bytes)
  var metaData = {name: file.getName(),
    mimeType: file.getMimeType()}
  var baseUrl =  "https://upload.twitter.com/1.1/media/upload.json" //?command=APPEND&media_id=" 
    //Oauth1percentEncode(init["media_id_string"]) +  "&segment_index=" + Oauth1percentEncode(0);
  var options = {method:'POST',
                 contentType : 'multipart/form-data',
                 payload : {'command':'APPEND',
                            'media_id' : init["media_id"],
                            'segment_index': 0,
                           },
                 files:{'media': bytes},
                 muteHttpExceptions:true}
  var response = service.fetch(baseUrl,options);
  return JSON.parse(response.getContentText())
}

Any Twitter developer out there finding bugs, I have found one with Google apps script. I am using OAuth 1.0a authentication and following all the procedures mentioned in the documentation correctly. I am using Urlfetchapp for posting the payload with content-type of multipart/form-data. Service param here is nothing but urlfetchapp with required authentication headers that is available in Oauth 1 library

enter image description here

/Twitter file upload - init -->append -->finalize/
initTwitterUpload function is working perfectly. Service param is a urlfetchapp with authorization headers and matches with one of the functions in the oauth1 library(fetch)

Other functions in my gs file:

function uploadTwitterMedia(mediaUrl){
    var file = DriveApp.getFileById(mediaUrl.replace("https://drive.google.com/open?id=",""))
    var initResponse = initTwitterUpload(mediaUrl,service)
    var appendResponse = appendTwitterUpload(file,initResponse,service)
    var finalizeResponse = finalizeTwitterUpload(initResponse,service)
    return initResponse["media_id_string"]
}

function initTwitterUpload(url,service){
  var file = DriveApp.getFileById(url.replace("https://drive.google.com/open?id=",""))
  var type = file.getMimeType()
  var size = file.getSize()
  var baseUrl =  "https://upload.twitter.com/1.1/media/upload.json?"
  var oauthParams = "command=INIT&total_bytes="+encodeURIComponent(size).replace(/\!/g, "%21")
  .replace(/\*/g, "%2A")
  .replace(/\'/g, "%27")
  .replace(/\(/g, "%28")
  .replace(/\)/g, "%29")+"&media_type="+encodeURIComponent(type).replace(/\!/g, "%21")
  .replace(/\*/g, "%2A")
  .replace(/\'/g, "%27")
  .replace(/\(/g, "%28")
  .replace(/\)/g, "%29")+"&media_category="+ Oauth1percentEncode("TWEET_IMAGE");
  var tweetUrl = baseUrl + oauthParams 
  var response = service.fetch(tweetUrl,{method:'POST'})
  return JSON.parse(response.getContentText())
}



function finalizeTwitterUpload(init,service){
  var baseUrl =  "https://upload.twitter.com/1.1/media/upload.json?"
  var params = "command=FINALIZE&media_id="+Oauth1percentEncode(init["media_id_string"])
  var tweetUrl = baseUrl + params 
  var response = service.fetch(tweetUrl,{method:'POST',
                                        muteHttpExceptions:true})
  return JSON.parse(response.getContentText())
}


function Oauth1percentEncode(text){
  text = encodeURIComponent(text).replace(/\!/g, "%21").replace(/\*/g, "%2A").replace(/\'/g, "%27")
  .replace(/\(/g, "%28");
  return text
}

Also, the statusTwitterUpload function is not working as expected, it gives a response as "Page not found".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

流绪微梦 2025-01-23 15:43:58

我找到了答案。感谢我,用问题中的函数替换这个appendTwitterUpload函数,它会工作得很好。

function appendTwitterUpload(file,init,service) {
  var options = null
  var response = null
  var baseUrl = "https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id=" + init["media_id_string"] +
    "&segment_index=" + Oauth1percentEncode(0);
  var boundary = "xxxxxxxxxx";
  var data = "";
  data += "--" + boundary + "\r\n";
  data += "Content-Disposition: form-data; name=\"media\"; filename=\"" + file.getName() + "\"\r\n";
  data += "Content-Type:" + file.getMimeType() + "\r\n\r\n";

  var payload = Utilities.newBlob(data).getBytes()
  .concat(file.getBlob().getBytes())
  .concat(Utilities.newBlob("\r\n--" + boundary + "--").getBytes());
  
  var options = {
    method : "post",
    contentType : "multipart/form-data; boundary=" + boundary,
    payload : payload,
      muteHttpExceptions: true,
}
var response = service.fetch(baseUrl,options);
return response.getResponseCode()
}

I found an answer. Thanks to me, Replace this appendTwitterUpload function with the one in the question and it will work great.

function appendTwitterUpload(file,init,service) {
  var options = null
  var response = null
  var baseUrl = "https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id=" + init["media_id_string"] +
    "&segment_index=" + Oauth1percentEncode(0);
  var boundary = "xxxxxxxxxx";
  var data = "";
  data += "--" + boundary + "\r\n";
  data += "Content-Disposition: form-data; name=\"media\"; filename=\"" + file.getName() + "\"\r\n";
  data += "Content-Type:" + file.getMimeType() + "\r\n\r\n";

  var payload = Utilities.newBlob(data).getBytes()
  .concat(file.getBlob().getBytes())
  .concat(Utilities.newBlob("\r\n--" + boundary + "--").getBytes());
  
  var options = {
    method : "post",
    contentType : "multipart/form-data; boundary=" + boundary,
    payload : payload,
      muteHttpExceptions: true,
}
var response = service.fetch(baseUrl,options);
return response.getResponseCode()
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文