Writing Messenger Bot in Dart

AADARSHA DHAKAL
5 min readJan 10, 2021

--

You may have used Dart language while writing mobile apps using flutter, or at least heard about it. Very few of you might also have heard about Dart being used in frontend by Google internally in products like Google Ads. Do you know that we can also use Dart on the server side? To show you the demonstration of Dart on the server, here I am going to create a messenger chat bot using Dart.

Getting things ready

First and foremost you should have these things with you to get started.

  1. A Laptop or Desktop
  2. Good Internet Connection
  3. Dart SDK installed in your device ( Install it from here if not: https://dart.dev/get-dart )
  4. Ngrok installed in your device ( Install it from here if not: https://ngrok.com/download )

Once you have the basics requirements fulfilled. You can move to the next step.

Creating Facebook App

Let’s begin by creating a Facebook App. To create a Facebook app, you must have a developer account which you can create for free here: https://developers.Facebook.com/

Once you have created your Facebook app, we have to connect the app to your Facebook page. If you don’t have a Facebook page then you can create one.

Now, In the app dashboard we have to set up a couple of products. First you have to set up Messenger product in your app.

After that we have to link our Facebook page to our app by clicking on the Add Pages button under the Access Token Section.

We also have to set up webhooks but we’ll do that at last.

For now, we can move to the next step.

Creating A Dart Project

To create a simple Dart project, you can run this command in the terminal.

dart create <project-name>

This will create a project folder, which you can open with your favorite code editor. Keeping tooling and support in mind, I will recommend you to use VS code.

Now before we start writing code, we have to install a couple of dependencies. For that open your pubspec.yaml file and update the dependencies list with these entries.

shelf_router
dio

We’ll use shelf_router package for writing our server code and dio packages for sending http requests.

Now, run this command in terminal to fetch dependencies.

pub get

Coding Time

Now comes the most exciting part of this tutorial. Finally we can now write some Dart codes.

Open the <project-name>.dart file inside the bin directory of your project. Now, first and foremost we have to import the packages we’re going to need.

import 'dart:convert';
import 'dart:io';
import 'package:bot/keys.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;
import 'package:dio/dio.dart' as don;

Then inside the main method, which is the entry point of our program, write a few lines to create a Router object that comes from the shelf_router package and set up a simple web server.

var bot = Router();var server = await io.serve(bot,‘127.0.0.1’,int.parse(Platform.environment[‘PORT’]) ??8080);

Now, we have to create an endpoint that accepts POST and GET requests. Let’s begin by writing a GET request handler, which will be used by Messenger Platform to verify the webhook which we’ll set up later.

bot.get(‘/’, (Request request) {
if (request.url.queryParameters[‘hub.verify_token’] == <VERIFY_TOKEN>) {
return Response.ok(request.url.queryParameters[‘hub.challenge’]);
} else {
return Response.ok(‘Hello! You are not authorized’);
}
});

Here, <VERIFY_TOKEN> can be any string. But you have to remember this because we need this while setting up the web hook.

Now, lets create a POST request handler to handle Message Received Events from the webhook.

bot.post(‘/’, (Request request) async {var payload = json.decode(
await request.readAsString(),
);
var data = payload[‘entry’][0][‘messaging’];for (var msg in data) {
var text = msg[‘message’][‘text’];
var sender = msg[‘sender’][‘id’];

var reply = processMessage(text);

await sendMessage(
reply: reply,
recipient: sender,
);
}
return Response.ok(‘Reply Sent!’);});

This handler parses the event data and gets the sender id and the message text from it. Then we process the message text in the processMessage() function. The processMessage() function will return the reply text that we are going to send back to the Messenger Platform using the sendMessage() function.

So let’s create a processMessage() function.

String processMessage(String text) {
String reply;
switch (text.toLowerCase()) {
case ‘hello’:
reply = ‘Hi! How can I help You ?’;
break;
case ‘how can i contact you?’:
reply = ‘You can contact me via my email:aadarshadhakalg@gmail.com!’;
break;
default:
reply = ‘I’ll reach out to you soon! Thank you for messaging.’;
}return reply;}

And, sendMessage() function,

Future<void> sendMessage({String reply, String recipient}) async {var dio = don.Dio();try {
var requestData = {
‘recipient’: {‘id’: recipient},
‘message’: {‘text’: reply},
};
var response = await dio.post(‘https://graph.facebook.com/v9.0/me/messages?access_token=<PAGE_ACCESS_TOKEN>', data: json.encode(requestData), options: don.Options(
headers: {
‘Content-Type’: ‘application/json’,
},
),
);
if (response.statusCode == 200) {
print(‘Success’);
} else {
print(response.statusCode);
}
} catch (e) {
print(e.toString());
}
}

Here, we are sending a POST request to the Messenger Platform using the dio package. We have to pass the access_token query parameter. You can generate PAGE_ACCESS_TOKEN by clicking on the Generate Token button in the app dashboard under messenger settings.

Now, we have completed writing the codes.To start our server in the terminal run the following command.

dart bin/<project-name>.dart

This will start a local server at port 8080. To make it accessible to the Messenger Platform we have to use ngrok tool. it allows us to expose our local web server running on our local machine to the internet.

Run this command in terminal and open the https version of the link provided by the ngrok,

ngrok http 8080

Okay, at last we have to set up a webhook in our Facebook app. To do so, go to the app dashboard, to messenger settings and under the webhook section , click on Add Callback URL and paste the url you have copied from the previous step. Also you have to provide the VERIFY_TOKEN, remember while we were writing the GET method handler we used a string, it should be the same.

Click on the Verify and Save button. If you are doing everything correctly, you will be able to see Add Subscription button inside the Webhook section. Click on that and select the message checkbox and save it.

Thank you for making up to last. I hope this was not boring and you love it.

--

--