1.2. Integration messenger and Node.js

1.2. Integration messenger and Node.js

1.Introduction

  • 只用DialogFlow我們可以建立一個簡單的機器人, 但是如果想要做到更延伸的功能, 我們可以整合Node.js, Heroku, DialogFlow

2.Step by step

  1. Create a new agent in DialgFlow

  2. Create a new Heroku app

    • Install Heroku cli

    • Open ternminal and type:

      heroku --version
      heroku login
  3. Clone template from Github

     git clone https://github.com/jbergant/chatbot-facebook-nodejs.git
  4. 從package.json中可以看出需要的module, 例如apiai

  5. 建立一個Facebook page

    • 填入名稱

  6. 建立一個新的Facebook App

    • 填入Facebook page名稱

    • 選擇Messenger -> SetUp

    • 從Page的下拉式選單中選擇你的Facebook page, 將會產生一組token拷貝它

    • 打開project -> config.js -> FB_PAGE_TOKEN, 貼上token

      module.exports = {
        FB_PAGE_TOKEN: '',
        FB_VERIFY_TOKEN: '',
        API_AI_CLIENT_ACCESS_TOKEN: '',
        FB_APP_SECRET: '',
        SERVER_URL: "",
      };
    • 設定Facbook app webhook

      • 打開Heroku Dashboard -> Settings -> 拷貝Heroku Domain

      • 將Heroku Domain貼到Facbook app webhook的Callback URL

      • 將Heroku Domain貼到project -> config.js -> SERVER_URL

      • 輸入一組任意字串到Verify token

      • 將Verify token貼到project -> config.js -> FB_VERIFY_TOKEN

      • Subscription Fields勾選messages, messaging_postbacks

      • 從DialogFlow的Dashboard中找到Client access token, 拷貝並貼到project -> config.js -> API_AI_CLIENT_ACCESS_TOKEN

      • 從Facebook developer appdashboard的Settings -> Basic, App Secret -> Show, 拷貝後貼到 project -> config.js -> FB_APP_SECRET

  7. 將project deploy到Heroku

    • Navigate to the project and type:

      git remote rm origin
    • 打開Heroku Dashboard -> Settings -> 拷貝Heroku Git URL, 並輸入

      git remote add heroku [Heroku Git URL]
    • commit the changes

      git add .
      git commit -m "init configuration"
    • push to Heroku

      git push heroku master
  8. Deploy完成後回到Facbook app webhook, 點選Verify and Save

  9. 從Webhooks section的下拉式選單中選擇你的Facebook page, 點選Subscribe

  10. 輸入heroku logs

  11. 如何在local端測試呢? 可以使用Localtunnel 或是ngrok

3. Code review

  • verifyRequestSignature

    • 在這裡會將x-hub-signature與加密後的app secret比對, 若不同則會拋出error

  • public folder

    • 放些公開的靜態資料如image

  • app.get('/')

  • app.get('/webhook/')

  • app.post('/webhook/')

    • receivedMessage: 處理user的訊息事件

      • handleEcho

      • handleQuickReply: 傳訊息給DialogFlow來處理

      • sendToApiAi

      • handleMessageAttachments: 處理非文字訊息

    • receivedPostback

Last updated