Create a post in Blogger with Google Apps Script

a 夏天 提交于 2019-12-20 07:06:15

问题


So far I haven't found a good code to create posts in Blogger with Google Script.

In the API Console I got the following credentials:

  • Client ID
  • Client Secret
  • API key

Also, libraries were added to the Google Script:

  • OAuth2 library → MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48
  • Blogger library → M2CuWgtxF1cPLI9mdRG5_9sh00DPSBbB3

I tried some codes, and this is the current one:

function create_post_blog_2() {
//<script src="https://apis.google.com/js/api.js"></script>
//<script>
  /**
   * Sample JavaScript code for blogger.posts.insert
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/guides/code_samples#javascript
   */
  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/blogger"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("AIzaSyC............."); // ¶ YOUR_API_KEY
    return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/blogger/v3/rest")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.blogger.posts.insert({
      "blogId": "12345..............", // ← Blog ID
      "fetchBody": true,
      "isDraft": false,
      "resource": {
        "content": "aaaaa", // ← new post contents
        "title": "bbbbb" // ← new post contents
      }
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "10984237..................."}); // ¶¶¶¶¶ YOUR_CLIENT_ID
  });
//</script>
//<button onclick="authenticate().then(loadClient)">authorize and load</button>
//<button onclick="execute()">execute</button>
}

AND the error message is ReferenceError: "gapi" is not defined. (line 40, file "crear_post_blog_2"). I took it from https://developers.google.com/blogger/docs/3.0/reference/posts/insert?apix=true#try-it and it worked fine when I filled out the parameters there, but not when running the code in Google Apps Script.

Acording to APIs documentation → «This error occurs when your JavaScript code tries to call the Google API Client Library for JavaScript before the library has actually loaded. Make sure that your code that references the gapi variable is not called until after the client library has loaded.» I don't know how to do that.

Please help me solve this with the simplest code possible and/or provide the necessary steps for good achievement.

Thanks a lot.


回答1:


Required reading:

  • ScriptApp#getOauthToken
  • Blogger §post#insert
  • UrlFetchApp#fetch
  • Editing manifest#Setting explicit scopes
  • Switch to standard GCP
  • API Library

Issue:

  • Usage of asynchronous client side browser samples in the synchronous server side.

Solution:

  • It is possible to access Blogger api from Google apps script using UrlFetchApp
  • Full OAuth flow can be bypassed using oauth token provided by ScriptApp
  • Include scopes in the appsscript.json manifest file.
  • Switch to a standard GCP and enable the blogger api

Snippet:

function createBlogPost(){
  var postUrl = "https://www.googleapis.com/blogger/v3/blogs/blogId/posts";
  var blogId = /*"YOUR_BLOG_ID"*/;
  postUrl = postUrl.replace("blogId",blogId);
  var options = {
    method:"post",
    contentType:"application/json",
    headers: { Authorization: "Bearer "+ ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
    payload: JSON.stringify({
      title: "Hello from Apps Script!",
      content: "This post is automatically created by Apps script"
    })
  }
  var res = UrlFetchApp.fetch(postUrl, options).getContentText();
  console.log(res);//or Logger.log(res)
}

Manifest scopes:

"oauthScopes": [
  "https://www.googleapis.com/auth/blogger",
  "https://www.googleapis.com/auth/script.external_request"
]


来源:https://stackoverflow.com/questions/57979124/create-a-post-in-blogger-with-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!