1

我正在使用一个节点包:slack-client 与 slack 的 api 交互。现在无论是否使用 slack-client,我如何从我的机器人向我想要指定的用户发送直接消息?这是迄今为止使用普通套接字连接的内容:

var WebSocket = require('ws')
,ws2 = new WebSocket(myURL); //from rtm start
 ws2.on('open', function() {
    ws2.send({
    "id": 333,
    "type": "message",
    "channel": "@user1", //User I want to send to
    "text": "HEY!!!!"
    });
});
ws2.on('message', function(message) {
    console.log('received: %s', message);
}); 

我希望该消息会直接从机器人发送给我,但什么也没有。我得到一个类型的回复你好虽然?上面的发送详细信息我在另一篇关于此的帖子中找到,但它对我不起作用。消息 ID 是我创建的。

4

1 回答 1

0

好的,所以当通过 web api 调用 rtm.start 时,你会得到一个对各种用户开放的 DM 列表,否则你可以很容易地用 im.open 打开一个 im。我正在使用我的问题中提到的节点包 slack-client 所以你可以这样做:

     //name of user your bot wants to send a msg to.
     var userTest = slack.getUserByName('user1');
     slack.openDM(userTest.id, function(res)
     {
         TestMsg(res.channel.id, 'some other msg');//test function I'm using
     });

接下来是 TestMsg 函数:

function TestMsg(userChannelId, msg)
{
  request.post({url:     'https://slack.com/api/chat.postMessage',
                form:    { token: "xxxx-yourbot-token",channel: userChannelId,text: msg ,username: "yourBotNamehere", as_user: false}
              }, function(error, response, body){
                console.log(response.body);
               });
}

我还不能使用 websockets 发送方法让它工作,但我想 postMessage 的 api 现在可以使用,因为你可以使用 postMessage 发布格式丰富的消息。希望这可以帮助某人

于 2015-07-16T12:32:26.447 回答