LoginSignup
6

More than 5 years have passed since last update.

LINEAPIとGASを使って遊んでみた

Last updated at Posted at 2018-08-13

雑文メーカー

自分がLINEで送信した内容がGSSのA列に一行ずつ入力されていく。

雑文メーカー.gs
// シートを取得
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("シート1"); // 「シート1」はシート名

//使用する変数を設定
var PROPERTIES = PropertiesService.getScriptProperties();
var LINE_ACCESS_TOKEN = PROPERTIES.getProperty('LINE_ACCESS_TOKEN')
var LINE_END_POINT = "https://api.line.me/v2/bot/message/reply"
var reply_token;
var query;

function doPost(e){
if (typeof e === "undefined"){
 reply_token = ""
 query = "本"
} else{
  var json = JSON.parse(e.postData.contents);
  reply_token= json.events[0].replyToken;
  //送られたLINEメッセージを取得
  query = json.events[0].message.text;
}
  Logger.log("検索キーワード"+query);
 writeGss(query);
 postBackToLine();
}

//GSSに受け取った内容を書き込む(A列の書き込みがされているセルの一つ下のセルに書き込む)
function writeGss(query){
  var values = sheet.getRange("A:A").getValues();
  for (var i = values.length - 1; i >= 0; i--) {
    if (values[i] != "") {
      break;
    }
  }
  var last_row = i + 2;
  sheet.getRange("A"+last_row).setValue(query);
}

//LINEに「書きこんだぜ!」と返事をする。
function postBackToLine(){
var messages = [{
 "type": "text",
 "text": "書きこんだぜ!"
}];
Logger.log(messages)
UrlFetchApp.fetch(LINE_END_POINT, {
 'headers': {
   'Content-Type': 'application/json; charset=UTF-8',
   'Authorization': 'Bearer ' + LINE_ACCESS_TOKEN,
 },
 'method': 'post',
 'payload': JSON.stringify({
   'replyToken': reply_token,
   'messages': messages,
 }),
});   
}

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