Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Send Email using Mailgun API in Node.js ?
Next article icon

How to get daily weather notification on mobile using Node.js and Twilio API ?

Last Updated : 11 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Looking for weather information daily is a trivial task. As programmers, we can make this task easier by creating a notification service. We will use the Twilio SMS API for sending SMS and Node.js for writing the service which runs every day at a particular time.

Getting Twilio Credentials: To use Twilio APIs, we need to register our app and get the API keys from Twilio’s console. We need to get ACCOUNT SID, AUTH TOKEN, and TRIAL NUMBER. You can get all these credentials from here.

Twilio Console

Save these credentials to .env file in your project’s root directory along with your phone number. Since its a security best practice to save every credential in a separate file.




ACC_SID = 'your-account-sid'
AUTH_TOKEN = 'your-auth-token'
  
TO = 'your-number-with-country-code'
FROM = 'twilio-trial-number'
 
 

Sending SMS: In order to send SMS, we can use Twilio’s library for Node.js. Install the library using the following command:

npm install twilio

Now let’s test our credentials by sending a message. Add the following code to the index.js file.




// Getting Data from .env file
const accountSid = process.env.ACC_SID;
const authToken = process.env.AUTH_TOKEN;
  
const twilio = require("twilio");
const client = new twilio(accountSid, authToken);
  
client.messages
    .create({
        body: "Hello from GeeksForGeeks!",
        to: process.env.TO,
        from: process.env.FROM
    })
    .then(message => console.log(message.sid));
 
 

If all goes good then you will receive an SMS from Twilio with the text “Hello from GeeksForGeeks!”.

Getting the weather information: To get the latest weather information, we will use Openweathermap API which is freely available.

To use the API signup on the website and go to the dashboard to generate the API key as follows:

Openweather map.org Dashboard

We will use the Node.js’s request library to fetch the data from the API. Install the dependency using the following command:

npm install request

And then add the following code snippet to the index.js file.




// Import request library
const request = require("request");
  
function getdata() {
    request(
"http://api.openweathermap.org/data/2.5/weather?q=delhi&appid=<your-api-key>&units=metric",
    { json: true },
    (err, res, body) => {
        if (err) {
            return console.log(err);
        }
  
        // Printing fetched data
        console.log(body); 
    });
}
  
// Calling function
getData();
 
 

Now, create a function to send notification data and add the code for sending SMS like below:




// Send message
function sendNotification(msg) {
  client.messages
    .create({
      body: msg,
      to: process.env.TO,
      from: process.env.FROM
    })
    .then(message => console.log(message.sid));
}
 
 

Now we have to create a message from the data received from the weather API. Replace the getData() function with the following code:




function getdata(){
  request(
    "http://api.openweathermap.org/data/2.5/weather?q=delhi&appid=<your-api-key>&units=metric",
    { json: true },
    (err, res, body) => {
        if (err) {
            return console.log(err);
        }
        
        // Create a message
        let msg = `\nToday's Weather : \n${body.weather[0].main}, ${body.main.temp}°C\nHumidity : ${body.main.humidity}%    
      `;
        
        // Calling Send Message function
        sendNotification(msg);
    });
}
 
 

Now, to send the message every day, we have to set up a cronjob using the node-cron library.

npm install node-cron

Add the cronjob to call getData() method every day at 8:00 AM:




// Importing library
const twilio = require("node-cron");
  
// Cronjob runs everyday at 8:00 AM
cron.schedule("0 8 * * *", () => {
  
    // Calling getData method which
    // calls the send message method
    getData(); 
});
 
 

If everything goes fine then you will receive an SMS displaying the weather information.

Output:



Next Article
How to Send Email using Mailgun API in Node.js ?
author
frikishaan
Improve
Article Tags :
  • Node.js
  • Web Technologies
  • Write From Home
  • Node.js-Misc

Similar Reads

  • How to Run Node.js with Express on Mobile Devices ?
    Node.js is a cross-platform open-source Javascript runtime environment and library for running web applications outside the browser. It is based on Chrome's V8 engine. Node.js is used to create server-side and command-line applications. Express.js is one of the most popular node frameworks. It is a
    2 min read
  • Real-time Notification System using Next.js and Socket.io
    This article explains the process of creating a Real Time Notification System using Next.js and socket.io. In a typical scenario, imagine the need to create a user-friendly application. This application helps the user to send and receive notifications and can be used in multiple projects like E-comm
    5 min read
  • How to Make GET call to an API using Axios in JavaScript?
    Axios is a promise-based HTTP client designed for Node.js and browsers. With Axios, we can easily send asynchronous HTTP requests to REST APIs and perform create, read, update and delete operations. It is an open-source collaboration project hosted on GitHub. It can be imported in plain JavaScript o
    3 min read
  • How to Send Email using Mailgun API in Node.js ?
    Sending an email is an essential part of any project and it can be achieved by using Mailgun API. It is very popular for sending emails. Features of Mailgun: .  It is easy to get started and easy to use.It is a widely used and popular module for sending emails.Mails can also be scheduled. Installati
    2 min read
  • Send Message to WhatsApp using Twilio in Node.js
    We all use WhatsApp in our daily life to send text messages to one another. We can send WhatsApp messages using the Twilio API in NodeJS using the following approach. Features of Twilio:  Widely used module for sending text messages.Supports various languages.Can be also used to send programmable vo
    3 min read
  • Create a Weather app using React and Tailwind
    React JS is a very famous library for front-end development. In this article, we will walk through the process of building a weather app using React, a popular JavaScript library for building user interfaces(UI). Here we also use Tailwind CSS, a utility-first CSS framework. Here we also use a weathe
    5 min read
  • Create a Simple Weather App UI using Tailwind CSS
    Tailwind CSS helps build simple weather app interfaces with its easy styling and responsive features. Developers use Tailwind CSS to enhance user experience in weather apps, adding functionality and engagement. ApproachCreate a basic HTML structure and then link the Tailwind CSS CDN link.Then apply
    3 min read
  • How to scrape the web data using cheerio in Node.js ?
    Node.js is an open-source and cross-platform environment that is built using the chrome javascript engine. Node.js is used to execute the javascript code from outside the browser. Cheerio: Its working is based on jQuery. It's totally working on the consistent DOM model. Cheerio is used for scraping
    2 min read
  • How to Create a Chat App Using socket.io in NodeJS?
    Socket.io is a JavaScript library that enables real-time, bidirectional, event-based communication between the client and server. It works on top of WebSocket but provides additional features like automatic reconnection, broadcasting, and fallback options. What We Are Going to Create?In this article
    5 min read
  • How to Design Movie Telegram Bot using Node.js ?
    Telegram bot API can be used to create a chatbot that returns the complete details of movies, web series, and Tv series by sending the name of the movie or series as a command. Telegram provides a bunch of API’s methods to perform different functions. The telegram bot can be used to know the complet
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences