0

I am using the Slack RTM node client and having a bit of an issue with DM's. Say a user joins the channel who has never DM'ed the bot before, the user types a command in the channel that the bot usually will respond to and by default the bot responds in a private message to the user. However, the bot cannot do this because the dataStore does not contain any DM data for this user. Code sample below...

rtm.on(RTM_EVENTS.MESSAGE, function (message) {
  user = rtm.getUserById(message.user);
  console.log(user); // It gets the user object fine
  dm = rtm.getDMByName(user.name);
  console.log(dm); // This is always undefined unless the user has DM'ed the bot previously
});

Is there a way around this? I can't seem to find anything in the docs or code to suggest there might be.

Catharsis
  • 616
  • 4
  • 20

1 Answers1

1

You can use the im.open method of the web API. Here's roughly how you'd do it with @slack/client (untested, apologies in advance!):

var webClient = new WebClient(token);
...
rtm.on(RTM_EVENTS.MESSAGE, function (message) {
  var dm = rtm.getDMById(message.user);
  if (dm) {
    console.log(`Already open IM: ${dm}`);
    // send a message or whatever you want to do here
  } else {
    webClient.im.open(message.user, function (err, result) {
      var dm = result.channel.id;
      console.log(`Newly opened IM: ${dm}`);
      // send a message or whatever you want to do here
    });
  }
});
user94559
  • 59,196
  • 6
  • 103
  • 103
  • I did think about doing something with the webClient to make this work but never actually tried it, I will give this a go tomorrow. Thanks for the response – Catharsis Jun 08 '16 at 21:50
  • Hey just wanted to say thinks, this indeed did work as I suspected, sorry it's taken me a while to test it out and get back to you, have a tick and an upvote :) – Catharsis Jun 21 '16 at 11:16