6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google SpreadsheetとCloud Functionsでランダムに出力するオミクジ的なサイトを作る

Last updated at Posted at 2018-09-22

Google Spreadsheetの値を他のアプリから扱えると何かと便利だが、URLがhttps://script.google.com/macros/s/{11文字+28文字+15文字}/execと、ちょっと使いにくいのでCloud Functionsと組み合わせて使いやすくしてみる。

SpreadSheetの値を取得する

まずスプレッドシートを作る。作ったスプレッドシートのURLに注目。IDの部分をコピペしておく。

https://docs.google.com/spreadsheets/d/{この部分がスプレッドシートのID}/edit#gid=0

ツールから「スクリプトエディタ」を開く。

スクリーンショット 2018-09-22 17.56.14.png

元の関数を消して下記のdoGet()をコピペ。ざっくり解説すると、getLastRow()で行数を取得し、ランダムに行を取得したものを出力している。別にランダムでなくてよければ、getRange(1,1)のように普通にセル指定して取得すればよい。

なお、元の「シート1」というシート名でエラーが起きてるようだったので「sheet1」とリネームしている。(これが原因だったか自信がないが・・・)

function doGet(){
  var spreadsheet = SpreadsheetApp.openById('{スプレッドシートのID}');
  var sheet = spreadsheet.getSheetByName('sheet1');
  var lastRow = sheet.getLastRow();
  var rand = Math.floor( Math.random() * lastRow ) + 1;

  var rowData = {};
  rowData.num = rand;
  rowData.value = sheet.getRange(rand,2).getValue();
  var result = JSON.stringify(rowData);
  return ContentService.createTextOutput(result);
}

コピペできたらスクリプトエディタから「ウェブアプリケーションとして導入」を選ぶ。

スクリーンショット 2018-09-22 17.57.22.png

「アプリケーションにアクセスできるユーザ」を全員にして「導入」ボタンを押す。

スクリーンショット 2018-09-22 17.57.47.png

この画面で「詳細」を押すと、アプリを許可する画面に進む。ここ、最初のうちは気づかなかった。

スクリーンショット 2018-09-22 18.04.52.png

こんな感じでURLが生成されたら成功。別のブラウザ(curlやChromeのプライベートブラウズなど)でアクセスして動作確認する。

スクリーンショット 2018-09-22 18.05.11.png

Cloud Functionsで値を取得・表示する

まずチュートリアルを参考に、helloGETできるところまで動作確認する。(プロジェクト作成から課金まで、意外にやることが多い)

helloGETが動いたら、Google Spreadsheetの値を取得するようindex.jsを書き換えてみる。

index.js
/**
 * HTTP Cloud Function.
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */

const request = require('request');

exports.content = (req, res) => {

  let url = 'https://script.googleusercontent.com/macros/echo?user_content_key=xx'
  request.get(url, function (error, response, body) {
    body = JSON.parse(body);
    let out = new String();
    out += body.value;
    res.status(200).send(out);
  });

};

requireはpackage.jsonに書かないと読み込んでくれないので、package.jsonもコピペ。

package.json
{
  "name": "test",
  "version": "0.0.1",
  "dependencies":{
    "request": "~2.88"
  }
}

チュートリアルで作ったhelloGETを削除して、新しく作ったcontentをデプロイする。

gcloud beta functions delete helloGET --trigger-http
gcloud beta functions deploy content --trigger-http

これでSpreadsheetの値をCloud Functionsで取得できる。めでたしめでたし。

ちなみにquote for TOEICという技術系の英文をランダムで表示するサイトも、こんな感じでサーバレスで動いてる。

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?