Skip to content

Instantly share code, notes, and snippets.

@AWtnb
Last active June 2, 2019 14:10
Show Gist options
  • Select an option

  • Save AWtnb/d2e48c67195947bd3d01a4ed33cd8ba6 to your computer and use it in GitHub Desktop.

Select an option

Save AWtnb/d2e48c67195947bd3d01a4ed33cd8ba6 to your computer and use it in GitHub Desktop.
reading log from slack
/*
読書記録用
*/
// ISBN 12桁の末尾にからチェックディジットを追加する関数
function appendCheckDigit (isbn12) {
var array = String(isbn12).split("")
var total = 0;
// 奇数桁
for (var i = 0; i <= 10; i += 2) {
total += Number(array[i])
}
// 偶数桁
for (var j = 1; j <= 11; j += 2) {
total += Number(array[j]) * 3
}
var checkD = ((10 - (total % 10))) % 10
return String(isbn12) + String(checkD);
}
// ISBN から書誌情報を取得する関数
function getInfoByISBN (ISBN) {
if (String(ISBN).length < 13) {
return false;
}
// openBD API で取得できなかった場合は google books API を使用。それでも取得できなかった場合は false を返す。
var url = "https://api.openbd.jp/v1/get?isbn=" + ISBN;
var res = UrlFetchApp.fetch(url);
if (res != "[null]") {
var json = JSON.parse(res);
var summary = json[0].summary;
var title = summary.title;
var authors = summary.author;
authors = authors.replace(//(著|翻訳|編集)/g, "");
}
else {
var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + ISBN + "&country=JP";
var res = UrlFetchApp.fetch(url);
var json = JSON.parse(res);
if (json.totalItems < 1) {
return false;
}
var title = json.items[0].volumeInfo.title;
var authors = json.items[0].volumeInfo.authors;
authors = authors.join(" ");
}
return [title, authors];
}
// slack slash command に応答する関数
function doPost (e) {
var SHEET_ID = PropertiesService.getScriptProperties().getProperty("SHEET_ID");
var ss = SpreadsheetApp.openById(SHEET_ID);
var sht = ss.getSheets();
// 投稿内容から書誌情報を取得
var text = e.parameter.text;
var params = text.split(/\s+/);
// ISBN 取得
var ISBN = params[0];
if (String(ISBN).length == 12) {
ISBN = appendCheckDigit(ISBN);
}
var info = getInfoByISBN(ISBN);
if (info) {
var res = {
text: "読んだ本に登録!\n" + "_『" + info[0] + "』" + "(" + info[1] + ")_",
response_type: "in_channel"
}
// シートに登録
var newLine = [ISBN, info[0], info[1], new Date()];
if (params.length > 1) {
newLine.push(params[1]);
}
sht[0].appendRow(newLine);
}
else {
var res = {
text: "ISBN では見つけられませんでした。手動で登録してください……",
response_type: "in_channel"
}
}
return ContentService.createTextOutput(JSON.stringify(res)).setMimeType(ContentService.MimeType.JSON);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment