使用 Google Apps 脚本在 Blogger 中创建 post
Create a post in Blogger with Google Apps Script
到目前为止,我还没有找到使用 Google 脚本在 Blogger 中创建帖子的好代码。
在 API 控制台中,我获得了以下凭据:
- 客户编号
- 客户端密码
- API键
此外,库已添加到 Google 脚本中:
- OAuth2 库 → MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48
- 博主库 → M2CuWgtxF1cPLI9mdRG5_9sh00DPSBbB3
我尝试了一些代码,这是当前的代码:
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);}
}
请帮我用最简单的代码解决这个问题。
必读:
- ScriptApp#getOauthToken
- Blogger §post#insert
- UrlFetchApp#fetch
- Editing manifest#Setting explicit scopes
- Switch to standard GCP
- API Library
问题:
- 异步客户端浏览器样本在同步服务器端的使用。
解决方案:
- 可以使用
UrlFetchApp
从 Google 应用程序脚本访问 Blogger api
- 可以使用
ScriptApp
提供的 oauth 令牌绕过完整的 OAuth 流程
- 在 appsscript.json 清单文件中包含范围。
- 切换到标准 GCP 并启用博主 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"
]