πŸ“ Create a Cloud Reminder App using Firebase Functions and Twilio

πŸ“ Create a Cloud Reminder App using Firebase Functions and Twilio

Unleash the Power of Cloud Reminders!

Β·

4 min read

Are you tired of forgetting important tasks or appointments? Do you want a reliable way to send reminders to yourself or others?

Look no further! In this blog post, I'll guide you through creating a cloud-based reminder app using Firebase Functions and Twilio. πŸ“…βœ‰οΈ

Prerequisites:

No, no you don't have to fear, you don't need to know anything πŸ˜…, here are some installs need to be made to keep the project up and going.

We will understand Firebase functions from scratch and how to use Twilo and Nodemailer to send email and SMS notifications.

So, make sure you have the following:

  1. A Firebase project set up.

  2. Node.js and npm (Node Package Manager) installed on your machine.

That's it!

Let's get started with the code snippets and explanations!

πŸ”’ Setting Up Firebase and Twilio:

To begin, we need to install the necessary dependencies and configure Firebase and Twilio.

exports.createReminder = functions.https.onRequest(async (req, res) => {
  try {
    const { message, phoneNumber, email, reminderTime } = req.body;

    // Store the reminder in Firestore
    const reminderRef = await db.collection('reminders').add({
      message,
      phoneNumber,
      email,
      reminderTime: new Date(reminderTime),
    });

    // Send response
    res.status(200).json({ id: reminderRef.id });
  } catch (error) {
    console.error('Error creating reminder:', error);
    res.status(500).send('Internal Server Error');
  }
});

In this code snippet, we define the createReminder function as an HTTP trigger.

It extracts the reminder details from the request body and saves them in the Firestore collection named "reminders"

We use the new Date() function to convert the reminderTime to a JavaScript Date object. Finally, we send a response with the ID of the created reminder.

πŸ“² Sending SMS Reminders:

Now, let's implement the functionality to send SMS reminders at the specified time.

We'll use Firebase's Pub/Sub scheduler to trigger this function periodically.

exports.sendReminderSMS = functions.pubsub
  .schedule('* * * * *') // Schedule to run every minute
  .timeZone('Asia/Kolkata') // Replace with your desired time zone
  .onRun(async (context) => {
    try {
      const currentTimestamp = new Date();

      // Query reminders that match the current time
      const remindersSnapshot = await db
        .collection('reminders')
        .where('reminderTime', '<=', currentTimestamp)
        .get();

      const reminders = [];

      // Prepare the reminders to be sent
      remindersSnapshot.forEach((doc) => {
        const reminder = doc.data();
        reminders.push(reminder);

        // Delete the reminder from Firestore
        doc.ref.delete();
      });

      // Send SMS for each reminder
      for (const reminder of reminders) {
        await twilioClient.messages.create({
          body: reminder.message,
          from: 'YOUR_PHONE_NUMBER',
          to: reminder.phoneNumber,
        });

        console.log(`SMS reminder sent to ${reminder.phoneNumber}`);
      }
    } catch (error) {
      console.error('Error sending SMS reminders:', error);
    }
  });

In this code snippet, we define the sendReminderSMS function as a scheduled Pub/Sub function.

It runs every minute and queries the Firestore collection for reminders of whose reminderTime is less than or equal to the current time. We collect the reminders in an array and delete them from Firestore to prevent resending.

Then, for each reminder, we use the Twilio client to send an SMS. Replace 'YOUR_PHONE_NUMBER' with your phone number. Finally, we log the success message to the console.

βœ‰οΈ Sending Email Reminders:

Similarly, let's implement the functionality to send email reminders using Nodemailer.

We'll use the Pub/Sub scheduler to trigger this function as well.

exports.sendReminderEmail = functions.pubsub
  .schedule('* * * * *') // Schedule to run every minute
  .timeZone('Asia/Kolkata') // Replace with your desired time zone
  .onRun(async (context) => {
    try {
      const currentTimestamp = new Date();

      // Query reminders that match the current time
      const remindersSnapshot = await db
        .collection('reminders')
        .where('reminderTime', '<=', currentTimestamp)
        .get();

      const reminders = [];

      // Prepare the reminders to be sent
      remindersSnapshot.forEach((doc) => {
        const reminder = doc.data();
        reminders.push(reminder);

        // Delete the reminder from Firestore
        doc.ref.delete();
      });

      // Send email for each reminder
      for (const reminder of reminders) {
        const mailOptions = {
          from: 'YOUR_EMAIL_ADDRESS',
          to: reminder.email,
          subject: 'Reminder',
          text: reminder.message,
        };

        await transporter.sendMail(mailOptions);

        console.log(`Email reminder sent to ${reminder.email}`);
      }
    } catch (error) {
      console.error('Error sending email reminders:', error);
    }
  });

In this code snippet, we define the sendReminderEmail function as a scheduled Pub/Sub function, running every minute.

It performs a similar workflow as the SMS function but sends email reminders using Nodemailer instead. Replace 'YOUR_EMAIL_ADDRESS' with your own email address.

That's it! You've successfully created a cloud-based reminder app using Firebase Functions and Twilio.

Now, whenever a reminder's time matches the current time, it will be sent as an SMS or email automatically. πŸŽ‰

Remember to deploy your Firebase Functions using the Firebase CLI (firebase deploy) to make them active and start sending reminders.

We hope this tutorial helps you build your own reminder app. Feel free to explore further and add more features like user authentication, recurring reminders, or mobile app integration.

🌟 Repository on GitHub:

You can find the complete source code for this project on GitHub. Don't forget to star the repository if you find it helpful!

πŸ”— GitHub Repository: https://github.com/ighoshsubho/Cloud-Reminder

Happy reminπŸ””ring!

πŸ“’ Connect with me:

I would love to connect with you and hear your feedback or answer any questions you may have. You can reach me on the following platforms:

🌐 Website: yourbrandstories.co

🐦 Twitter: @subhoghosh02

πŸ“Έ Instagram: @subhoghosh02

πŸ’Ό LinkedIn: thesubhoghosh

πŸ”— GitHub: github.com/ighoshsubho

Don't hesitate to reach out and let's connect!


πŸ’­ Quote of the Day:

"The only person you are destined to become is the person you decide to be." - Ralph Waldo Emerson

Remember to stay motivated and keep building amazing things! πŸ’ͺ

Did you find this article valuable?

Support Subho Ghosh by becoming a sponsor. Any amount is appreciated!

Β