Skip to content

Instantly share code, notes, and snippets.

@tai-sho
Created April 24, 2024 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tai-sho/d43be200d5a2e160c78a73f5bcfce646 to your computer and use it in GitHub Desktop.
Save tai-sho/d43be200d5a2e160c78a73f5bcfce646 to your computer and use it in GitHub Desktop.
webサイトのCO2消費量をスプレッドシート出力する。 API Doc: https://api.websitecarbon.com/
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