0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

gasからChatworkのAPIを利用して送信する

Last updated at Posted at 2020-04-30

発端

自分のリマインダーとしてスプレッドシート x チャットワークへの送信をお手製で作成した。

概要としてはスプレッドシートに記載したリマインドリストを、設定した時間になったらチャットへ飛ばすというもの。

ただし、送信したメッセージが自分から見て未読表示にならないため今回紹介する方法で対応した。

環境

実行環境: GAS ( Google Apps Script )
ライブラリ: chatwork-client-gas

結論

いろんな記事で紹介されている「sendMessage関数」は使わずに「post関数」を使う。

説明

よく使う「sendMessage」関数はpostしたメッセージを未読にする「self_unread」オプションに対応はしていなかった。

チャットワークAPIドキュメント

なので、post時にオプションを設定できる「post関数」を使って実施した。
( ここをライブラリ本体のjsを見るまで知らなかった... )

実装

▼ライブラリのsendMessage関数部分

ライブラリのsendMessage関数部分
    ChatWork.prototype.sendMessage = function(params) { 
      var post_data = {
        'body': params.body
      }
      
      return this.post('/rooms/'+ params.room_id +'/messages', post_data);
    };

そこでライブラリに標準装備されている「post関数」を使ってself_unreadオプションを付与するようにした。

      var roomID = 12345678;  // チャットワークのルームID
      var message = "あああああ";  // 投稿するメッセージ

      // チャットワークAPI
      var client = ChatWorkClient.factory({
        token: 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
      });
      
      var endPoint = "/rooms/" + roomID  + "/messages";
      var postData = {
        body: message,
        self_unread: "1" // 自分の投稿を未読にする
      };

     // チャットワークへポスト
     client.post(endPoint, postData);      

これで、送信後に自分から見ても未読になった状態ができた。

この中で一つだけ注意点があり、このself_unreadのオプションを指定する「1」は文字列にしないと、「1.0」という数値に変換されてしまい送信時にエラーになってしまう。

参考:GAS から Chatwork の通知をする場合、self_unreadの値は文字列で設定する

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?