This walkthrough describes how to create your own bot with Facebook Messenger Platform in few easy steps and how to run it on your EC2 (Amazon Web Service).
- An AWS account
- A domain name (in this tutorial : yourdomainname.com)
First of all, you need to create an EC2 instance. On Amazon Web Service, select EC2 :
In the left menu, choose "Instances" :
On the Instance page, clic on "Launch Instance" on the top menu :
"Step 1: Choose an Amazon Machine Image (AMI)" : You should select "Ubuntu Server 14.04 LTS (HVM), SSD Volume Type - ami-f95ef58a" :
"Step 2: Choose an Instance Type" : Verify that the instance t2.micro is selected and clic on "Review and launch"
"Step 7: Review Instance Launch" : Clic on "Launch" (Right bottom of the page)
If you already used AWS, you already have a key pair so you can use it and for finish, clic on "Launch Instance"
If you never used AWS, you should create a new key pair : Enter the name of your key pair (can be what you want) and clic on "Download Key Pair" and for finish, clic on "Launch Instance"
Now, you should have this page : Clic on "View Instances" (Right bottom of the page)
A new instance is launching :
After few minutes, when the EC2 instance is ready, you should see this :
If you clic on it, you will see all the details about the EC2 Instance.
In this tutorial, you need your own domain name. Mine is guillaumeteillet.fr
For this step, we will use a new service of AWS called "Route 53" :
In the left menu, select "Hosted zones" :
Then clic on "Create Hosted Zone" :
Enter your domain name (mine is guillaumeteillet.fr) and then clic on "Create" :
Route 53 has created two Record Sets in your Hosted Zone : We will need the 4 DNS (red square on the picture)
Now, change the DNS Name of your domain name (My registrar is OVH so perhaps the procedure is a bit different) :
Before any change, the DNS name was :
The registrar need some time to change the DNS of your domain name :
After few minutes, the 4 DNS of your domain name should be active :
Now, go back on AWS, choose EC2 and then choose "Instances" on the left menu. We need the public IP, mine is 54.171.135.46, copy this ip.
Now, go to "Route 53" :
Select "Hosted Zones" in the left menu, clic on your domain name : You will arrived on the list of the Record Set.
Clic on "Create Record Set" :
We will now create two record set. First, keep the field name empty and in the field value, paste the public ip of your ec2 instance. For the type of the record set, choose A - IPV4 Address
Next, in the field name, enter "www", in the field value, paste the public ip of your ec2 instance. For the type of the record set, choose A - IPV4 Address.
Now, you should wait few minutes. You can use this tool WhatsmyDNS to see if your domain name is now using the good ip address : Enter your domain name (mine is guillaumeteillet.fr) and clic on "Search". If the IP Address of your EC2 Instance appears, it means your domain name is now using the good ip address, you can continue this tutorial.
On Amazon Web Service, select EC2, Instances (in the left menu), select your instance and clic on "Connect" (in the top menu).
Copy the ssh command. Mine is "ssh -i "Guillaume.pem" [email protected]". Open a terminal, go to the folder that contains the key pair and paste the ssh command.
Now your are connected on your EC2 Instance.
Run this on your EC2 instance :
sudo su
apt-get update
apt-get install -y git
git clone https://github.com/guillaumeteillet/create-your-own-facebook-messenger-bot-platform-ec2-aws.git
cd create-your-own-facebook-messenger-bot-platform-ec2-aws
apt-get install -y npm
npm install
npm install forever --global
curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
apt-get install -y nodejs
apt-get install -y nano
apt-get install -y apache2
cd /etc/apache2/sites-available
nano yourdomainname.com.conf
The text editor nano opens, copy and paste this :
<VirtualHost *:80>
ServerName www.yourdomainname.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Where "www.yourdomainname.com" should be replace by your own domain name.
Save your file : Ctrl + X + S, then press y and enter
In the same directory, run this on your EC2 instance :
a2ensite yourdomainname.com.conf
You should have this return :
Enabling site yourdomainname.com.
To activate the new configuration, you need to run:
service apache2 reload
So now, you have to reload apache2. Just run this command :
service apache2 reload
You should have this return :
* Reloading web server apache2 *
5. HTTPS with Let's encrypt
First, we will open all ports of our ec2 temporarly. On Amazon Web Service, select EC2, Instances (in the left menu), select your instance. In the Description Area, clic on the "security group"
You will arrive on the security group page with only one security group. Clic on "Inbound"
Clic on "Edit"
Clic on "Add Rule"
Then, select "All Trafic" for the type and "Anywhere" for the source. Save the changes.
Now, run this on your EC2 instance :
cd
sudo su
git clone https://github.com/letsencrypt/letsencrypt
cd letsencrypt
./letsencrypt-auto
Facebook required a https Webhook, so we will use let's encrypt to get our ssl certificate. When ./letsencrypt-auto is ready (few minutes), you will see this :
As you can see, my domain "www.guillaumeteillet.fr" is selected ([*]). You can select/unselect domain with space bar, navigate with up and down. When the domain name for which you want a SSL certificate is selected, press Enter.
Let's encrypt ask your email address to notify you when the certificate expires. Enter a valid email and press Enter.
Press Enter again when let's encrypt ask you if you read the Terms.
Then select "Easy" and press Enter.
Congratulations ! Your domain have now a ssl certificate !
Now open your browser and try to go to https://www.yourdomain.com : you should see the Apache Default Page.
Now you can remove the "All Trafic" option in your EC2 Instance. On Amazon Web Service, select EC2, Instances (in the left menu), select your instance. In the Description Area, clic on the "security group".
You will arrive on the security group page with only one security group. Clic on "Inbound"
Clic on "Edit"
Clic on the remove icon and save the changes.
Now you're ready to go to Facebook developers panel, create or use existing app (and page) and setup its' webhooks.
Clic here to create your facebook page if you already have a facebook page, you can skip this step. Follow the instruction of facebook : i will not give you details here, it's a very basic facebook page. If you don't know how to create your facebook page
Clic here to create your facebook app
Enter the name of your app and then press "Create New Facebook App ID".
Enter your email address, choose a category and press "Create App Id".
Clic on "Skip Quick Start"
You will be redirect on the "Dashboard Page" of the app.
Go back in your terminal (with the EC2 connection opened) and in the "create-your-own-facebook-messenger-bot-platform-ec2-aws" folder, run this command :
nano index.js
The nano text editor will open. On line 11, you will see 5 variables :
// Variables
let pageToken = "";
const verifyToken = "";
const privkey = "";
const cert = "";
const chain = "";
**For the variable "pageToken" : **
Go to the Facebook App that you just created : Facebook Developper website. Clic on My Apps > "Your App"
You will arrive on the dashboard of your app. On the left menu choose Messenger.
Clic on "Get Started".
Select the page you just created :
A new tab opens : Clic two times on "Okay".
The page closes and you return to the previous page. The Page Access Token will be generated for your facebook page. Copy it and Paste it in the pageToken variable in index.js (on your EC2 Instance).
**For the variable "verifyToken" : **
Enter a string that will be used by facebook to identify your bot. This can be anything. I decide to set this variable with the string "my_first_messenger_bot".
For the variable "privkey" :
You need to set this variable with the path of the private key of the ssl certificate. If you follow this tutorial with let's encrypt, the path should be : "/etc/letsencrypt/live/yourdomainname.com/privkey.pem"
For the variable "cert" :
You need to set this variable with the path of the certificate of the ssl. If you follow this tutorial with let's encrypt, the path should be : "/etc/letsencrypt/live/yourdomainname.com/cert.pem"
For the variable "cert" :
You need to set this variable with the path of the chain file of the ssl. If you follow this tutorial with let's encrypt, the path should be : "/etc/letsencrypt/live/yourdomainname.com/chain.pem"
Now, save your file : Ctrl + X + S, then press y and enter
You will open the 55555 port of your EC2 Instance. On Amazon Web Service, select EC2, Instances (in the left menu), select your instance. In the Description Area, clic on the "security group"
You will arrive on the security group page with only one security group. Clic on "Inbound"
Clic on "Edit"
Clic on "Add Rule"
Then, select "Custom TCP Rule" for the type, "55555" for the Port Range and "Anywhere" for the source. Save the changes.
Go back in your terminal (with the EC2 connection opened) and in the "create-your-own-facebook-messenger-bot-platform-ec2-aws" folder, run this command :
node index.js
If you have everything configured properly, you should have this in the terminal :
App is ready on port 55555
Now your bot is running. Open a browser and enter this url : https://www.yourdomainname.com:55555/webhook . You shoud have this in your browser :
Error, wrong validation token
Now, we will see how to run your bot in background. First, You can stop the process of your bot with Ctrl + C and after you should run this command :
forever start index.js
You should have something like this in the terminal :
warn: --minUptime not set. Defaulting to: 1000ms
warn: --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info: Forever processing file: index.js
Run this command :
forever list
You should have something like this in the terminal :
info: Forever processes running
data: uid command script forever pid id logfile uptime
data: [0] mgMM /usr/bin/nodejs index.js 31035 31040 /root/.forever/mgMM.log 0:0:9:52.300
With this command, you can get the path of the logfile. Now, you will "cat" the logfile to check if everything is running well. In my example, I will run "cat /root/.forever/mgMM.log"
cat /root/.forever/mgMM.log
You should have something like this in the terminal :
App is ready on port 55555
Your webhook is ready ! If you want to stop your bot, you can get the uid of your bot by running :
forever list
======
info: Forever processes running
data: uid command script forever pid id logfile uptime
data: [0] mgMM /usr/bin/nodejs index.js 31035 31040 /root/.forever/mgMM.log 0:0:9:52.300
And then, run this command (mgMM is ths MY uid, so use your uid !)
forever stop mgMM
Now lets configure the Facebook app. Before starting this step, your bot should run on port 55555.
Go to the Facebook App that you just created : Facebook Developper website. Clic on My Apps > "Your App"
You will arrive on the dashboard of your app. On the left menu choose Messenger.
Clic on "Setup Webhook" :
Complete the different field :
Callback URL : https://www.yourdomainname.com:55555/webhook (Mine is https://www.guillaumeteillet.fr:55555/webhook)
Verify Token : The "verifyToken" variable you set previously. (Mine is my_first_messenger_bot)
Subscription Fields : Check all the options.
Save the configuration by clic on "Verify and Save"
If everything is configured correctly, you should see this :
Open a new terminal and run this command :
curl -i -H "Content-Type: application/json" -X POST -d "{\"verifyToken\": \"YOUR VERIFY TOKEN\", \"token\": \"YOUR PAGE ACCESS TOKEN\"}" https://www.youdomainname.fr:55555/token
Of course, you should replace YOUR VERIFY TOKEN and YOUR PAGE ACCESS TOKEN by your own values (pageToken and verifyToken in the index.js)
The answer of the server should be something like this :
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/plain; charset=utf-8
Content-Length: 2
ETag: W/"2-4KoCHiHd29bYzs7HHpz1ZA"
Date: Fri, 22 Apr 2016 15:42:23 GMT
Connection: keep-alive
OK
Then run this command :
curl -ik -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=YOUR PAGE ACCESS TOKEN"
Of course, you should replace YOUR PAGE ACCESS TOKEN by your own value (pageToken in the index.js)
The answer of the server should be something like this :
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Pragma: no-cache
Cache-Control: private, no-cache, no-store, must-revalidate
Facebook-API-Version: v2.6
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Content-Type: application/json; charset=UTF-8
X-FB-Trace-ID: Fe0XhGA9/Rb
X-FB-Rev: 2299175
X-FB-Debug: 3iXH8FfFvQoNYYpVTDZ83cw0q1SxArRbwCbN1lO8EPIUPdtgAy0Z8hqEXULV5abdsQSJBrdtJzpg4zMBZ/Yr1A==
Date: Fri, 22 Apr 2016 15:50:36 GMT
Connection: keep-alive
Content-Length: 16
{"success":true}
Now, your basic bot is ready and running ! Congratulations ! :)
Go to your Facebook Page and clic on "Message".