使用 Google Apps 脚本在 Blogger 中创建帖子 [英] Create a post in Blogger with Google Apps Script

查看:23
本文介绍了使用 Google Apps 脚本在 Blogger 中创建帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我还没有找到使用 Google Script 在 Blogger 中创建帖子的好代码.

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

在 API 控制台中,我获得了以下凭据:

In the API Console I got the following credentials:

  • 客户 ID
  • 客户机密
  • API 密钥

此外,库已添加到 Google 脚本中:

Also, libraries were added to the Google Script:

  • OAuth2 库 → MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48
  • 博主库 → M2CuWgtxF1cPLI9mdRG5_9sh00DPSBbB3

我尝试了一些代码,这是当前的代码:

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

function create_blog_post() {
  var payload =
      {
        "kind": "blogger#post",
        "blog": {
          "id": "12345........" // YOUR_BLOG_ID
        },
        "title": "New post",
        "content": "With content..."
      };
var headers = {
    "Authorization": "Bearer " + getService().getAccessToken(), // ← THIS IS WRONG
    "X-HTTP-Method-Override": "PATCH"
  };
  var options =
      {
        "method" : "post",
        "headers" : { "Authorization" : "Bearer" + getService().getAccessToken()},
        "contentType" : "application/json",
        "payload" : '{ "kind": "blogger#post", "blog": { "id": "12345........" }, "title": "New post", "content": "With content..." }'
      };
  try {
    var result = UrlFetchApp.fetch(
      "https://www.googleapis.com/blogger/v3/blogs/12345......../posts", options);
    Logger.log(result);
    } catch (e) {Logger.log(e);}
}

请用最简单的代码帮我解决这个问题.

Please help me solve this with the simplest code possible.

推荐答案

必读:

  • ScriptApp#getOauthToken莉>
  • 博主 §post#insert
  • UrlFetchApp#fetch
  • 编辑清单#设置显式范围
  • 切换到标准 GCP
  • API 库
    • 异步客户端浏览器示例在同步服务器端的使用.
    • 可以使用 UrlFetchApp
    • 从 Google 应用程序脚本访问 Blogger api
    • 可以使用 ScriptApp
    • 提供的 oauth 令牌绕过完整的 OAuth 流程
    • 在 appsscript.json 清单文件中包含范围.
    • 切换到标准 GCP 并启用 Blogger api
    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)
    }
    

    清单范围:

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

    这篇关于使用 Google Apps 脚本在 Blogger 中创建帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆