12
8

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.

SlackのEvents APIが複数回叩かれてしまうことがあったのでその対応をした

Posted at

GASでメンションに反応してくれるslackbotをつくったんですが、なぜか複数回同じパラメータでapiが叩かれてしまうバグ(仕様?)があったのでその対応をしました。
具体的には、キャッシュを利用して同じメッセージには一度しか応答しないようにしました。

スクリプト

function doPost(e) {
  var postData = JSON.parse(e.postData.getDataAsString());
  var res = {};
  
  // これはslackbotのurl検証用コード
  if(postData.type == 'url_verification') {
    res = {'challenge':postData.challenge}
    return ContentService.createTextOutput(JSON.stringify(res)).setMimeType(ContentService.MimeType.JSON);
  }

  var channel = postData.event.channel;
  var ts = postData.event.ts;
  
  var cache = CacheService.getScriptCache();
  // ここのキーは自由に変えてください。
  // 今回はメンションに反応するbotなので発言されたチャネルID、タイムスタンプをキーにしました。
  var cacheKey = channel + ':' + ts;
  var cached = cache.get(cacheKey);
  if (cached != null) {
    console.log('do nothing!');
    return;
  }
  cache.put(cacheKey, true, 1800); // 30分キャッシュする(ここは目安。もっと短くてもいいかもしれない)
 
  // do something

}

以上です :hugging:

参考

12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?