← Back to Blog

Build a YouTube Channel Notifier with Azure Functions

How to build a serverless YouTube channel notifier using Azure Functions that sends alerts when new videos are published to a channel.

azureserverlessyoutubedotnet

Overview

This article demonstrates building a serverless application using Azure Functions and JavaScript to send email notifications when new comments appear on YouTube videos. The solution integrates the YouTube API and SendGrid to automate comment monitoring and notifications.

Create Google Developer Project to get a YouTube API Key

Create SendGrid Account

SendGrid provides email delivery and tracking capabilities for marketing campaigns and notifications.

Create an Azure Account

  • Register for Azure at https://azure.microsoft.com/en-us/free/ (free tier available)
  • Create an Azure Storage account to host your Function
  • Copy your storage account's Connection String from Access keys in Settings

Install Azure Functions Extensions

  • Install the Azure Functions Extension from the VS Code marketplace
  • Sign in with your Azure Account credentials
  • Install Azure Functions Core Tools for local debugging capabilities

Create a New Azure Function Project

Within Visual Studio Code's Azure menu:

  • Name your project
  • Select JavaScript as your language
  • Choose Timer Trigger as the template
  • Configure the cron schedule (example: "0 0 */5 * * *" for every 5 hours)

Install NPM Packages

npm install --save googleapis
npm install --save @sendgrid/mail

Define Environment Variables

Add these configuration values to local.settings.json within the "Values" section:

"YouTubeAPIKey": "[YOUTUBE_API_KEY]",
"YouTubeChannelID": "[YOUTUBE_CHANNEL_ID]",
"SendGridAPIKey": "[SENDGRID_API_KEY]",
"EmailFrom": "[SENDER_EMAIL]",
"EmailTo": "[RECEIVER_EMAIL]"

Set AzureWebJobsStorage to your storage account's connection string. The EmailTo field accepts multiple addresses separated by commas.

The Function

Initialize API clients within index.js:

const { google } = require("googleapis");
const sendGridClient = require("@sendgrid/mail");

const youtubeClient = google.youtube({
  version: "v3",
  auth: process.env["YouTubeAPIKey"],
});

sendGridClient.setApiKey(process.env["SendGridAPIKey"]);

Retrieve recent comments from the channel:

const response = await youtubeClient.commentThreads.list({
  part: "snippet,replies",
  allThreadsRelatedToChannelId: process.env["YouTubeChannelID"],
  maxResults: 100,
  order: "time",
});

Process comments to identify new ones posted since the last function execution:

if (response.data) {
  const lastRun = new Date(myTimer.scheduleStatus.last);

  response.data.items.forEach(function (comment) {
    const topLevelComment = comment.snippet.topLevelComment.snippet;
    const topLevelCommentDate = new Date(topLevelComment.publishedAt);

    if (topLevelCommentDate.getTime() > lastRun.getTime()) {
      sendEmail(
        topLevelComment.authorDisplayName,
        topLevelComment.textDisplay,
        `https://www.youtube.com/watch?v=${topLevelComment.videoId}&lc=${comment.id}`
      );
    }

    if (comment.snippet.totalReplyCount > 0) {
      comment.replies.comments.forEach(function (reply) {
        const replyDate = new Date(reply.snippet.publishedAt);
        if (replyDate.getTime() > lastRun.getTime()) {
          sendEmail(
            reply.snippet.authorDisplayName,
            reply.snippet.textDisplay,
            `https://www.youtube.com/watch?v=${reply.snippet.videoId}&lc=${reply.id}`
          );
        }
      });
    }
  });
}

Implement the email sending function:

function sendEmail(user, comment, url) {
  let body = "There is a new comment in one of your videos\n";
  body += `User: ${user}\n`;
  body += `Comment: ${comment}\n`;
  body += `Url: ${url}`;

  const msg = {
    to: process.env["EmailTo"],
    from: process.env["EmailFrom"],
    subject: "There is a new comment in your YouTube Channel",
    text: body,
  };

  sendGridClient
    .send(msg)
    .then(() => console.log("Email sent"))
    .catch((error) => console.log(error.response.body));
}

Deploy the Function to Azure

  • Access the Azure Explorer by clicking the Azure icon in VS Code
  • Select the blue up arrow beneath Functions
  • Choose Create new Function app in Azure
  • Provide a unique global name for your Function App
  • Select your preferred Node.js runtime and Azure region

Your Function will be operational in Azure following deployment.

Final Words

This tutorial covered creating, debugging, and deploying a time-triggered Azure Function using JavaScript and Visual Studio Code, demonstrating basic API integrations with YouTube and SendGrid services. Future considerations include analyzing resource consumption and evaluating associated costs. Unused Functions can be deleted via the Azure Explorer.