特定のラベルが付いたGmailのメールをTodoistのタスクに登録するGoogleAppsScript

Gmailにフィルタの設定を行い、対象のメールに特定のラベル(以下のサンプルだと mailtotask )を付与する仕組みを入れておく。
その状態でこのスクリプトを走らせると、そのメールの件名をタイトルとする Todoist タスクを自動生成し、処理が成功したらラベルを自動的に剥がす。
スクリプトは5~10分間隔で自動実行させるのを推奨。

必要なパラメータはプロジェクトのプロパティに値として設定すれば、スクリプトはそのまま流用可能(なはず)。もし動作をカスタマイズするならクエリなどを修正すればOK。

GoogleAppsScript本体

// 固定値の定義
const scriptProperties = PropertiesService.getScriptProperties();
const TODOIST_API_TOKEN = scriptProperties.getProperty('TODOIST_API_TOKEN');
const TODOIST_PROJECT_ID = scriptProperties.getProperty('TODOIST_PROJECT_ID'); // プロジェクトID
const TODOIST_SECTION_ID = scriptProperties.getProperty('TODOIST_SECTION_ID'); // セクションID
const TODOIST_LABELS = scriptProperties.getProperty('TODOIST_LABELS'); // ラベル(ラベル文字列、カンマで複数指定)
const TODOIST_PRIORITY = scriptProperties.getProperty('TODOIST_PRIORITY'); // 4
const GMAIL_LABEL = scriptProperties.getProperty('GMAIL_LABEL'); // 処理対象として識別させるラベル(Gmailのフィルタクエリの記述に準拠する)

function syncMailToTodoist() {
  // Gmailの検索クエリ
  const query = "label:" + GMAIL_LABEL;

  console.log("メール確認:" + query);
  const threads = GmailApp.search(query);

  // ラベル取得
  const CtrlLabel = GmailApp.getUserLabelByName(GMAIL_LABEL);
  
  if (threads.length === 0) {
    console.log("対象のメールはありませんでした。");
    return;
  }

  threads.forEach(thread => {
    const messages = thread.getMessages();
    const latestMessage = messages[messages.length - 1];
    const subject = latestMessage.getSubject();
    // メールへの直接URLを生成
    // 基本的には https://mail.google.com/mail/u/0/#inbox/[threadId] でアクセス可能
    const threadId = thread.getId();
    const mailUrl = "https://mail.google.com/mail/u/0/#inbox/" + threadId;
    
    // Todoist APIにタスクを投稿
    const success = createTodoistTask(subject, mailUrl);
    
    if (success) {
      // 処理済みとしてマークする(二重登録防止)
      thread.removeLabel(CtrlLabel); // ラベルを剥がすならこちら
      // thread.markRead(); 既読にするならこちら

      console.log("タスクを作成しました: " + subject);
    } else {
      console.log("タスク作成に失敗しました: " + subject);
    }
  });
}

function createTodoistTask(title, description) {
  const url = 'https://api.todoist.com/rest/v2/tasks';
  
  const payload = {
    'content': title,
    'description': description,
    'due_string': 'today',
    'priority': TODOIST_PRIORITY,
    'project_id': TODOIST_PROJECT_ID,
    'section_id': TODOIST_SECTION_ID,
    'labels': [ TODOIST_LABELS ]
  };

  const options = {
    'method': 'post',
    'contentType': 'application/json',
    'headers': {
      'Authorization': 'Bearer ' + TODOIST_API_TOKEN
    },
    'payload': JSON.stringify(payload),
    'muteHttpExceptions': true
  };

  const response = UrlFetchApp.fetch(url, options);
  // console.log("Response from Todoist: " + response);
  return response.getResponseCode() === 200;
}

GoogleAppsScriptプロジェクトのプロパティ設定サンプル

 

この記事が気に入ったら
いいね!しよう

最新情報をお届けします

Twitter でそらみみをフォローしよう!

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です