【AWS/Node.js】LINEのmessaging apiを使ってオーディエンスを作成/情報取得/削除する

もくじ

はじめに

LINEの特定のユーザへメッセージ配信したいとき、オーディエンスという集合体を作成することができます。 属性でなく、独自のユーザ群をまとめマーケティングしたい時などに活用できると思います。

ただ、messaging apiのドキュメントを見てもcurlコマンドしか記載がなかったため備忘録です。

公式ドキュメントに載っているcurlコマンドを実際にはaxiosしてオーディエンスを扱っています。変換には curlconverter を活用しました。

前提

下記は準備&登録済みとします。

LINEのChannel access tokenも確認しておいてください。

コード

オーディエンス作成

import axios from 'axios';

export default class LineMessagingApi {
  private channelAccessToken = 'xxxxx';  // channel access token

  public async createLineAudience(lineUserIds, audienceName) {  // lineUserIds は配列
    const requestBody = {
      'description': audienceName,
      'audiences': lineUserIds.map(
        item => ({
          'id': item
        })
      )
    };
    await axios.post(
      'https://api.line.me/v2/bot/audienceGroup/upload',
      requestBody,
      {
        headers: {
          'Authorization': `Bearer {'${this.channelAccessToken}'}`,
          'Content-Type': 'application/json'
        }
      }
    );
  }
};

オーディエンス情報取得

存在するオーディエンスの情報を取得します。

import axios from 'axios';

export default class LineMessagingApi {
  private channelAccessToken = 'xxxxx';  // channel access token

  public async getLineAudience(audienceId) { 
    try {
      const res = await axios.get(
        `https://api.line.me/v2/bot/audienceGroup/${audienceId}`,
        {
          headers: {
            'Authorization': `Bearer {${this.channelAccessToken}}`,
          }
        }
      );
      return res.data;
    } catch (e) {
      // audienceId が存在しないときは400エラーがレスポンスされる
      console.log(e.response.data.message);
    }
  }
};

オーディエンス削除

import axios from 'axios';

export default class LineMessagingApi {
  private channelAccessToken = 'xxxxx';  // channel access token

  public async deleteLineAudience(audienceId) {
    await axios.delete(
      `https://api.line.me/v2/bot/audienceGroup/${audienceId}`,
      {
        headers: {
          'Authorization': `Bearer {${this.channelAccessToken}}`,
        }
      }
    );
  }
};

それぞれtry catchやオーディエンス存在確認などは適宜加えてくださいね。

呼び出して使う

上記のクラスを呼び出して、好きなところで使ってください。

オーディエンスIDはLine official account managerホーム>データ管理>オーディエンスで詳細を開くと確認できます。

// オーディエンス作成
const lineUserIds = [
  'xxxxx', // lineUserId
  'yyyyy', // lineUserId
  'zzzzz'  // lineUserId
];
const audienceName = 'sample_audience';

// オーディエンス作成
new LineMessagingApi().createLineAudience(lineUserIds, audienceName);

// オーディエンス情報取得
const audienceId = 0123456789012;
await LineMessagingApi.getLineAudience(audienceId);

// オーディエンス削除
const audienceId = 0123456789012;
await LineMessagingApi.deleteLineAudience(audienceId);

参考

Messaging APIリファレンス | LINE Developers

Convert curl commands to code