TypeError:无法读取null的属性“sendMessage”

时间:2017-05-15 22:05:53

标签: node.js bots slack-api slack

我正在尝试测试我的新Slackbot,向它发送一个问候语,其中包含它回复的预期行为'这是一条测试消息'按照我在slackClient.js中的代码:

'use strict'

const RtmClient = require('@slack/client').RtmClient;
const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
let rtm = null;

function handleOnAuthenticated(rtmStartData) {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`);
}

function handleOnMessage(message) {
  console.log(message);
  // This will send the message 'this is a test message' to the channel identified by id 'C0CHZA86Q'
  rtm.sendMessage('this is a test message', message.channel, function messageSent() {
    // optionally, you can supply a callback to execute once the message has been sent
  });
}

function addAuthenticatedHandler(rtm, handler) {
  rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, handler);
}

module.exports.init = function slackClient(bot_token, logLevel){
  const rtm = new RtmClient(bot_token);
  addAuthenticatedHandler(rtm, handleOnAuthenticated);
  rtm.on(RTM_EVENTS.MESSAGE, handleOnMessage)
  return rtm;
}

module.exports.addAuthenticatedHandler = addAuthenticatedHandler;

这是我得到的错误:

 rtm.sendMessage('this is a test message', message.channel, function messageSent() {
     ^

TypeError: Cannot read property 'sendMessage' of null

如果我理解正确,它会告诉我我不能给rtm一个null值,但是我可以给它什么类型的样板值以便我可以测试它?

1 个答案:

答案 0 :(得分:0)

我发现了我的错误,我将rtm作为const,然后是let。所以我从rtm = new RtmClient(bot_token)中删除了const;并继续添加像这样的nlp:

'use strict'

const RtmClient = require('@slack/client').RtmClient;
const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
let rtm = null;
let nlp = null;

function handleOnAuthenticated(rtmStartData) {
  console.log(`Logged in as ${rtmStartData.self.name} of team ${rtmStartData.team.name}, but not yet connected to a channel`);
}

function handleOnMessage(message) {

  // This will send the message 'this is a test message' to the channel identified by id 'C0CHZA86Q'
  rtm.sendMessage('this is a test message', message.channel, function messageSent() {
    // optionally, you can supply a callback to execute once the message has been sent
  });
}

function addAuthenticatedHandler(rtm, handler) {
  rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, handler);
}

module.exports.init = function slackClient(bot_token, logLevel, nlpClient){
  rtm = new RtmClient(bot_token);
  nlp = nlpClient;
  addAuthenticatedHandler(rtm, handleOnAuthenticated);
  rtm.on(RTM_EVENTS.MESSAGE, handleOnMessage)
  return rtm;
}

module.exports.addAuthenticatedHandler = addAuthenticatedHandler;