7
5

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 3 years have passed since last update.

GASでごはんのアイデアを送ってくれるBotを作成してみた。

Posted at

どうも、Pythonを主軸に開発を行っている学生エンジニアのirohasです。
今回は最近話題のGAS(GoogleAppsScript)を使用したLineBotを作ってみました。

使用したもの
・GAS(GoogleAppsScript)
・LINE Developers
・スプレッドシート

コードは下記の通りです。

gohan.gs
// LINE Developerのアクセストークン
var access_token = "YOUR ACCESS TOKEN"
// リプライ先を特定するためのログ管理スプレッドシートID
var spreadsheet_id = "YOUR SPREADSHEET ID"
// ご飯リストのスプレッドシートID
var gohan_spreadsheet_id = "YOUR SPREADSHEET ID"

/**
 reply
 */
function reply(data) {
  var url = "https://api.line.me/v2/bot/message/reply";
  var headers = {
    "Content-Type" : "application/json; charset=UTF-8",
    'Authorization': 'Bearer ' + access_token,
  };
  var text = "";
  
  if (data.events[0].message.text === "ご飯","ごはん","gohan","dinner","Dinner","Lunch","lunch","breakfast","BreakFast","Morning","morning") {
    // ご飯リストスプレッドシートを取得
    var gohan = SpreadsheetApp.openById(gohan_spreadsheet_id).getSheetByName("log");
    // A1セルから入力されている最終行まで一気に取得
    var gohanData = gohan.getRange(1, 1, gohan.getLastRow());
    // ランダムで候補を選ぶ
    var intRandomNum = Math.round(Math.random()*gohan.getLastRow());
    
    text = gohanData.getValues()[intRandomNum][0];
  }
  else {
    text = "「ご飯」って話しかけてね。"
  }

  var postData = {
      "replyToken" : data.events[0].replyToken,
      "messages" : [
        {
          'type':'text',
          'text':text + "はどうかな~",
        }
      ]
    };

  var options = {
    "method" : "post",
    "headers" : headers,
    "payload" : JSON.stringify(postData)
  };

  return UrlFetchApp.fetch(url, options);
}

/**
 LINEからのPOST受け取り
 */
function doPost(e) {
  var json = JSON.parse(e.postData.contents);
  var data = SpreadsheetApp.openById(spreadsheet_id).getSheetByName('log').getRange(1, 1).setValue(json.events);

  reply(json);
}

ごはんのスプレッドシートは各自で作成し、好きな食べ物を格納していってください。
スプレッドシートIDは各々のスプレッドシートのURLを見て、"https://docs.google.com/spreadsheets/d/SPREADSHEET ID/edit#gid=0"の太字の部分をコピペして貼り付けてください。

・実行結果

image0 (2).png

コードの19行目にて、BOTが反応するキーワードを複数用意したのでこのようにいろいろなキーワードに反応し、応答してくれます。
キーワードはいくつ作っても大丈夫なので好きなキーワードを入れて作成しましょう!

・最後に

GASで開発するのはまだ数回程度しか経験がありませんが、かなり便利だなという印象を持っています。
なによりLINEとの連携がすごく楽なのが魅力的ですよね!!!!
ニュースや天気予報など様々な分野を混ぜてマルチなBOTも作ることが出来そうなので次はそこらへんにもチャレンジしたいと思います!!!!

7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?