Chatbot với Botpress - Phần 2: Coding

Tiếp tục phần 2, phần trước Chatbot với Botpress bạn đã có 1 bộ khung cho Bot chỉ với vài thao tác, kết nối mới Messenger với Persistent Menu, Getting Started message, làm quen với postback, Auto response, ... module botpress-analytics để thống kê.

Về cơ bản Bot theo cơ chế lắng nghe lệnh (từ khóa) và trả lời. Sau mình sẽ ví dụ đơn giản về cách lập trình cho Bot, làm Bot thông minh hơn khi kết hợp với 1 số service API trí tuệ nhân tạo (Wit.ai, Api.ai, ...)

Xem lại phần 1: Chatbot với Botpress - Phần 1: Init Chatbot

Simple Hello World

OK để bắt đầu ta mở index.js

module.exports = function (bp) {
  bp.middlewares.load();
};

Dòng 1: bp là biến global context object, từ bp ta có thể truy cập đến mọi chức năng của botpress và module api. Dòng 2: Botpress sử dụng cơ chế middlewares để xử lý incoming và outcoming tin nhắn (hoặc tương tác). Bạn có thể xem thêm về trang middleware tại đây.

Bây giờ chúng ta thêm vào index.js như sau:

module.exports = function (bp) {
  bp.middlewares.load();

  bp.hear('hello ku', (event) => {
    // Capture 'hello ku'
    bp.messenger.sendText(event.user.id, 'Hello world!'); // Response
  });
};

Khởi động lại Botpress server. Ở đây mình hardcoded, Bot sẽ lắng nghe chuỗi "hello ku" và trả lời "Hello world!". Đây chỉ là ví dụ cơ bản thôi, hear middleware thực sự rất hữu ích.

Hello world nhưng bớt ngu hơn xíu

Bây giờ mình muốn mỗi khi bot nghe "hello" là tự động chào lại bằng tên (first_name) mình.

module.exports = function (bp) {
  bp.middlewares.load();

  bp.hear(/hello/i, (event, next) => {
    // We use a regex instead of a hardcoded string
    const first_name = event.user.first_name;

    bp.messenger.sendText(event.user.id, 'Hello, ' + first_name, {
      typing: true,
    });
  });
};
  • Ở lệnh hear, mình không dùng hardcoded string nữa mà sử dụng regex. Bất kì tin nhắn nào chứa "hello" thì callback sẽ được gọi.
  • Object event.user sẽ chứa mọi thông tin của user, mình sử dụng nó để reply lại chính tên người dùng.
  • Tham số thứ 3 của hàm sendText, ta dùng { typing: true } messenger sẽ hiển thị hiệu ứng đang typing, nhìn sẽ thật hơn.

Messenger Quick Reply

Quick Reply là chức năng trong Messenger, cho phép user thay vì phải chat thì có thể chọn 1 từ menu. Khai báo tham số quick_replies như sau:

module.exports = function (bp) {
  bp.middlewares.load();

  bp.hear(/hello/i, (event, next) => {
    // We use a regex instead of a hardcoded string
    const first_name = event.user.first_name;
    console.log('==========', event.user);

    bp.messenger.sendText(event.user.id, 'Hello, ' + first_name, {
      typing: true,
    });
  });

  bp.hear(/help/i, (event, next) => {
    const options = {
      quick_replies: [
        {
          content_type: 'text',
          title: 'Đẹp',
          payload: 'HELP_OPTION_1',
        },
        {
          content_type: 'text',
          title: 'Rất đẹp',
          payload: 'HELP_OPTION_2',
        },
      ],
      typing: true,
      waitRead: true, // `waitDelivery` or `waitRead` options
    };

    const text = 'Duyệt có đẹp trai không?';
    bp.messenger.sendText(event.user.id, text, options).then(() => {
      // Do `waitRead` nên nội dung trong đây sẽ được thực thi khi user read.
    });
  });
};

Messenger Attachments

Messenger có thể gửi đính kèm với 4 định dạng: 'audio', 'file', 'image' or 'video'

module.exports = function (bp) {
  bp.middlewares.load();

  bp.hear(/meo/i, (event) => {
    const type = 'image'; // 'audio', 'file', 'image' or 'video'
    const img_url =
      'https://avatars0.githubusercontent.com/u/5009534?v=3&s=460';
    bp.messenger.sendAttachment(event.user.id, type, img_url);
  });
};

Tham số thứ 3 url của file đính kèm.

Messenger Templates

Facebook hỗ trợ nhiều dạng message template. Ví dụ như:

  1. Button Template
  2. Generic Template
  3. List Template
  4. Receipt Template
  5. Airline Bording Pass
  6. Airline Checkin
  7. Airline Itinerary
  8. Airline Flight Update

Để sử dụng chúng ta chỉ cần khai báo đúng template như trong docs của facebook. Ví dụ:

bp.hear(/duyetdev/i, (event) => {
  const payload = {
    template_type: 'button',
    text: 'duyetdev profile',
    buttons: [
      {
        type: 'web_url',
        url: 'https://duyet.net',
        title: 'duyet.net',
      },
      {
        type: 'web_url',
        url: 'https://duyet.net',
        title: 'Profile',
      },
      {
        type: 'web_url',
        url: 'https://facebook.com/duyetdev',
        title: 'Facebook',
      },
    ],
  };

  bp.messenger.sendTemplate(userId, payload, { typing: true });
});

Kết

ChatBot không chỉ phải biết trả lời theo từ khóa mà còn phải hiểu được ý người chat khi viết bằng nhiều cách khác nhau, phần tiếp theo chúng ta sẽ làm cho con ahihi "thông minh" hơn bằng cách kết hợp với các Service API NLP để get được context, object, ... từ tin nhắn của người dùng.

Nếu có thời gian mình sẽ viết 1 bài tự build ra model cho Bot để có thể đọc hiểu và trả lời ở mức cơ bản.

Xem phần 1: Chatbot với Botpress - Phần 1: Init Chatbot

Tham khảo

  1. Nodejs - Chatbot với Botpress
  2. Botpress Advanted Topics
  3. Botpress Messenger
  4. Messenger Platform - Facebook Developers.
WebChatbotJavascriptNode.jsNode