How to paste on PasteBin using WhatsApp?
Tags: whatsapp, twilio, pastebin, netlify
Published: 2021-06-20 16:04:08

#### How would you transfer the links/text sent by your friend on the WhatsApp Smartphone app to the desktop?
The obvious answer is WhatsApp Web, right? Yes, but sometimes WhatsApp web just doesn't load and keeps retrying, especially if you are having a poor internet connection like me 😑. What would you do then? Mailing!? Not a good idea, since you have to copy text, then, open the mail app, paste it and send. Phew!😰 Too many clicks, right?
 
What if you can just forward the text message to a WhatsApp contact and it automatically reflects on your [Pastebin][pastebin] from where you can access your content on the desktop. Isn't this way easier😁 than the previous method (mailing)?
 
This is what we will **learn to build** in this blog.
 
## Table of Contents
---
 
- [Overview](#overview)
- [Twilio WhatsApp Sandbox Setup](#twilio-whatsapp-sandbox-setup)
- [Pastebin Setup](#pastebin-setup)
  + [Getting Developer API Key](#getting-developer-api-key)
  + [Getting Folder Id](#getting-folder-id)
  + [Creating Pastebin User Key](#creating-pastebin-user-key)
- [Configuring end-point URL to handle incoming message by a Netlify Function](#configuring-end-point-url-to-handle-incoming-message-by-a-netlify-function)
  * [Installing Netlify CLI and configuring](#installing-netlify-cli-and-configuring)
  * [Program to integrate Twilio endpoint and Pastebin](#program-to-integrate-twilio-endpoint-and-pastebin)
  * [Hosting on Netlify Functions](#hosting-on-netlify-functions)
- [Adding our just configured end-point URL to Twilio WhatsApp sandbox](#adding-our-just-configured-end-point-url-to-twilio-whatsapp-sandbox)
- [Drawbacks](#drawbacks)
- [Future scope](#future-scope)
- [References](#references)
- [Conclusion](#conclusion)
 
 
 
 
## Overview
---
 
 
![overview.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624075682200/kPtKzrr0E.jpeg)
 
Let's see how this works 👀, you send a WhatsApp message to a specific number, that is Twilio registered number. Upon receiving a message Twilio Sandbox sends a payload to an end-point URL 🔗 we provide. We create an end-point URL using Netlify Functions, on receiving payload, the Netlify function is triggered and a script 📜 is executed in which we call Pastebin API, and paste our message. Also, an acknowledgment ✔ message is sent back to the user number.
 
I have shown below what we want to achieve 🏆 at the end of this blog.<br>
- Send a message to a WhatsApp number.
 
![19.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624099474767/kySv957KC.jpeg)
 
- The message is pasted on the Pastebin site and acknowledgment is returned about the status of pasting.
 
![20.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624099544152/OW-sFPLQS.jpeg)
 
### Tools
 
1. [Twilio Sandbox for WhatsApp][twilioWhatsAppSandbox]
2. [Netlify Functions][netlifyfunctions]
3. [Pastebin API][pastebinAPI]
 
## Twilio WhatsApp Sandbox Setup
---
 
#### What is Twilio?
 
[Twilio][twilio] allows software developers to programmatically make and receive phone calls, send and receive text messages, and perform other communication functions using its web service APIs.
In our case, we will be using Twilio's WhatsApp Sandbox. Let's setup it.
 
 
**Step 1**: Sign up on [Twilio][twilio]
 
**Step 2**: Go to console and create a new account
![1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624078972604/E4X3kk1db.jpeg)
<br>
Give a catchy name to your project account
![2.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624078882684/_Ow0ulSO7.jpeg)
 
 
**Step 3**: Verify your account and answer the questions asked
 
**Step 4**: Go to Try It Out/ Try WhatsApp Tab
![4.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624078827963/xUk053qS0.jpeg)
 
Follow the few steps as instructed by Twilio.
After following the steps, you would be guided to the WhatsApp Sandbox Settings page.
 
![6.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1624079273943/0oIMkF3C_.jpeg)
 
Time for mini-celebrations! 🎉 We have set up Twilio WhatsApp Sandbox successfully!
 
Twilio hits to end-point URL (which we provide later) whenever your Twilio Sandbox number receives a new message. Default end-point URL is configured to reply to you with the default message as shown below.
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624080025773/s3r_drSkf.png)
 
We will come back later to Twilio after setting up the end-point URL to handle incoming messages from the sandbox.
 
## Pastebin Setup
----
We need to get some credentials from Pastebin.
Create a free account on [Pastebin][pastebin].<br>
#### Getting Developer API Key
 
Get your dev key [here](https://pastebin.com/doc_api#1) (API Section) after log in.
 
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624088848020/hAm8jagCR.png)
 
#### Getting Folder Id
 
Create a folder and copy its Id
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624089022019/EaqBRC7SS.png)
 
Open the folder and copy its Id from URL
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624089174111/okHAvyOMw.png)
 
Now we have Developer Key and Folder Id. It's time to create your user key.
 
#### Creating Pastebin User Key
 
Run this curl command in [this](https://reqbin.com/curl) site to get your user key.<br>
Note: Only one key can be active at the same time for the same user. This key does not expire, unless a new one is generated.
 
```php
curl -X POST -d 'api_dev_key=YOUR_DEV_KEY' -d 'api_user_name=YOUR_USERNAME' -d 'api_user_password=YOUR_PASSWORD' "https://pastebin.com/api/api_login.php"
```
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624090051321/g3JI-xI5-.png)
<br><br>
 
 
## Configuring end-point URL to handle incoming message by a Netlify Function
----
 
 
### Installing Netlify CLI and configuring
#### Prerequsite
[NodeJs][nodejs] installed on your system
 
**Step 1**: Create a account on [Netlify][netlify] and a team
 
**Step 2**: Run this command from any directory in your terminal:<br>
```npm install netlify-cli -g```<br>
This installs Netlify CLI globally, so you can run `netlify` commands from any directory.
 
**Step 3**: Run this command to give access of your netlify account to Netlify CLI<br>
`netlify login` <br>
This will open a browser window, asking you to log in with Netlify and grant access to Netlify CLI.
 
### Program to integrate Twilio endpoint and Pastebin
 
Read the comments to understand the code. <br>
📁 Check out complete project files [here][githubrepo]. <br>
 
```Javascript
// To make POST request to Pastebin API
// https://www.npmjs.com/package/axios
const axios = require("axios").default;
 
// To convert incoming URLencoded data to readable format
// https://www.npmjs.com/package/qs
const qs = require("qs");
 
// Keys and Tokens stored in Environment Variables
 
// Twilio Credentials
const twilioAccountSID = process.env.TWILIO_ACCOUNT_SID; // Available on your Twilio Dashboard
const twilioAuthToken = process.env.TWILIO_AUTH_TOKEN; // Available on your Twilio Dashboard
const twilioNumber = process.env.TWILIO_NUMBER; // WhatsApp Sandbox Contact Number
const clientNumber = process.env.CLIENT_NUMBER; // Your registred WhatsApp Number with Twilio
 
// Pastebin Credentials
const pbDevKey = process.env.PASTEBIN_DEV_KEY;
const pbUserKey = process.env.PASTEBIN_USER_KEY;
const pbFolderKey = process.env.PASTEBIN_FOLDER_ID;
 
// Client to send messages
// https://www.npmjs.com/package/twilio
const twilioClient = require("twilio")(twilioAccountSID, twilioAuthToken);
 
// Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method
exports.handler = async (event, context) => {
try {
let dataMap = qs.parse(event.body.toString()); // Payload recieved from Twilio webhook
const content = dataMap.Body; // Message
var pasteTitle = content.slice(0, 50) + "..."; // Title of Paste
 
// Uploading message recieved from Twilio to Pastebin
// Refer Pastebin API for more details - https://pastebin.com/doc_api
const res = await axios({
method: "post",
url: "https://pastebin.com/api/api_post.php",
data: qs.stringify({
api_dev_key: pbDevKey,
api_option: "paste",
api_user_key: pbUserKey,
api_paste_code: content,
api_paste_name: pasteTitle,
api_paste_private: 0, // 0 => Public, 1 => Unlisted, 2=> Private
api_folder_key: pbFolderKey,
}),
headers: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8",
},
});
 
// On sucessfull POST request
var successString = `Pasted Succesfully! at ${res.data}`;
console.log(successString);
 
await replyBack(successString); // Calling Reply Function at Success
 
return {
statusCode: 204,
};
} catch (err) {
// On Failed POST request
var errorString = "There was error => " + err.toString();
console.log(errorString);
 
await replyBack(errorString); // Calling Reply Function at Failure
 
return { statusCode: 500, body: err.toString() };
}
};
 
// Replies to user on WhatsApp with ackowledgement of paste on Pastebin
async function replyBack(msg) {
try {
const a = await twilioClient.messages.create({
from: "whatsapp:" + twilioNumber,
body: msg,
to: "whatsapp:" + clientNumber,
});
console.log(`Reply sent succesfully`);
return 0;
} catch (err) {
console.log("There was error while replying back.. => " + err.toString());
return -1;
}
}
 
 
```
 
Now, let's learn how to host this program on Netlify Functions.
 
### Hosting on Netlify Functions

#### Prerequsite

Code Editor (I am using [VSCode][vscode])
 
**Step 1**: Open a empty folder in VSCode<br>
**Step 2**: Create sub-folder named "functions" under parent folder<br>
**Step 3**: Create a `your_file_name.js` file and paste [this][code] code.<br>
**Step 4**: Run command `npm init` to create *package.json* file. <br>
**Step 5**: Run this command `npm install` , this will install required npm packages locally under folder name *node_modules*<br>
**Step 6**: Run command `netlify init`<br>
Select the team and site name as shown below
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624086831648/MvXI49kzM.png)
 
**Step 7**: Create a file `netlify.toml` in parent directory and paste the following code.<br>
```
[build]
functions = "functions/"
```
Using this config file, netlify can recognize the path to functions.
By now your folder structure should be like below:
```
📦ParentFolderName<br>
┣ 📂.netlify<br>
┃ ┗ 📜state.json<br>
┣ 📂functions<br>
┃ ┗ 📜your_file_name.js<br>
┣ 📂node_modules<br>
┃ ┗ 📜....<br>
┃ ┗ 📜....<br>
┣ 📜.gitignore<br>
┣ 📜netlify.toml<br>
┣ 📜package-lock.json<br>
┗ 📜package.json<br>
 ```
 
**Step 8**: Deploying function to Netlify<br>
Run command `netlify deploy --prod` .
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624091091988/EByBaJTSL.png)
 
**Step 9**: Adding Environmental Variables to Netlify console.<br>
Go to Netlify console -> Your-Site->Site-Settings->Build-&-Deploy->Environment
*https://app.netlify.com/sites/YOUR_SITE_NAME/settings/deploys#environment*
 
Click on Edit Variable and add all necessary variable we used in code. Make sure variable names are same as used in code.
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624091587219/Vl52jD4F2.png)
 
**Step 10**: Run deploy command `netlify deploy --prod` again to update our function with just added enviornment variables.
 
## Adding our just configured end-point URL to Twilio WhatsApp sandbox
---
Go to Netlify Console-> YOUR_SITE -> Functions
 
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624091947438/6HsECpPhT.png)
 
After opening your function tab, copy the end-point.
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624092138361/BeouwgMkb.png)
 
Paste the netlify function end-point in Twilio's WhatsApp sandbox settings and save.
 
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1624092345739/-51eYw7aF.png)
 
----
**That's it!** 🍾🥂 Now, any WhatsApp message sent to Twilio's number will be pasted in your Pastebin account under the folder you mentioned.
 
 
---
## Drawbacks
- Pastebin free account has a restriction on pastes a free account user can do in 24 hrs period. More details at *https://pastebin.com/faq#11a*
- If you try to paste after hitting limits, Pastebin API returns an error with 422 code.
 
## Future scope
- Develop your own Pastebin clone to minimize said drawbacks.
- Explore more about WhatsApp Business API and bypass Twilio.
 
## Conclusion
I implemented this to solve my own problem, hope it solves others' too. I **learned** about **Webhooks**, Hosting on Netlify, and explored Twilio and Pastebin API.
 
## References
 
- https://www.twilio.com/docs/whatsapp/sandbox
- https://pastebin.com/doc_api
- https://docs.netlify.com/functions/overview/
- https://www.youtube.com/watch?v=41NOoEz3Tzc (Webhook tutorial)
 
---
## Thank you :)
Hit me up, if you need any help implementing this.
 
#### Note:
This is my first blog. I will be very happy to get your feedback and improve myself for the next blog.

Original Blog at [Hashnode](https://ajaygalagali.hashnode.dev/how-to-paste-on-pastebin-using-whatsapp)
 
*See you in next blog 👋*
 
 
 
 
 
 
 
 
 
[pastebin]:https://pastebin.com/
[twilio]:https://www.twilio.com/
[netlify]:https://www.netlify.com
[netlifyFunctions]:https://www.netlify.com/products/functions/
 
[twilioWhatsAppSandbox]:https://www.twilio.com/docs/whatsapp/sandbox
[pastebinAPI]:https://pastebin.com/doc_api
 
[vscode]:https://code.visualstudio.com/download
[nodejs]:https://nodejs.org/
[code]:#program-to-integrate-twilio-endpoint-and-pastebin
[env]:https://docs.netlify.com/configure-builds/environment-variables/
[githubrepo]:https://github.com/ajaygalagali/WhatsBin