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.

4

1 回答 1

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
    });
  }
});
于 2016-06-08T18:07:13.440 回答