“LINE Messaging API” x “Firebase (Cloud Function + Firestore)”

Level of this tutorial: Developer

{Intro}

Hi developers!, According to the passed tutorial I talk about “Get started using LINE Messaging API” for beginner and the steps for getting ready before developing so in this tutorial we will start coding the chatbot making it reply message to the user which has Firebase as a webhook. so let get start!

[หากต้องการอ่านบทความที่มีเนื้อหาคล้ายๆกับในบทความนี้ และเขียนด้วยภาษาไทย ผมเเนะนำบทความนี้เลยครับ เขียนโดย Jirawatee (พี่ตี๋)]

Note: If you don’t know what is LINE Messaging API I suggest you read my “Get started using LINE Messaging API” tutorial in the link below

* What is Firebase?

Firebase is a cloud platform run by Google. They have so many services such as CloudFirestore, Authentication, Cloud functions, etc. and it FREE for the starter but if you want more quota for using their service, you can pay for it.

Now, let scope on Cloud Functions for Firebase, This is the service that allows us to create the online function using JavaScript or TypeScript and you can call it from anywhere. We’ll use this service for creating a webhook to receive the POST Request from LINE Messaging API.

For more detail:

{Preparing our project}

Before anything else let talk about our example project goal and features. We will create a chatbot in LINE Messaging API having the cloud function for firebase as a webhook. Our webhook will have the features to store the chat history and get the customer data from the Firestore Database then reply it back to our user with LINE Messaging API if the user are recognized as our customers. You are allowed to use the code in this tutorial, I will upload full source code to my GitHub, Link is at the bottom of this tutorial.

  • We can develop cloud function as a webhook for LINE Messaging API
  • We can develop our cloud function to connect to the Firestore Database for storing and querying the data
  • We can decode the request sent by LINE Messaging API and get the required data from that request ( In this tutorial we need: userId, text, timestamp)

So let get started!

* Create Firebase Project

First, let go to Firebase home page by follow the link below

Log in with your Google account and then click on “Go to console” button

And then click on “Add project” button

Note: If you have other Firebase Project, it’ll appear in this page as in the picture(In the blank block)

Then type your awsome project name and don’t forget to check “I accept terms of use” and then click Create Project

And it gonna take a few seconds for creating your project and you’ll see this page when your project has been created, Then click Continue and it will automatically redirect you to your Project Console

This is your project console

* Changing Firebase pricing plain

Because we will use Cloud Function for connecting the external network(Connect to LINE Server).In the Spark plan, we cannot use Cloud Function to connect to any external network due to the restriction so we gonna change it to Blaze plan(or Pay as you go) with this plain you can build the cloud function without any restriction and you won be charged if you use all services in the free quota limit.

Next, choose Blaze plain

Note: This gonna require your credit card

Done!. (It may required you to specify your billing account in Google Cloud Project so continue to follow it to the end and back to change your plan to Blaze plan again)

* Setting up Firebase tools

Firebase tool is a CLI used to talk with the Firebase server from your terminal. In this tutorial, we’ll use it for deploying your Cloud Function to Firebase.

Note: You gonna need NodeJS for installing the Firebase tool

Install the Firebase tool by typing this command into your terminal

$ npm install -g firebase-tools

If it doesn’t work, you may need to apply the permission for npm by typing “sudo” at the start of the command

Note: This gonna take sometimes

You can check if Firebase tools is installed correctly by typing this command

$ firebase -V

This will return a version of Firebase Tools. Mine is 7.1.0

* Creating the Firestore Database

Firestore is the NoSQL database which we will use in this project

First, let go to the database tab and then click “Create database” button

We will start our database in the locked mode for improving the database’s security so leave it default.

Next, the Firestore database location. Select the location near your service area for decreasing the latency. ( Mine is asia-east2 )

Once it is created you’ll see this page

{Start developing the Cloud Function}

First, we gonna log in with Google Account in Firebase tools by typing this command and follow the login steps

$ firebase login

Once it done, you’ll see this message

Next, we need to create a folder that will contain our cloud function and helper-files and open your terminal then locate into that folder directory. Then we’ll initialize our firebase project by typing this command

$ firebase init

Next, You’ll see these options which have Database, Firestore, Functions, etc. We gonna select Functions option (Use SpaceBar to select) Then press enter

Then, Choose your project and press enter.

Next, We’ll write this function in JavaScript so choose JavaScript Then press enter.

Next, answer all question like this

Do you want to use ESLint to catch probable bugs and enforce style? — Yes

Do you want to install dependencies with npm now? — absolutely Yes
Note: This will start to install all of the dependencies that you gonna need

Done!. Now let check what we got in our project folder.

|-firebase.json
|-functions
|- node_modules
|- index.js
|- package-lock.json
|- package.json

We’ll get something like this.

* Coding part for CloudFunction

Next, we’ll start creating the Cloud Function. open up the file named index.js in functions folder with your favorite IDE (Mine is Visual Studio Code). You’ll see the inital code like this.

Now we’ll create our Cloud Function called “LineMessAPI” which will recive the POST Request from LINE Messaging API also send our message back to it.

You can specify where your cloud function is going to be deployed near your services area(Mine is asia-east2 = HongKong), This will decrease latency between your bot and cloud function (Make it reply faster). even more, you can specify how much ram using in this function is good for your project (Mine is 1GB).

We’ll use the cloud function URL as the webhook so let deploy it for the first time and grab to URL and config it at LINE Developer console.

You can deploy your cloud function by using this command

$ firebase deploy --only functions
You’ll get the functions URL(This will show up for the first time deploy only, also You may find it in the firebase website in function page)

Note: The cloud function URL will be generated when you deploy the cloud function for the first time, you can get it from the CLI or the firebase website in function page.

Back to our cloud function, When we want to do some reply message back to our user in LINE so we need to do the POST request from our cloud function back to LINE Messaging API so that we need to call the dependency named request (Version ^2.88.0), So let open up the package.json file (Not package-lock.json) then add this decpndency to your cloud function.

package.json

Don’t forget to install your dependency by using this command

$ npm install

Next, let call this dependency in our code like this but let also initialize the firebase-admin for connecting to the Firestore Database

Now let take a look into the example request which our webhook will recieve

{
"destination": "Ua0343aa97924b261da9bd5362039****",
"events": {
"0": {
"replyToken": "29e4fe9d921a430680635a681fa53da0",
"timestamp": "156414582****",
"type": "message",
"message": {
"id": "10281586537***",
"type": "text",
"text": "Hello"
},
"source": {
"type": "user",
"userId": "U1efbc797c7174dd636c047f5ca8e****"
}
}
}
}

Here is the data containing our user information, message, and the replyToken(This will be used for sending the reply back to the user). As you can see this is the JSON formatted data. In this project, we need the text, userId, and timestamp from this data. In nodejs, we can decode it easily like this.

Now, let keep userId, text, and timestamp into the Firestore Database but first let create the collection called chat-history

Next, choose auto-id for document id and just click save.

Back to coding, We will insert our data into this collection by using this command

Now we complete two of our goals, let continue our project

Next, let create another collection called Customer for keeping our customer information (Do the same step as you created the chat-history collection).

Example data.

You might ask, How can I get my userId? — You’ll see.

Then we will check if our user is in the Customer collection by using this command

Next, We’ll create the function for doing the reply message back to the user also specify the header of the request. (We’ll create this function outside of the exports.LineMessAPI)

The function reply_message can be used by passing the 2 data into it. First is replytoken and second is the text you want to reply. Mean that this function can only reply just the text if you want it to reply more message type you need to edit its body.

Next, let fill the code with this function.

Lastly, Don’t forget to return 200 http status code back to LINE Messageing API by using this command

Here is the complete code.

Next, Deploy it by using this command and see the result

$ firebase deploy --only functions

{Done! Let test it out!}

First, Let leave every collection in the database default and send the message to our chat-bot. This is the result.

and let see in the Firestore Database, In chat-history collection

You’ll see the new document contains the chat detail from the user.

Now let grab the userId from this document and then go to Customer collection and then create the new document by using userId as the document name. also create the fields like this (name, surname, nickname)

And then let test sending the message to our chat-bot again

That is. Now you can build your chat-bot using cloud function as a webhook and connect your cloud function for storying or querying the data in the Firestore database…

Here is the full source code on my GitHub:

So that’s all for this topic, Thank you for your reading. This tutorial is taking a bit long time to read because it has so many details to explain. The actual purpose is to make you understand it not to make you just copy and paste the code. so that why this takes a bit long time to read.

If you have the question, Feel free to write it down in the comment, I’ll reply ASAP and also If you like this tutorial please click the handclaps button that will be my encouragement for posing the next tutorial ^^

and as always if I make the mistake about the language please apologize for this. because English is not my primary language but I’ll try my best for sharing my knowledge with other developers in worldwide

Thank you for reading and see you in the next post ^.^)~

Tonnam,
Software Developer.

{Referent}

A normal Thai Student who also a Software Developer iOS, Flutter Developer 📱 | Firebase Developer 🔥 | LINE Developer 🎾