5
4

More than 1 year has passed since last update.

【LINE Messaging API, GAS】友だち追加時にスプレッドシートにユーザIDを記録

Last updated at Posted at 2022-04-08

フォローイベントとは

LINE公式アカウントが友だち追加またはブロック解除されたことを示すイベントです。フォローイベントには応答できます。(Messaging APIリファレンスより)

フォローイベントを取得

コード.gs
function doPost(e){
  const events = JSON.parse(e.postData.contents).events;
  for (var i = 0; i < events.length; i++){
    execute(events[i]);
  }
}

function execute(event){
  const eventType = event.type;
  const replyToken = event.replyToken;
  const userId = event.source.userId;

  if(eventType === "follow"){
    // スプレッドシートにユーザIDを書き込む
  }
}
【参考】フォローイベントのJSONコード例

Messaging APIリファレンス #フォローイベントより

JSON
{
  "destination": "xxxxxxxxxx",
  "events": [
    {
      "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
      "type": "follow",
      "mode": "active",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U4af4980629..."
      }
    }
  ]
}
【参考】メッセージイベントのJSONコード例

Messaging APIリファレンス #メッセージイベントより

JSON
{
  "destination": "xxxxxxxxxx",
  "events": [
    {
      "replyToken": "nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
      "type": "message",
      "mode": "active",
      "timestamp": 1462629479859,
      "source": {
        "type": "user",
        "userId": "U4af4980629..."
      },
      "message": {
        "id": "325708",
        "type": "text",
        "text": "@example Hello, world! (love)",
        "emojis": [
          {
            "index": 14,
            "length": 6,
            "productId": "5ac1bfd5040ab15980c9b435",
            "emojiId": "001"
          }
        ],
        "mention": {
          "mentionees": [
            {
              "index": 0,
              "length": 8,
              "userId": "U850014438e..."
            }
          ]
        }
      }
    }
  ]
}

スプレッドシートの操作

gs
const sheetId = "シートID";

var data = SpreadsheetApp.openById(sheetId).getSheets[0];  // シートを取得
var lastRow = data.getLastRow();  // 最終行を取得
data.getRange(lastRow+1,1).setValue(userId);  // A列目にユーザID記入
data.getDataRange().removeDuplicates([1]);  // ユーザIDの重複を削除
  • シートID
    スプレッドシートのリンクから取得
    https://docs.google.com/spreadsheets/d/[sheetId]/edit
  • getRange(row, column)
    行と列を指定してセル範囲を取得(引用元
  • getDataRange()
    そのシート上の値が存在するセル範囲を取得(引用元
  • removeDuplicates(columnsToCompare)
    指定された列の値のうち、前の行と重複する値を含む、この範囲内の行を削除(引用元

getRange(row, column) において(1行, A列)の指定は getRange(1, 1) とする。

参考

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