LoginSignup
7
12

More than 5 years have passed since last update.

BotkitでSlackに投稿したメッセージを一定時間後に消す

Posted at

BotkitでSlackのBOTを作成してみたんですが、投稿を削除するのに少し工夫が必要だったのでそのメモです。
今回対象としているのは controller.hears() または controller.on() でハンドリングした際に投稿するメッセージの削除です。
使い方の説明はしません。

BOTが自身の投稿したメッセージを消すには

投稿の callback 内でレスポンスから channelts (タイムスタンプ) を取得してslack apichat.deletを叩けば消すことができます。実際には channel は投稿前にわかっているので消すのに必要なものは ts のみです。

bot.reply()でresponseが空になってしまう

Botkitのドキュメントを見ると、引数のcallbackでエラーとレスポンスが取れるようなのですが、なぜか空になっていました。(僕だけでしょうか...)

Argument Description
message Incoming message object
reply String or Object Outgoing response
callback Optional Callback in the form function(err,response) { ... }

以下はうまくいかなかった例です。

投稿完了した後10秒後に削除できなかった例
bot.reply(message, '投稿するメッセージ', function(err, response) {
    if (!err) {
        setTimeout(function() {
            bot.api.chat.delete({
                ts: response.ts,
                channel: response.channel,
            }, function(err, res) {
                if (err) {
                    bot.botkit.log('chat.delete error: ', error);
                }
            });
        }, 10000);
    }
});

解決策

仕方がないので投稿をslack apichat.postMessageを利用して行いました。
こちらではcallbackにレスポンスが含まれており削除することができました。

投稿完了した後10秒後に削除できた例
bot.api.chat.postMessage({
    username: "bot name",
    text: '投稿するメッセージ',
    channel: message.channel,
    link_names: 1,
    unfurl_links: true,
    icon_url: 'http://example.com',
  }, function(err, response) {
    if (!err) {
        setTimeout(function() {
            bot.api.chat.delete({
                ts: response.ts,
                channel: response.channel,
            }, function(err, res) {
                bot.botkit.log('chat.delete:\n', res);
            });
        }, 10000);
    }
  });
});
7
12
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
7
12