Google Apps Script
自分用のメモ。あまり参考にはならないかも
めちゃんこ工事中
GASをローカル環境で開発するための環境構築
GoogleAppsScript(GAS)をローカル開発するためのツールの使い方
日付のフォーマット
formatDate(date, timeZone, format)
// This formats the date as Greenwich Mean Time in the format
// year-month-dateThour-minute-second.
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
Logger.log(formattedDate);
Typetalkのbotを作成する
自動投稿とか。HTTPリクエスト。
UrlFetchApp.fetch(url, params)
// Make a POST request with a JSON payload.
var data = {
'name': 'Bob Smith',
'age': 35,
'pets': ['fido', 'fluffy']
};
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
UrlFetchApp.fetch('https://httpbin.org/post', options);
ペイロードっちゅうのはデータの正味部分みたいな意味。
JSONの変換
(GASっていうよりjavascript組み込み)
JSON.parse(text[, reviver])
function replacer(key, value) {
// Filtering out properties
if (typeof value === 'string') {
return undefined;
}
return value;
}
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
値をJSON化。reviverは関数。オブジェクトを返す前に全てのプロパティに対して処理してくれる。
JSON.stringify(value[, replacer[, space]])
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', "week" と "month" プロパティだけが保持される
JSONを文字列化。replacerは関数or配列。関数の返した値で、キーの値が上書きされる。配列のときは、そのキー以外は捨てられる。
スクリプトプロパティ
AfterEffectsのスクリプトでは、環境設定にスクリプトで使用するデータを保存し、次回起動時に設定を読み込みが出来るが、それと同じようなことが、GASでも出来る。「キー名」と「値」のセットで扱い、全て文字列データでの保存。その点もAEと同じ扱い方なのでとっつきやすい。。
var props = PropertiesService.getScriptProperties();
props.getProperty("キー名");
「ファイル」→「プロジェクトのプロパティ」→「スクリプトのプロパティ」で手動設定も出来る。
V8ランタイムに対応した記念
ラムダ式
var varLambda = () => {}
let letLambda = () => {}
const constLambda = () => {}
var varAsyncLambda = async () => {}
let letAsyncLambda = async () => {}
const constAsyncLambda = async () => {}
letとconst
ブロクスコープでの変数宣言が可能
// V8 runtime
let s = "hello";
if (s === "hello") {
let s = "world";
console.log(s); // Prints "world"
}
console.log(s); // Prints "hello"
const N = 100;
N = 5; // Results in TypeError
アロー関数
// Rhino runtime
function square(x) {
return x * x;
}
console.log(square(5)); // Outputs 25
// V8 runtime
const square = x => x * x;
console.log(square(5)); // Outputs 25
// Outputs [1, 4, 9]
console.log([1, 2, 3].map(x => x * x));
クラス
おれぁ、未だにクラスのありがたみが理解できねぇんだ...。
// V8 runtime
class Rectangle {
constructor(width, height) { // class constructor
this.width = width;
this.height = height;
}
logToConsole() { // class method
console.log(`Rectangle(width=${this.width}, height=${this.height})`);
}
}
const r = new Rectangle(10, 20);
r.logToConsole(); // Outputs Rectangle(width=10, height=20)
分割代入
配列、オブジェクトの中身を取り出してそれぞれ変数に入れる。
// Rhino runtime
var data = {a: 12, b: false, c: 'blue'};
var a = data.a;
var c = data.c;
console.log(a, c); // Outputs 12 "blue"
var array = [1, 2, 3];
var x = a[0];
var y = a[1];
var z = a[2];
console.log(x, y, z); // Outputs 1 2 3
// V8 runtime
var data = {a: 12, b: false, c: 'blue'};
var {a, c} = data;
console.log(a, c); // Outputs 12 "blue"
var array = [1, 2, 3];
var [x, y, z] = array;
console.log(x, y, z); // Outputs 1 2 3
テンプレート文字列
文字列を括るのに「`」(Shift+@)を使用することで、文字列の中に変数を使いたい時、連結が楽になる
// Rhino runtime
var name =
'Hi ' + first + ' ' + last + '.';
var url =
'http://localhost:3000/api/messages/'
+ id;
// V8 runtime
var name = `Hi ${first} ${last}.`;
var url = `http://localhost:3000/api/messages/${id}`;
また、複数行の文字列も、改行直前で\nなど書かなくてもいい。
// Rhino runtime
var multiline = "This string is sort of\n"
+ "like a multi-line string,\n"
+ "but it's not really one.";
// V8 runtime
var multiline = `This on the other hand,
actually is a multi-line string,
thanks to JavaScript ES6`;
デフォルト引数
引数を与えなかったときの初期値を設定しておける。今までだと関数の中で引数の値がundefinedの時は代入、などしないといけなかった。
// Rhino runtime
function hello(greeting, name) {
greeting = greeting || "hello";
name = name || "world";
console.log(
greeting + " " + name + "!");
}
hello(); // Outputs "hello world!"
// V8 runtime
var hello =
function(greeting="hello", name="world") {
console.log(
greeting + " " + name + "!");
}
hello(); // Outputs "hello world!"
コンテナバインドのスクリプトから、コンテナ(親)を取得
SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.getActivesheet();
VBAからpsotされたデータをスプレッドシートに書く
スプレッドシートでセルの選択が変わったときに自動で実行
onSelectionChange(e)を使う。
eの中身はこんな感じ
{
"authMode":"LIMITED",
"range":{
"columnEnd":1,
"columnStart":1,
"rowEnd":1,
"rowStart":1
},
"source":{},
"user":{
"email":"",
"nickname":""
}
}
e.rangeはそのままRangeオブジェクトとして使えるみたい?ここには出てないけどメソッドも持ってるから、公式ガイド見たほうがいい。