node-webot / weixin-robot

微信公共帐号自动回复机器人 A Node.js robot for wechat.
1.76k stars 555 forks source link

noReply = true无效 #66

Closed sang4lv closed 10 years ago

sang4lv commented 10 years ago

目前我的第一条rule是基于用户是否启动会话从而判断是否由weixin-robot来回复,否的话,noReply = true。但是不知为何,程序总是会跳到下一条rule,而且这是info为空,导致程序崩溃。大致代码如下

    wechat.set('SUPPORT', {
      pattern: function(info) {
        return info.session.chatUsers.indexOf(info.uid) !== -1;
      },
      handler: function(info) {
        if( info.is('event') ) {
          info.reply = 'Doing Stuff...';
        } else {
          eventEmitter.emit('userMessage', info.uid, info.text);
          info.noReply = true; //这里就不应该继续跳下去
        }
      }
    });
    wechat.set('SERVICE_DELIVERY', {
      pattern: function(info) {
        return info.param.eventKey.toLowerCase() === 'service_delivery'; //这里崩溃了
      },
      handler: 'some reply'
    });
sang4lv commented 10 years ago

这是崩溃是出的call stack

/var/www/node/wechat/app.js:122
      return info.param.eventKey.toLowerCase() === 'service_delivery';
                                 ^
TypeError: Cannot call method 'toLowerCase' of undefined
    at Rule.wechat.set.pattern (/var/www/node/wechat/app.js:122:34)
    at Rule.test (/var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/rule.js:157:14)
    at tick (/var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/webot.js:400:15)
    at /var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/webot.js:438:7
    at Rule.exec (/var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/rule.js:236:14)
    at tick (/var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/webot.js:424:10)
    at /var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/webot.js:438:7
    at Rule.handler (/var/www/node/wechat/app.js:101:5)
    at Rule.exec (/var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/rule.js:238:15)
    at tick (/var/www/node/wechat/node_modules/weixin-robot/node_modules/webot/lib/webot.js:424:10)
ktmud commented 10 years ago

info.noReply 只代表最后处理出的消息内容不会返回给微信接口;你可以使用 info.ended 来表示不再需要执行下一条规则。

另外,不建议直接在 handler 里直接给 info.reply 赋值。因为一个 handler 提供的 reply 应该是唯一的,你可以直 return 回复内容。

随附的代码可以优化为:

    wechat.set('SUPPORT', {
      pattern: function(info) {
        return info.session.is_chat_user;
      },
      handler: function(info) {
        if( info.is('event') ) {
          return 'Doing Stuff...';
        }
        eventEmitter.emit('userMessage', info.uid, info.text);
        info.noReply = true;
        info.ended = true;
      }
    });
ktmud commented 10 years ago

另外, info.session 对每个微信用户来说都是唯一的,不要把全局数据赋给每个 session