Get Your Daily Dose of BTS with the Twilio API!
Tags: javascript, twilio, beginners, twitter
Published: 2020-12-08 04:56:14

### Introduction

This is for all of my busy🐝  ARMYs out there who want to support their favorite artists but just can't find the time to scroll endlessly through social media apps to keep up. We all know BTS is always coming out with new music, videos, guest appearances are more.

We're going to learn how to use the Twilio API to enhance the ARMY experience and get fun BTS related Tweets sent directly to us every day!

![https://media.giphy.com/media/M9TGCBNBeL0ajWElkt/giphy.gif](https://media.giphy.com/media/M9TGCBNBeL0ajWElkt/giphy.gif)

### Getting Prepped

Before starting, we want to download a few packages required for this app.

- Install Node and npm: [https://www.npmjs.com/get-npm](https://www.npmjs.com/get-npm), [https://nodejs.org/en/download/](https://nodejs.org/en/download/)
- Run the following commands to install Twilio, Twit (for the Twitter API), and Cron

```bash
npm install twilio
npm install twit
npm install cron
```

### Setting up the Twitter API with Twit

Let's start with creating our Individual Developer Account on Twitter, which will allow us to get access to the Twitter API. First, log into twitter on the computer and navigate to the [developer](https://developer.twitter.com/en/application/use-case) website. Once logged in, it will ask us some questions to guide us through the process of setting up the account. If you're not sure which option to select, choose "Exploring the API" under the "Hobbyist" column and click "Next."

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/j6i39borl1ou8g82s4ax.png)

We will need to make sure we have a valid phone number and email address associated with the account. Once you are done answering questions to verify your identify, you can submit the form and it will ask you for a unique application name - you can call it anything. In this case, I will name mine `BTweetS`.

Once we're on your Overview page, we can click on the Keys and Tokens button to get access to our API keys.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gnhsuix6tb40n2pu8qfn.png)

For the next part, I followed Shajia Abidi's awesome tutorial called ["Automate Your Job Search with Twitter and Twilio Programmable SMS"](https://www.twilio.com/blog/automate-your-job-search-with-twitter-and-twilio-programmable-sms) that recommended using the [Twit](https://www.npmjs.com/package/twit) npm package to simplify using the Twitter API.

The [Twit documentation](https://www.npmjs.com/package/twit) does a great job of explaining how to use it make get and pull requests.

### Setting up the Twilio API to get access keys

Now that we have the tweets we're looking for, we need the help of the Twilio API to actually send over those tweets to us as a text. We'll need to create a [Twilio account](https://www.twilio.com/console).

When you first login, it will ask you to save your keys and tokens somewhere safe. Once you have your account all set up, you can go into the [Twilio Console](https://www.twilio.com/console), click on Project info and get access to your account keys.

### Coding

Before we start, let's take a short dance break with BTS.

![https://media.giphy.com/media/Y0gq8Uji6VRblCMwrt/giphy.gif](https://media.giphy.com/media/Y0gq8Uji6VRblCMwrt/giphy.gif)

Now that we're all pumped up and ready to code, let's start with opening a terminal and creating a directory to hold all of your files related to this project. For this you can run the following commands:

- Locate the Documents folder: `cd ~/[path]/Documents`
- Create a new folder for this project called btweets: `mkdir btweets`
- Enter the new btweets directory: `cd btweets`
- Create an empty file called index.js for the code: `touch index.js`

### Connecting to the Twitter API to find tweets

Add the following lines of code to your index.js file. The first line requires the Twit package for your program.

```jsx
const Twit = require('twit');
```

Once you have done that, you can start creating variables to hold your keys and numbers which will be called in your get request.

```jsx
...

// Your Twilio number
var from_number = '+12345678900';
// Your phone number
var to_number = '+15550000000';

// 
var T = new Twit({
  consumer_key: '[insert_your_consumer_API_key_here]',
  consumer_secret: '[insert_your_consumer_API_secret_key_here]',
  access_token: '[insert_your_access_token_here]',
  access_token_secret: '[insert_your_access_secret_token_here]',
});
```

Add the following line below your code and run your app by using the `node index.js` command in the terminal.

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	// Print tweet to console
  console.log(data);
})
```

This line searches tweets (`search/tweets`) and finds one (`count: 1`) with bts in the text (`q: 'bts'`)

When we run the code we should receive a random tweet with "bts" in the console and it should look something like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1xr3dqoe10k37b7tax5m.png)

If you want to change the type of tweet you receive, check out the [Twit documentation](https://www.npmjs.com/package/twit).

### Connecting to the Twilio API to receive texts

Now that we have confirmed that we are receiving tweets, we need to find a way to edit the callback function so that we can use the Twilio API and receive the tweet as a text. Within the function, we need to create const variable that will hold our Account SID and Auth Token from Twilio and instantiate the Twilio client as shown below:

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	...

  const accountSid =  '[insert your account SID here]'
  const authToken  =  '[insert your auth token here]'
  const client = require('twilio')(accountSid, authToken);

  ...
})
```

Next we will save the `statuses` array so that we can get information on each tweet. Recall in the earlier stage, we set `count` to 1, meaning we would only receive one tweet. In this case, `data.statuses[0]` refers to the first tweet, `data.statuses[1]` would refer to a second tweet if count was greater than 1. In our case, `data.statuses[1]` would be undefined.

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	...

  const statuses = data.statuses;

})
```

Next, we can [send a message](https://www.twilio.com/docs/sms/send-messages#monitor-the-status-of-your-message) to our phone by using `client.message`. Add the following code below:

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	...

  client.messages
     .create({
       body: `Test`,
       from: from_number,
       to: to_number
     })
     .then(message => console.log(message.sid));
})
```

Run the app and make sure you receive a text to the number you saved in the `to_number` variable earlier.

Now we need to use the Twilio API to send the tweet itself. When we ran `console.log(data);`, we printed a bunch of information from the tweet into console. We can use this information to determine how to link the tweet into our text message.

`id_str` holds the ID of the tweet, the user struct saves a bunch of info regarding the user and the retweeted_status struct saves a bunch of info about the engagement of the tweet. To create the link for the tweet, we need the base structure of the link. All tweets are linked in the format: `https://twitter.com/[user.screen_name]/status/[id_str]`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zd5c1jls65ictcnjhzxq.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/98h3x9xplf2qzv9c9a8m.png)

We know that `data.statuses[0]` gives us info on the first tweet, thus we can get the link with:

`https://twitter.com/${data.statuses[0].user.screen_name}/status/${data.statuses[0].id_str`

To personalize my text, I want to also receive information regarding the user and the popularity of the tweet, so my final message will look like this:

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	...

  client.messages
     .create({
       body: `Here's your BTweetS for the day from ${data.statuses[0].user.screen_name}: https://twitter.com/${data.statuses[0].user.screen_name}/status/${data.statuses[0].id_str} with ${data.statuses[0].retweeted_status.retweet_count} retweets and ${data.statuses[0].retweeted_status.favorite_count} likes!`,
       from: from_number,
       to: to_number
     })
     .then(message => console.log(message.sid));
})
```

In case something goes wrong in the process of getting a tweet and sending it as a message, we want to make sure that the receiving number is aware that something went wrong. For this, we can put the client message into a try-catch block, which looks like this:

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	

  try {
    ...

  } catch(e){
     ...
   }
})
```

The try block will attempt to send the tweet and will trigger a different response if something goes wrong. Your final try-catch statement should look like this:

```jsx
...

T.get('search/tweets', { q: '@bts_twt', count: 1 }, async (err, data, response) => {
	...

  try {
    const statuses = data.statuses;

  client.messages
     .create({
       body: `Here's your BTweetS for the day from ${data.statuses[0].user.screen_name}: https://twitter.com/${data.statuses[0].user.screen_name}/status/${data.statuses[0].id_str} with ${data.statuses[0].retweeted_status.retweet_count} retweets and ${data.statuses[0].retweeted_status.favorite_count} likes!`,
       from: from_number,
       to: to_number
     })
     .then(message => console.log(message.sid));

  } catch(e){
     client.messages
     .create({
       body: `Oops! something is wrong - ${new Date().toLocaleString()}`,
       from: from_number,
       to: to_number
     })
     .then(message => console.log(message.sid));
   }
})
```

We're almost done! At this point, when we the run the app we receive a text message with a random tweet related to or mentioning BTS.

![https://media.giphy.com/media/wsiXGi5jUnyY9ZnJPD/giphy.gif](https://media.giphy.com/media/wsiXGi5jUnyY9ZnJPD/giphy.gif)

### Automating for Daily Tweets using Cron:

Require the cron package by adding the following line to the top of your index.js file:

```jsx
cronJob = require('cron').CronJob;
```

Cron is a time-based scheduler that we will use to automate the process of receiving the tweets. To understand how to send out these tweets at a certain period of time, we first need to understand how the crontab works:

```bash
* * * * * [command]
| | | | | the last * represents the day of the week (from 0==Sunday to 6==Saturday)
| | | | the fourth * represents the month (from 1==January to 12==December)
| | | the third * represents the day of the month (1 to 31)
| |  the second * represents the hour
| the first * represents the minute
```

Start by creating a cron job:

```bash
crontab -e
```

For this case, we want to send out the text everyday at 9am and run the `node index.js` command. After executing the previous command, a blank crontab file will open. Here we will type in our cron entries, each separated by a single space.

For the command, we need to locate and use the local paths to `node index.js`

```bash
0 0 9 * * * /Users/shreya/node_modules/node /Users/shreya/Documents/btweets/app.js
```

Now we can save this file and exit out of it. We can also list out the scheduled cron jobs with the `crontab -l` command.

### Congratulations!

We have finally completed building our automated BTweetS app. Here's a round of applause from the kings themselves:

![https://media.giphy.com/media/McOXfLCpYA6mAQkKDj/giphy.gif](https://media.giphy.com/media/McOXfLCpYA6mAQkKDj/giphy.gif)

### Thanks to:

- [Automate Your Job Search with Twitter and Twilio Programmable SMS](https://www.twilio.com/blog/automate-your-job-search-with-twitter-and-twilio-programmable-sms)
- [Create SMS Notifications from Tweets, Retweets, and Mentions with JavaScript and Twilio SMS](https://www.twilio.com/blog/sms-notifications-tweets-javascript-twilio)
- [Send and Receive Tweets using SMS with Twilio](https://www.twilio.com/blog/2015/03/send-tweets-via-sms-with-twilio-part-1.html)
- [4 ways to schedule Node.js code](https://www.twilio.com/blog/4-ways-to-schedule-node-code)
- [Cron](https://en.wikipedia.org/wiki/Cron)

### Source Code:

[BTweetS GitHub](https://github.com/shreythecray/btweets/blob/main/index.js)