Created
April 24, 2024 05:19
-
-
Save tai-sho/d43be200d5a2e160c78a73f5bcfce646 to your computer and use it in GitHub Desktop.
webサイトのCO2消費量をスプレッドシート出力する。 API Doc: https://api.websitecarbon.com/
This file contains 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
const TARGET_URL = 'https://example.com'; | |
const CARBON_API_URL = `https://api.websitecarbon.com/site?url=${TARGET_URL}`; | |
/** | |
* APIからデータを取得し、スプレッドシートに記録する | |
*/ | |
function main() { | |
const response = callApi(CARBON_API_URL); | |
if (response !== null) { | |
writeToSpreadsheet(response); | |
} | |
} | |
/** | |
* 指定されたURLからAPIを呼び出し、レスポンスデータを取得する | |
* @param {string} url - APIのURL | |
* @return {Object} APIレスポンス | |
*/ | |
function callApi(url) { | |
const response = UrlFetchApp.fetch(url, { | |
muteHttpExceptions: true | |
}); | |
const statusCode = response.getResponseCode; | |
const data = JSON.parse(response.getContentText()); | |
if ('error' in data || statusCode < 200 || 300 <= statusCode) { | |
console.warn(data.error); | |
return null; | |
} | |
return data; | |
} | |
/** | |
* 取得したデータをスプレッドシートに記録する | |
* @param {Object} data - APIから取得したデータ | |
*/ | |
function writeToSpreadsheet(data) { | |
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('index'); | |
const timestamp = new Date(data.timestamp * 1000); | |
console.log(data) | |
// スプレッドシートに書き込む行のデータ | |
const rowData = [ | |
timestamp, | |
data.url, | |
data.green, | |
data.bytes, | |
data.cleanerThan, | |
data.rating, | |
data.statistics.adjustedBytes, | |
data.statistics.energy, | |
data.statistics.co2.grid.grams, | |
data.statistics.co2.grid.litres, | |
data.statistics.co2.renewable.grams, | |
data.statistics.co2.renewable.litres | |
]; | |
sheet.appendRow(rowData); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment