Share the love

Whatsapp is so common these days that people notice messages in there when compared to normal messages. So here’s an example code to send Whatsapp message based on critical alert.

Things to note:

  • This is just a pseudo code.
  • You need to integrate it with other form of automation to trigger it.
  • It is assumed that you know what alert you’re looking for. I am just using string “critical” for this example.
  • I am using Twilio API.
  • You might need to check if your Twilio phone number is a WhatsApp enabled number, in order to be able to send WhatsApp messages through it.

Here is an example of .NET code that can be used in an Azure Function to send a WhatsApp message based on a critical Azure alert:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using Twilio;
using Twilio.Rest.Api.V2010.Account;

public static class SendWhatsAppMessage
{
    [FunctionName("SendWhatsAppMessage")]
    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req,
        TraceWriter log)
    {
        // Parse the JSON input from the alert
        dynamic data = await req.Content.ReadAsAsync<object>();

        // Check if the alert is critical
        if (data.status == "Critical")
        {
            // Send WhatsApp message using Twilio API
            string accountSid = "your_twilio_account_sid";
            string authToken = "your_twilio_auth_token";
            TwilioClient.Init(accountSid, authToken);

            var message = MessageResource.Create(
                body: $"Critical alert: {data.description}",
                from: new Twilio.Types.PhoneNumber("whatsapp:+14155238886"),
                to: new Twilio.Types.PhoneNumber("whatsapp:+15551234567")
            );

            log.Info($"Sent WhatsApp message: {message.Sid}");
        }

        return req.CreateResponse(HttpStatusCode.OK, "Message sent");
    }
}

In this example, the Azure Function is triggered b

y an HTTP request, which is expected to contain a JSON payload representing the Azure alert. The function first checks if the alert status is “Critical”, and if it is, it uses the Twilio API to send a WhatsApp message containing the alert description. The Twilio account SID and auth token, as well as the phone numbers for sending and receiving the message, should be replaced with the appropriate values for your specific scenario.

It’s important to note that you need to have the Twilio NuGet package installed in your project in order to use the Twilio classes and methods.