Last active
July 21, 2022 05:28
-
-
Save kn1cht/3228bacd8c35fa30675b7df226afc0ef to your computer and use it in GitHub Desktop.
new-page.gs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var properties = PropertiesService.getScriptProperties(); | |
// Scrapbox settings | |
var sid = properties.getProperty('SCRAPBOX_SID'); | |
var projectName = properties.getProperty('SCRAPBOX_PROJECT'); | |
// Slack settings | |
var webHookUrl = properties.getProperty('SLACK_WEBHOOK_URL'); | |
// JSON data settings | |
var jsonName = 'scrapbox-titles.json'; | |
function doPost(e) { | |
var attachment = JSON.parse(e.postData.getDataAsString()).attachments[0]; | |
var titles = JSON.parse(getJsonFileFromDrive(jsonName).getBlob().getDataAsString() || '[]'); | |
if(titles.length === 0) // fetch the list of the page titles | |
titles = getPageListFromApi().pages.map(function(p){ return p.title; }); | |
console.log(attachment.title); | |
if(titles.indexOf(attachment.title) === -1) { // New page! | |
titles.push(attachment.title); | |
var message = projectName + 'に記事"' + attachment.title + '"が作成されました'; | |
console.log(message); | |
UrlFetchApp.fetch(webHookUrl, options(message, attachment)); | |
} | |
getJsonFileFromDrive(jsonName).setContent(JSON.stringify(titles)); | |
} | |
function options(message, attachment) { | |
return { | |
method : 'post', | |
contentType : 'application/json', | |
payload : JSON.stringify({ | |
username : 'Scrapbox', | |
icon_emoji : ':scrapbox:', | |
text : message, | |
attachments : [attachment] | |
}) | |
}; | |
} | |
function getPageListFromApi() { | |
var headers = { 'Cookie' : 'connect.sid=' + sid }; | |
var response = UrlFetchApp.fetch('https://scrapbox.io/api/pages/' + projectName + '?limit=1000', { | |
method : 'get', | |
headers : headers | |
}); | |
return JSON.parse(response); | |
} | |
function getJsonFileFromDrive(name) { | |
var files = DriveApp.searchFiles('title = "' + name + '"'); | |
if (files.hasNext()) return files.next(); | |
return DriveApp.createFile(name, ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment