每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg

2018年6月14日:开源日报第98期

今日推荐开源项目:《从 Python 开始的机器学习 Machine learning basics 》GitHub链接

推荐理由:这个项目主要是介绍如何使用纯 Python 实现基本的机器学习算法,虽然这可能并不是最快的方法,但是可以让读者更好的理解算法和它们的结构。推荐刚刚开始学习机器学习算法的朋友们一读。

2018年6月14日:开源日报第98期

今日推荐英文原文:《Build A Chat App With Sentiment Analysis Using Next.js》作者:Brandon Morelli

原文链接:https://codeburst.io/build-a-chat-app-with-sentiment-analysis-using-next-js-c43ebf3ea643

推荐理由:这篇文章制作一个简单的实时聊天程序的教程,同时还加入了通过词语进行情感分析的功能。虽然情感分析不算是太万能,不过也当作一个Next.js的试手也成。

Build A Chat App With Sentiment Analysis Using Next.js

Realtime applications have been around for quite a long time as we can see in contexts such as multi-player games, realtime collaboration services, instant messaging services, realtime data analytics tools, to mention a few. As a result, several technologies have been developed over the years to tackle and simplify some of the most challenging aspects of building apps that are sensitive to changes in realtime.

In this tutorial, we’ll build a very simple realtime chat application with sentiments. With sentiment analysis, we will be able to detect the mood of a person based on the words they use in their chat messages.

Prerequisites

Before you begin, ensure that you have Node and npm or Yarn installed on your machine. Here is a run-down of the core technologies we will be using.

  1. Next.js — A framework for building server-side rendered(SSR) React applications with ease. It handles most of the challenges that come with building SSR React apps.
  2. Pusher — Pusher is a technology for building apps with varying realtime needs like push notifications and pub/sub messaging. It is the engine behind the realtime ability of our comments widget.
  3. Sentiment — Sentiment is a module that uses the AFINN-165 wordlist and Emoji Sentiment Ranking to perform sentiment analysis on arbitrary blocks of input text.
  4. React — A very popular JavaScript DOM rendering framework for building scalable web applications using a component-based architecture.
  5. A few other libraries will be used as we will see in a moment. Also ensure that you have Node installed on your machine.

Installing dependencies

Create a new directory for the application and run the following command to install the required dependencies for the app.

Setting environment variables

Create a new application on your Pusher Dashboard to get your application credentials. Create a .env file in the root directory of your application and add your application credentials as follows.

Ensure that you use the same variable names as specified in the above snippet. We will make reference to them at several points in our code.

Next create a Next.js configuration file named next.config.js in the root directory of your application with the following content:

Since Next.js uses Webpack in the background for module loading and bundling, we are simply configuring Webpack to be able to provide the environment variables we have defined and make them available to our React components by accessing the process.env object.

Getting started

Setting up the server

We will go ahead to set up a simple server using Next.js to wrap an Express application server. We will also load the necessary middlewares for the Express server and then we will configure Pusher using the credentials we added to our environment variables.

Create a server.js file in the root directory of your application and add the following code snippet to it to set up the server:

Modify npm scripts

Finally, we will modify the "scripts" section of the package.json file to look like the following snippet:

We have gotten all we need to start building our app components. If you run the command npm run dev on your terminal now, it will start up the application server on port 3000 if it is available. However, nothing happens on the browser yet, because we have not built any index page component. Let’s start building the app components.

Building the index page

Next.js requires that you create the page components of your app in a pages directory. We will go ahead and create a pages directory in our app root directory and create a new index.js file inside it for the index page of our application.

Before we add content to the index page, we will build a Layout component that can be used in our app pages as a kind of template. Go ahead and create a components directory in your app root. Create a new Layout.js file inside the just created components directory with the following content:

Here, we try not to do so much. We are simply using the next/head component to add meta information to the <head> of our pages. We have also added a link to the Bootstrap CDN file to add some default styling to our app. We are also setting the page title dynamically from props and rendering the page contents using {props.children}.

Now let’s go ahead and add content to the index.js file we created earlier:

We created a component IndexPage for the index page of our app. We initialized the state of the component with an empty name property. The name property is meant to contain the name of the currently active user.

We also added an input field to receive the name of the user, if no user is currently active. Once the input field is filled and the enter or return key is pressed, the name supplied is stored in state.

If we test the app on our browser now, we should see a screen that looks like the following screenshot:

2018年6月14日:开源日报第98期

Building the Chat component

We will go ahead and build the chat component. Create a new Chat.js file inside the components directory and add the following content:

Here is a simple break down of what we’ve done:

  1. We first initialized the state to contain an empty chats array property. This chats property will be populated with chat messages as they keep coming. When the component mounts, we set up a Pusher connection and channelsubscription inside the componentDidMount() lifecycle method.
  2. You can see that we are subscribing to a Pusher channel called chat-room for our chat application. We are then binding to the new-message event on the channel, which is triggered when a new chat message comes in. Next, we simply populate the state chats property by appending the new chat.
  3. Also, on the componentDidMount() method, we are binding to the connected event on the Pusher client, when it is freshly connected, to fetch all the chat messages from history by making a POST /messages HTTP request using the axios library. Afterwards, we populate the state chats property with the chat messages received in the response.
  4. The Chat component is not completed yet. We still need to add a render() method. Let’s do that quickly. Add the following snippet to the Chat component class.

As seen in the render() method, we require an activeUser prop to identify the currently active user. We also rendered a <textarea> element for entering a chat message. We added an onKeyUp event handler to the <textarea> to send the chat message when you press the enter or return button.

On the handleKeyUp() event handler, we construct a chat object containing the user sending the message (currently active user), the message itself, and then the timestamp for when the message was sent. We clean up the <textarea>and then make a POST /message HTTP request, passing the chat object we created as payload.

Let’s add the Chat component to our index page. First, add the following line to the import statements in the pages/index.js file.

Next, locate the render() method of the IndexPage component. Render the Chat component in the empty <section>element. It should look like the following snippet:

You can reload the app now in your browser to see the changes.

Defining the messaging routes

For now, nothing really happens when you try to send a chat message. You don’t see any message or any chat history. This is because we have not implemented the two routes we are making requests to.

We will go ahead and create the /message and /messages routes. Modify the server.js file and add the following just before the call to server.listen() inside the then() callback function.

First, we created a kind of in-memory store for our chat history, to store chat messages in an array. This is useful for new clients that join the chat room to see previous messages. Whenever the Pusher client makes a POST request to the /messages endpoint on connection, it gets all the messages in the chat history in the returned response.

On the POST /message route, we are fetching the chat payload from req.body through the help of the body-parsermiddleware we added earlier. We then use the sentiment module to calculate the overall sentiment score of the chat message. Next, we reconstruct the chat object, adding the sentiment property containing the sentiment score.

Finally, we add the chat to the chat history messages, and then trigger a new-message event on the chat-room Pusher channel, passing the chat object in the event data. This does the real time magic.

We are just a few steps away from completing our chat application. If you load the app on your browser now and try sending a chat message, you don’t see any feedback yet. That’s not because our app is not working. It is working perfectly. It’s simply because we are not yet rendering the chat messages on the view. Let’s head on to that and finish this up.

Displaying the chat messages

Create a new ChatMessage.js file inside the components directory and add the following content to it.

The ChatMessage component is a very simple component requiring two props: message for the chat message and position for the positioning of the message – either right or left. This is useful for positioning the messages of the active user on one side and then the messages of other users on the other side as we would do in a moment.

Finally, we will modify the components/Chat.js file to render the chat messages from the state. Make the following changes to the Chat component.

First add the following constants before the class definition of the Chat component. Each constant is an array of the code points required for a particular sentiment emoji. Also ensure to import the ChatMessage component.

Then, add the following snippet between the chat header <div> and the chat message box <div> we created earlier in the Chat component.

Let’s try to understand what this code snippet is doing. First, we are going through each chat object in the state chatsarray property. We check if the sender of the message is the same as the currently active user and use that to determine the position of the displayed chat message. As you can see, the active user’s messages will appear on the right.

We also use the sentiment score in the chat object to set the mood of the user while typing the message to either happy, sad or neutral using the earlier defined constants.

We conditionally render the name of the user before the chat message based on one of the following conditions being met.

  1. isFirst – the current chat message is the first in the list
  2. !inSequence – the current chat message directly follows a message from another user
  3. hasDelay – the current chat message has a delay of over 1 minute from the previous message of the same user
  4. Also notice how we are using the [String.fromCodePoint()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint) method added in ES6 to get the emoji from the code points we defined in our constants earlier.

We are finally done with our chat app. You can go ahead to test what you have built on your browser. Here are some screenshots showing a chat between 9lad, Steve and Bob.

9lad

2018年6月14日:开源日报第98期

Steve

2018年6月14日:开源日报第98期

Bob

2018年6月14日:开源日报第98期

Conclusion

In this tutorial, we have been able to build a very simple chat application with chat sentiment using Next.js (React), Pusher and Sentiment Node module. While this tutorial focuses on just the basics, there are a lot of advanced stuffs you can do to make a better chat app. You can check the source code of this tutorial on GitHub.

Do check the documentation for each technology we used in this project to learn more about other ways of using them. I hope that this tutorial is helpful for you!


每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;微博:https://weibo.com/openingsource;电报群 https://t.me/OpeningSourceOrg