【Node.js】建立Bot机器人

刚接触 NodeJS,纪录一下

//============汇入Modules============
var restify = require('restify');
var builder = require('botbuilder');

//============读取config============
var fs = require('fs');
var config = fs.readFileSync(__dirname + '/config.json','utf8'); //__dirname -->localpath

//============建立Server============
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978);

//============建立Bot============
var connector = new builder.ChatConnector({
  appId:config.appId,            //bot framework appId
  appPassword:config.appPassword //bot framework appPassword
});

var bot = new builder.UniversalBot(connector);

server.post('/api/messages', connector.listen()); //----->这个要记住

//============建立Bot对话============
bot.dialog('/',
  [function(session)
  {
      session.send("Hi,I am bot ~");
      builder.Prompts.text(session,'What\'s your name ?');
  },
  function(session,result)
  {
    session.send('Nice to meet you ,'+ result.response);
  }]
);
  1. 先到Bot Framework取得bot帐号(appId)和密码(appPassword),并且建立一个Bot
  2. 在console下输入 npm init,建立package.json(记得要save)
  3. console 汇入 npm install restify –save,npm install botbuilder –save
  4. 建立app.js
  5. 汇入连线restify 和机器人botbuilder
  6. 建立Server端,需要process.env.port、process.env.PORT、3978,之后布版才能随机取得IP
  7. 建立和机器人连线的connector和机器人bot 物件,之后记得要post(‘/api/messages’,connector.lisren())
  8. 机器人初始对话要从’/’开始,session.send() method是无回应,builder.Prompts.text()是会等待回应,记得要有session,binding用户,之后用户回应用result.response接收

以上参照Bot Builder Getting Started