Search code examples
node.jsslack-apibotkit

slack how to know if bot recently posted


I am using botkit, i have a bot that responses to a certain word. But i don't want the bot to response if it recently did so.

Currently i am using channels.history method to retrieve 4 recent messages then find the bot id, if its there it won't reply. This is not pretty, i've been searching for useful methods to use but i can't find any. I just want to find out if the bot recently posted or not and do actions base on it.

   const targetBotID = 'GKALXJCM6'  
   bot.api.channels.history({
            channel: message.channel,
                latest: message.ts,
                count: 4,
                inclusive: 1,
            },  function(err, response) {
                  if(err) { bot.reply(message, 'Something is wrong with me, check log if there is??'); }

                  if(response){
                      const recentPostFound = response.messages.filter(function (member) {
                                                 return member.user === targetBotID;
                                              });

                      if(recentPostFound){
                        return bot.reply();
                      }
                        return bot.reply(answer) // Answer if no matching id found

                  }
              });

Solution

  • I can see two solutions to your issue:

    1. Record previous actions of your bot in some kind of app context (e.g. database). Then you can verify each time if your bot already answered.

    2. Consider using Events API instead of loading the chat history each time. Then your bot gets exactly one event request for each new message in a channel and you can be sure that your bot will only react once.