Get Your Daily Dose of BTS with the Twilio API!

shreythecray

Shreya

Posted on December 8, 2020

Get Your Daily Dose of BTS with the Twilio API!

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

Getting Prepped

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

npm install twilio
npm install twit
npm install cron
Enter fullscreen mode Exit fullscreen mode

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 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

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

For the next part, I followed Shajia Abidi's awesome tutorial called "Automate Your Job Search with Twitter and Twilio Programmable SMS" that recommended using the Twit npm package to simplify using the Twitter API.

The Twit documentation 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.

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, 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

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.

const Twit = require('twit');
Enter fullscreen mode Exit fullscreen mode

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

...

// 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]',
});
Enter fullscreen mode Exit fullscreen mode

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

...

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

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

If you want to change the type of tweet you receive, check out the Twit documentation.

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:

...

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);

  ...
})
Enter fullscreen mode Exit fullscreen mode

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.

...

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

  const statuses = data.statuses;

})
Enter fullscreen mode Exit fullscreen mode

Next, we can send a message to our phone by using client.message. Add the following code below:

...

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));
})
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

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:

...

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));
})
Enter fullscreen mode Exit fullscreen mode

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:

...

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


  try {
    ...

  } catch(e){
     ...
   }
})
Enter fullscreen mode Exit fullscreen mode

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:

...

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));
   }
})
Enter fullscreen mode Exit fullscreen mode

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

Automating for Daily Tweets using Cron:

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

cronJob = require('cron').CronJob;
Enter fullscreen mode Exit fullscreen mode

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:

* * * * * [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
Enter fullscreen mode Exit fullscreen mode

Start by creating a cron job:

crontab -e
Enter fullscreen mode Exit fullscreen mode

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

0 0 9 * * * /Users/shreya/node_modules/node /Users/shreya/Documents/btweets/app.js
Enter fullscreen mode Exit fullscreen mode

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

Thanks to:

Source Code:

BTweetS GitHub

💖 💪 🙅 🚩
shreythecray
Shreya

Posted on December 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related