SYSTEM NOTICE

Auto translation by AI. Be sure, accuracy, nuances and authorial intent may not be fully reflected.
見出し画像

Advanced Parenting Tech: Managing Children's Lesson Notifications with Google Apps Script & LINE Official Account (2025 ver.)

When I previously wrote an article to help solve the struggles of parenting generations, I received an unexpected response. I introduced a way to consolidate scattered information, such as notifications for children's lesson check-ins/check-outs and school gate pass-throughs, into a single LINE account, and that article was actually selected as one of the most read articles of the week on note.

It also achieved 560,000 views on X!


I received comments from many people saying, "I set it up!" and "This is so helpful!", which made me realize that many parents face similar challenges.

However, there was an announcement that LINE Notify will end its service on March 31, 2025 . The official announcement (https://notify-bot.line.me/closing-announce) suggested considering the use of the LINE Official Account Messaging API.

https://notify-bot.line.me/closing-announce

In this article, I will explain in detail the migration procedure from the soon-to-be-discontinued LINE Notify to a LINE Official Account, including screenshots. Please stay with me until the end!

For those who read the previous article but were still hesitant to set it up, why not take this opportunity to give it a try? Let's make family communication even smoother with a more convenient and reliable notification system!


Get children's check-in/check-out notifications on LINE!
A smooth method for migrating to the new API following the end of LINE Notify

Overall Flow

  1. Creating a LINE Official Account

  2. Settings in the LINE Developers Console

  3. Notification settings in Google Apps Script

  4. GAS deployment and Webhook settings

  5. Trigger settings

Now, let's proceed in order.



Step 1: Creating a LINE Official Account

First, create an account in the LINE Official Account Manager.

1. Account Creation


LINE Official Account Manager and log in. Let's create a new account here. For personal use, it is fine to select "Individual" as the industry.

2. Consent Confirmation


A screen asking for consent to the Terms of Service will appear; review the content and agree. This completes the creation of your LINE Official Account.

And with that, the creation of your LINE Official Account is complete!

Step 2: Configuration in the LINE Developers Console

Next, we will configure the Messaging API using the LINE Developers Console.

1. Account Preparation

Scan the QR code of the LINE Official Account you just created with your smartphone and add it as a friend in the LINE app. This will allow you to receive notifications from LINE later.

2. Accessing the LINE Developers Console

(1) Access the LINE Developers Console

Next, we will issue a channel access token. Open "Settings" in the top right, select "Messaging API," and click "Use Messaging API."

Open "Settings" in the top right.


Next, click on LINE Developers.

Open the LINE Developers console.

(2) Select Provider
A list of providers will be displayed. Select the provider you created earlier. This provider is linked to your LINE Official Account.

3. Issuing a Channel Access Token

This is an important step. The channel access token is required when using the LINE Messaging API from GAS or other programs.

(1) Open Messaging API Settings
Once you have navigated to the channel details page, click on the "Messaging API" tab.

(2) Issue Channel Access Token
Look for the item labeled "Channel access token (long-lived)."
Click the "Issue" button next to this item.
The issued token is required when using the API from programs like GAS, so be sure to copy and save it in a notepad or a secure location.
Caution: This token is highly sensitive information. If it becomes known to others, there is a risk that unauthorized actions could be performed through your LINE account. Never make it public.

Step 3: Google Apps Script Configuration

Next, we will write the code to send notifications to LINE using Google Apps Script (GAS).

1. Creating a GAS Project

Access Google Apps Script and create a new project.

2. Writing the Script

Copy and paste the following code into your project. This code has the functionality to find unread emails with a specific Gmail label and notify their content to LINE.


function sendNotificationForUnreadMessages() {
  // LINE Messaging API設定
  const channelAccessToken = '************************';
  const userId = 'U***************************';
  const labelName = '*****'; // 監視したいGmailラベル名を設定

  // Gmailの検索
  const searchQuery = `label:${labelName} is:unread`;
  const threads = GmailApp.search(searchQuery);
  const messages = GmailApp.getMessagesForThreads(threads);

  // メッセージ処理
  for (const thread of messages) {
    for (const message of thread) {
      if (!message.isUnread()) continue;

      const subject = message.getSubject();
      const bodyText = message.getPlainBody();
      const snippet = bodyText.substring(0, 70) + '...';
      const sender = message.getFrom();
      const receivedDate = message.getDate();

      // メッセージ本文の作成
      const messageText = 
        `📧 新着メール\n\n` +
        `📎 件名:${subject}\n` +
        `👤 送信者:${sender}\n` +
        `🕒 受信日時:${receivedDate.toLocaleString()}\n\n` +
        `📝 本文:\n${snippet}`;

      // メッセージペイロード作成
      const payload = {
        to: userId,
        messages: [{
          type: 'text',
          text: messageText
        }]
      };

      // API送信オプション
      const options = {
        method: 'post',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${channelAccessToken}`
        },
        payload: JSON.stringify(payload),
        muteHttpExceptions: true
      };

      try {
        // メッセージ送信
        const response = UrlFetchApp.fetch(
          'https://api.line.me/v2/bot/message/push',
          options
        );
        
        const responseCode = response.getResponseCode();
        
        if (responseCode === 200) {
          Logger.log('メッセージを送信しました');
          message.markRead();
        } else {
          Logger.log(`送信エラー (${responseCode}): ${response.getContentText()}`);
        }

      } catch (error) {
        Logger.log(`エラーが発生しました: ${error.toString()}`);
      }
    }
  }
}

// トリガー設定用関数
function createTimeDrivenTrigger() {
  // 既存のトリガーを削除
  const triggers = ScriptApp.getProjectTriggers();
  triggers.forEach(trigger => ScriptApp.deleteTrigger(trigger));

  // 新しいトリガーを作成(5分間隔)
  ScriptApp.newTrigger('sendNotificationForUnreadMessages')
    .timeBased()
    .everyMinutes(5)
    .create();
}

3. Items that require individual configuration



(1) channelAccessToken
Replace channelAccessToken with your own information obtained earlier from LINE Developers. This is the Channel Access Token (long-lived).

  const channelAccessToken = '【LINE Developerで取得したトークン】';


(2) userId
The userID starts with "U", followed by 32 alphanumeric characters.
Please refer to this article for how to obtain your user ID.
https://note.com/m316jp2/n/nc466911fa9ab

  const userId = '【あなたのユーザーID】';


(3) labelName
Set the conditions for emails to be notified via LINE. In my case, I have it set to notify LINE when an email with a specific label arrives.'Gmail label name you want to notify'Enter the label name you want to be notified about in the place of.

  const labelName = '【通知したいGmailのラベル名】'; // 監視したいGmailラベル名を設定

4. Saving the Code

Once you have entered all the code, save the project. Please give the project a name.

Step 4. Deploying GAS and Setting the Webhook URL

1. Deploying GAS

Select "Deploy" > "New deployment" from the menu.

  • Select "Web app" as the deployment type.

  • Select "Anyone" for who can access the app.

  • Once the deployment is complete, the web app URL will be displayed. Copy this URL.

2. Setting the Webhook URL


Return to the Messaging API settings screen in the LINE Developers console, paste the web app URL you copied earlier into the "Webhook URL" field, and click the "Update" button. This will allow event information from the LINE platform to be sent to GAS.

3. Verifying the Webhook

To verify that the script is working correctly, please try running it manually. If it works properly, you will receive a Gmail notification on LINE.

Step 5: Setting up Triggers

Finally, set the script to run automatically at regular intervals.

In the GAS script editor, open the 'Triggers' menu and create a new trigger.

  • Function to run: sendNotificationForUnreadMessages

  • Event source: Time-driven

  • Time-based trigger: Every minute (or any interval of your choice)

With this, the script will run automatically at the specified interval, and you will be notified on LINE whenever there is a new email.

This completes the switch from LINE Notify to the Messaging API! It might feel a bit complicated at first, but once you have it set up, you can achieve more advanced LINE notifications. Please give it a try.



----------
The book I wrote has been published!
\Born from Twitter/
A slightly science-oriented home play book

Amazon Best Sellers Rank
Early Childhood Education Category - Paid Top 100
It reached #1 Bestseller!✨
Thank you!

Available on Kindle Unlimited and in paperback!








いいなと思ったら応援しよう!

宮崎真理|『AI×家事』著者 ❤️応援ありがとうございます。いただいたご支援は「めんどくさい」を解決する新しいテクノロジーの検証費や、3兄弟との楽しい実験材料費に大切に使わせていただきます。皆さまの応援が力になります!