Search code examples
node.jsslack-apislack

How to build a slack bot to have multiple conversations?


I am building a slack bot using a third party service to handle responses based on inputs rather than just hard coding them into the bot. This service's API needs a client id & a conversation id to get the response. I found out that each time a slack bot receives a message, it creates a new message object each time so there isn't a way of keeping the clientID and conversation ID within the message object and have slack hold onto it.

rtm.on(RTM_EVENTS.MESSAGE, function(message // <-- new object each time the bot hears a message){
  rtm.sendMessage('hello', message.channel);
});

So shortened down, does anyone know of a way to keep a conversation between a single user and the bot while holding onto some type of variable to hold the client and conversation ID?


Solution

  • You can store the message.user ID and track the conversation referring to that specific user. You will need to keep track of all ongoing conversations yourself. Something like this

    rtm.on(RTM_EVENTS.MESSAGE, function(message // <-- new object each time the bot hears a message){
      if(stored_conversations.indexOf(message.user) > -1){
        //customize message depending on history
        rtm.sendMessage('I remember you', message.channel);
      }
    });
    

    Or, you could use Botkit - it manages bot-user conversations for you.