I have worked on the development of conversational robots, both software and hardware. In the past, the server used express and the front-end used Vue. The hardware is quanzhi + Lexin. Now I’m back to writing conversational bots, using React (hooks) on the front end and Laravel (PHP) on the back end. I don’t code the hardware this time.

The reasons for using Laravel for the back end are as follows:

1. Cost considerations. Python or Node hosts are much more expensive than PHP hosts. In fact, such applications do not require much computing resources. So Laravel is well suited for this application scenario.

If you just want to build a conversational robot, you don’t even need a back end, just connect to the various microservice apis.

2. The previous company used Express, so the new development is in Laravel and will not contain any code similar to the previous company.

The front end uses react hooks for the following reasons:

1. Almost all of my previous commercial projects in the company were VUE. In order to avoid accidentally mixing in the company’s commercial code (although it is highly unlikely), I directly used React hooks.

2. In the past, the author’s React projects in the company were all versions before 16.4, so I can guarantee that there is no previous code in the React hooks this time, thus eliminating risks.

3. There is a UI dedicated to the chat interface, and it only supports React. With a well-developed UI, you can save a lot of time.

There is little need to focus on life cycles, only dependence on a variable, so complex logic becomes simple.

5. Alibaba’s open source ahooks ahooks.js.org/zh-CN is an enhancement of hooks, which is very convenient to use.

What is a conversational robot

Conversational robots are mainly used as a means of interaction to do more focused functional products on a limited screen.

PC terminal interface can be very rich, such as library query system, such as IKEA household query interface. It shows a lot of things.

But on a small screen, it’s hard to fit all that stuff. Apps or small programs, with their touch-based operations, are not a panacea. Touch screens are limited and easy to misuse. The most common is the ordering machine, which sometimes slips up and down, adding items to the cart by mistake.

A conversational chatbot, in the form of a chat, runs a process. By throwing out a question and providing corresponding input components (single selection, multiple selection, click on the hot area of the picture, etc.), users do not need to slide, only need to click to input, reduce the side effects caused by misoperation, the effect is more focused.

In the case of hardware, users can also choose from shortcut keys on the hardware, reducing the lag experience caused by touch sensitivity issues.

It can also play a guiding role for users who have difficulty choosing.

2. What can conversational robots do? What are the application scenarios?

Conversational robots are mainly used to provide help, and the application areas are customer service (pre-sales inquiry, sales guidance, after-sales service), shopping guide, guidance, companion learning, etc. The application scenarios are as follows:

1. Project selection of amusement park

Whether you are afraid of heights, whether you like stimulation, how much your height and weight, there is no heart cerebrovascular disease. These questions are asked by the robot through dialogue, and the user can choose the appropriate amusement project. The background needs to process these keywords that the user answers (clicks) to screen out the items suitable for the user. For example, if a user is afraid of heights, roller coasters might not be recommended.

2. Mall recommendation

Buy clothes, not only match, but also according to their own body shape (body shape, not fat or thin, specific is shoulder, hip, leg type, etc.), skin and skin quality. But there is another scenario, which is the dressing of a particular scene, which requires certain guidelines.

For example, users to interview, should buy what kind of clothing, users to attend a wedding, or to participate in the award ceremony, what clothes to wear.

This can be done through a process of asking the user to choose and recommend a suitable outfit through a dialogue.

3. Product and service consultation

This is a customer service chatbot. Almost every commercial organization has one. It is usually some customized keywords that can automatically reply to the user and give the user information. Also include to let the user input contact information, submit to the background, after the relevant sales staff will call to understand the user needs.

4, shopping mall dining guide

Do not know what to eat, whether you are angry recently, want to eat light or spicy. How many people to eat, how much money to budget. Based on these, the robot is made into a conversational robot, asking and answering questions to recommend restaurants in the mall. Many stores already have hardware that allows users to chat with robots on a hardware screen and get suggested restaurants.

5. Score, message, feedback, suggestion, etc

I once saw a chatbot interface like this on an ATM. After the operation is performed, you are allowed to choose your rating, whether you are satisfied with the experience, whether you have feedback and suggestions, etc.

There are many, many more applications.

The following example is a demo that uses a simple robot to help users choose the development version according to the development language, hardware interface requirements and application scenarios:

In the actual application, it’s going to be a lot more complicated than that. But it’s not a technical thing. The technical considerations are implementation only, but the specific questions and inputs will eventually be provided with an editor for the user to customize.

Obviously the editor needs a background, which is implemented in Laravel.

Three, first build a shell, do the simplest chatbot dialogue interface

From an architectural point of view, work out the functionality first and then the UI. But on the front end, you have to build the UI first, and then you have to connect to the API on the back end.

When doing back-end communication, often do an echo first, that is, no matter what is said, to return the original text.

Now the whole interface is composed of several parts, above is a title bar, in the case of the other party (robot) has not completed the input, the display is input, after the completion of the display is the normal title.

The following is the input box. After input, your message will be on the right and the robot’s message will be on the left. Because there is no backend currently connected, the echo effect of the robot is completely delayed.

Four, key code

1. Because echo has a delay, using timeout will cause every time the robot says something to overwrite what the user says because of the scope. (In timeout, the list you get is not the updated list, but the previous one, so if you append it after a delay, you append it before the first one, so you erase the first one.)

I made a special demo here, and you can see why: codesandbox.io/s/ ahook-te…

There are many ways to do this, the simplest way is to use the dynamic lists directly in Alibaba’s open source Ahooks.

Codesandbox.io /s/ ahook-te…

Code that uses dynamic lists in ahooks:

const { list, remove, getKey, push } = useDynamicList([]);
Copy the code

Push () can then be used to add to the list, as in:

const botSay=text=>{
    push({
        avatar:"/logo.jpeg",
        name:'bot',
        text:text,
        time:Date.now(),
        isOwn:false
    });
}
Copy the code

2. After input, the title box will produce the prompt of input, which is to change the title before and after the robot input.

const send = text => {
    push({
        avatar:null,
        name:'Guest',
        text:text,
        time:Date.now(),
        isOwn:true
    });
    setTpying('typing... ');
    setTimeout(() => {
        botSay(text);
        setTpying('Chat test');
    }, 1000);
}
Copy the code

3. Scroll after input, using the scrollIntoView effect.

const messagesEndRef = useRef(null);
const scrollToBottom = () => {
    messagesEndRef.current.scrollIntoView({ behavior: "smooth"})}Copy the code

When the list changes, you can start scrolling:

useEffect(scrollToBottom, [list]);
Copy the code

In return, add

:

  return (
      <ThemeProvider>
        ...
          <div ref={messagesEndRef} />
        ...
      </ThemeProvider>
  );
}
Copy the code

4. Because the user input and the robot input are displayed in different positions in the interface, the dialog between the robot and itself is also displayed as a function component.

function Bot(props){
  return(
    <Row>
      <Avatar imgUrl={props.avatar}/>
      <Message  authorName={props.name}>
        <MessageText>{props.text}</MessageText>
      </Message>
    </Row>
  )
}
function Guest(props){
  return(
    <Message isOwn authorName={props.name}>
      <MessageText>{props.text}</MessageText>
    </Message>
  )
}
Copy the code

V. Effect, deficiency and improvement

1. With the increase of chat content, the content does not automatically scroll to the bottom, which will cause part of the content to be covered (has been solved).

2. The UI is still rough, the aligned parts are not aligned, for example, the text content of the text input field is not centered, the spacing of the adjustment is not adjusted, for example, the x in the upper right corner is too far to the right.

These issues will be addressed when there is plenty of time.

The current effect is:

The source code for this example is located at github.com/botform/bot

In the next article, I’ll show you how to use Laravel, including setting up the environment, using the framework, and interacting with the front end.