2
0

Google App ScriptとLINEbotでテキストとスタンプを同時に送りたい

Posted at

Google App ScriptとLINEbotを使って旅行までのカウントダウンや旅行当日の天気予報をメッセージとして送れるようにしたが、メッセージだけではやはり寂しいのでメッセージと同時にLINEスタンプを送れるようにしました。

//LINEbotを作成し、APIキーを下の'YOUR_LINE_ACCESS_TOKEN'に入れてください
const LINE_ACCESS_TOKEN = 'YOUR_LINE_ACCESS_TOKEN';


// スタンプパッケージIDとスタンプIDのリスト
const STAMP_PACKAGE_ID = 1070;
const STAMP_IDS = Array.from({length: 17878 - 17839 + 1}, (v, k) => k + 17839);

/**
 * ランダムなスタンプとテキストメッセージを送信する関数
 * @param {string} text - 送信するテキストメッセージ
 */


function sendRandomStampWithText(text) {
  // スタンプIDをランダムに選択
  const randomStampId = STAMP_IDS[Math.floor(Math.random() * STAMP_IDS.length)];
  
  // LINE Messaging APIのエンドポイントURL
  const url = 'https://api.line.me/v2/bot/message/broadcast';

  // 送信するメッセージデータ
  const messageData = {
    
    messages: [
      {
        type: 'text',
        text: text
      },
      {
        type: 'sticker',
        packageId: STAMP_PACKAGE_ID.toString(),
        stickerId: randomStampId.toString()
      }
    ]
  };

  // HTTPリクエストのオプション
  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      'Authorization': 'Bearer ' + LINE_ACCESS_TOKEN
    },
    payload: JSON.stringify(messageData)
  };

  // HTTPリクエストを送信
  const response = UrlFetchApp.fetch(url, options);
  
  // レスポンスをログに表示
  Logger.log(response.getContentText());
}

ここでは、sendRandomStampWithText()を実行する際、引数に送信したいLINEのメッセージ内容をもたせることでそのLINEの内容と私の気に入ったLINEスタンプの中からスタンプが一つランダムに送られるというものになっています。

image.png

気に入ったと言っても上記のパッケージIDが1070の中のスタンプが送られるというものです。

他のが良ければ、簡単に変えられるのでぜひ変えてみてください。

また、もっとこうしたほうがわかりやすいとか動作が早いという案があれば教えていただきたいです。

それでは、以上!

2
0
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
2
0