### LINE Message APIとGoogle Apps Scriptで毎朝おはよーしてくれる奴
LINE Message APIとGoogle Apps Scriptで毎朝おはよーしてくれる奴
Message APIのセットアップはいろんなサイトで詳しく書いてあるので割愛してGoogle Apps Script (以下GAS)側だけ記載 GASはログ周りが使いにくいのでGoogle Document上にログを出力するオブジェクトの作成
var LOGGER = function (TAG) { const self = this; const fileId = 'Google DocumentのID'; const file = DocumentApp.openById(fileId); const body = file.getBody(); const tag = TAG; const levels = 'newidv'; this.level = 3; const put = function (level, object) { if (self.level < levels.indexOf(level)) return; const text = typeof object === 'string' ? object : JSON.stringify(object); const datetime = JSON.stringify(new Date()).substring(1, 20); body.appendParagraph('[' + datetime + '] (' + tag + ') ' + level.toUpperCase() + ': ' + text); }; [].map.call(levels, function (level) { self[level] = function (object) { return put(arguments.callee.level, object); }; self[level].level = level; }); };
ほんとはLoggerとしたかったんだが、名前がかぶるので、とりあえず大文字で妥協。 ちなみにconst LOGGER = ほにゃららとすると、エラーで動かない。GASのスコープと初期化のタイミングの問題?
LOGGERオブジェクトは以下のように使える
const log = new LOGGER('Main process'); log.i('処理開始します。'); log.e('エラーです。');
本題、LINEでメッセージのパース、送信をするオブジェクトの作成
var Line = function () { const log = new LOGGER('LINE'); log.v('Create Line Object'); const self = this; const ACCESS_TOKEN = 'アクセストークン'; const OWNER = '自分のID'; self.Info = function (userId) { const url = 'https://api.line.me/v2/bot/profile/' + userId; const response = UrlFetchApp.fetch(url, { headers: { Authorization: 'Bearer ' + ACCESS_TOKEN } }); log.v('Info: ' + JSON.stringify(response)); const responseContent = response.getContentText(); log.v('Info: ' + JSON.stringify(responseContent)); return JSON.parse(responseContent); }; self.Parse = function (contents) { log.v('Parse-Start;'); return contents.events.map(function (lineEvent) { log.v('Parse: ' + JSON.stringify(lineEvent)); const token = lineEvent.replyToken; if (typeof token === 'undefined') return undefined; const message = lineEvent.message.text; const id = lineEvent.source.userId; const name = self.Info(id).displayName; return { message: message, id: id, name: name, token: token }; }).filter(function (x) { return x; }); }; self.Send = function (message, reply) { log.v('Send: ' + message + ' -> ' + (reply ? reply : 'Owner')); const url = 'https://api.line.me/v2/bot/message/' + (reply ? 'reply' : 'push'); const payload = { messages: ( message instanceof Array ? message.filter(function (v, i, a) { return i < 5;}) : [message] ).map(function (text) { return { type: 'text', text: text}}) }; if (reply) payload.replyToken = reply; else payload.to = OWNER; return response = UrlFetchApp.fetch(url, { headers: { 'Content-Type': 'application/json; charset=UTF-8', Authorization: 'Bearer ' + ACCESS_TOKEN, }, method: 'post', payload: JSON.stringify(payload), }); }; self.get = function (url) { return response = UrlFetchApp.fetch(url, { headers: { Authorization: 'Bearer ' + ACCESS_TOKEN }, method: 'get', }); }; };
単純にテキストメッセージを送るときはこう
const line = new Line(); line.Send('おはよー');
これを適当な関数に突っ込んでトリガー設定しておしまい。 毎朝「おはよー」ってLINEでメッセージが届く生活が体験できる。