Build the future of communications.
Start building for free

Chuck Norris jokes via WhatsApp with C# and Azure Functions

tqHx9wLhOJm_JUAx8gNphdspQHuf8DVyXIB-aIsNww4L5yQImyL5k2bB2qkOL9Bqf-VPq0Hfq74sGJSvBBQTjMnSkrVz0btT4vSCHQO4cZ6-vjviB7WINn-1WtLdDD_3tC0lVAuN

Setting up a .NET application takes time and sometimes you just want to write a quick bit of code that sends you a Chuck Norris joke via the Twilio API for WhatsApp! So that’s what we’re going to do with the help of Azure Functions.

What you’ll need:

Azure Functions allow you to write code without having to worry about infrastructure or servers, so they are perfect for setting up a simple webhook for an incoming SMS or call from Twilio.

Create an Azure Function

From the Azure portal, click the Create a resource button, found at the top of the menu on the left.  Search for a Serverless Function App and then click on the matching result.

Give your app a name, I called mine twilio-whatsapp-jokes, create or reuse a resource group, and choose the Location that best suits you.  You can then click Create at the bottom of the panel.

OGrYAbdWih2eFxErBKWFP1Pu6yEcSR0eDe1T8WTD4aZUEHsDLX2vxaWrXyhK4kKYv0FBwwWU4k01i2G8A47StlwAH5OQks-lHvSk5yymYco3gzEym7-rwRRlGhuoR1OMV931GNBU

Once that has deployed, go into the Functions from the menu on the left.  If you can’t see Functions then click on All services, it’s below Create a resource, search for Function Apps and then click the star to the right of the result to favourite it.  Now it should be on the panel on the left.

You should see your newly created Function App with three submenus; Functions, Proxies and Slots.  Click on the plus button beside Functions to add a new function to our Function app.

90HEHmuJtS8aMOC2mp-jhei5qi1vTTLaeGfL5CFwrtLXSZtSGXojQyD1IJEfgSLGGJpqJ0ha7-wtcG696PKFLv9LA93UVihshp5O70WeMA5f_-U-X7LTxepabFu4tGzGHTXdOuqH

You’ll be given some options for quickstarts but we are going to create a Custom Function, so go ahead and click on that link.

xFtrYTdhkRHjTqmCxPg1PEtd-dZ7GYqD0CEzXGxexkqjPbGxhDcLg0eFJJx0aUs8FcAHlGRTwtUuYkste4gyxGWhue_s4O2-Th6g4ITiLWj_evQ85Lw1Yg8LP2smLyv_TuRMw4iO

Blesf7RLu1FxaKDKYzmV3WHz-U4DNEFtGmNkZuwhlCa6o4H1oD7K_VvjVfrVMZYIsVGZ1JZjdOQUTvht1B5zOxi6EaL0InFuvFt_9HPCK60YB2In48OpaqtkHV8dINotMWhwzxOD

The link will take you to a screen with loads of template types.  The one we want, HTTP trigger, should be first, select the link for C#.  A panel will slide out from the right of the screen asking you to name your function, do this and then click create.

You should now see your newly created function listed under your function app. Click on the Get function URL button and save the URL for later.

yCMjqGPoh-ZCf0h9KnO6N31K0VEA5Bma1Mhd9BTH4p6N3szpX3r0K5VigAeh_Mpm2rYxrPkIQS1K1RofzxKxKDOJ9kXDXTEHIsbjHCjAY1m2LRPFMpgjvdS3VNgZSdBC1EDnWZXw

On the far right, you will see a panel, expand this and click on the View Files tab.  We need to add a new file called to project.json enable us to bring in NuGet packages.  Once added, copy and paste the code below in and save it.

{
 "frameworks": {
   "net46": {
     "dependencies": {
       "Twilio": "5.15.0"
     }
   }
 }
}

Calling the Chuck Norris API

kN_tCcQvXrnxErj3e2gKoMb11tgkKZghVP874FGIPtHElPDE6FZzuJYCrvpXba9XedVlyQoawvU1DnzMXXaNvn7EKfuuYKPogkoAmR_rmR6Vy6yIBdgS6n4mhulqaLLCMEtAswVH

We will need a method to fetch a random joke from the Chuck Norris API, one of my favourite APIs!  

So, let’s add another file to the function called GetJoke.csx and add the following code.  We are using an HTTP client to make the call to the Chuck Norris API.  If our mine, is successful, we go ahead and deserialize the returned JSON string to a dynamic object and return the value.

#r "Newtonsoft.Json"

using System;
using System.Net;
using System.Net.Http.Headers;
using Newtonsoft.Json;

public static async Task<string> GetNewJokeAsync()
{
   var joke = "No joke for you!  Something went wrong!";

   using (var httpClient = new HttpClient())
   {
       var apiEndPoint = "https://api.chucknorris.io/jokes/random";
       httpClient.BaseAddress = new Uri(apiEndPoint);
       httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

       var responseMessage = await  httpClient.GetAsync(apiEndPoint);

       if (responseMessage.IsSuccessStatusCode)
       {
           var jsonContent = await responseMessage.Content.ReadAsStringAsync();
           dynamic data = JsonConvert.DeserializeObject(jsonContent);
           joke = data.value;        
       }    
   }

   return joke;
}

Azure Functions come with some external assemblies, like Newtonsoft.json already included, we just need to reference them using the #r "Newtonsoft.Json" notation.  This also means we don’t need to add them to the project.json file.

Click on the run.csx file. This is our entry point so we will handle the incoming API call here.

Update the file with the following code where we set up our usings. Note how we reference our GetJoke method with #load "GetJoke.csx".

#r "System.Xml.Linq"
#load "GetJoke.csx"

using System.Net;
using System.Text;
using Twilio.TwiML;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,TraceWriter log)
{
}

Now, all we need to do is grab a joke using GetNewJokeAsync and create a new TwiML response to return our joke.

public static async Task Run(HttpRequestMessage req, TraceWriter log)
{
   {
       var joke = await GetNewJokeAsync();
       var response = new MessagingResponse().Message(joke);

       var twiml = response.ToString();
       return new HttpResponseMessage       
       {
             Content = new StringContent(twiml, Encoding.UTF8, "application/xml")
       };
    }
}

Now that we have our working function we can add the function URL we saved earlier to the Twilio API for WhatsApp configuration, under A Message Comes In.

cJAtegYTUqWexhXFojCSJQXxRH0WNfHaBQDvjfg9T0ixp9yXVjlRRl301S7WbsSE8ZOR8MLwBk_ftHkIH19rGCDJ814i4qHAG7R85K_1xIK37XGy_RUN6gaut_Oy1LoktmDZGdG0

Time to retrieve a joke

Send your message to the Twilio WhatsApp number and you should receive a random Chuck Norris joke.
Your day has now been made!

6VYPBGmKyUwB6-l2D5nspZAcsklpIixUUdYuah_-T1Wz319Nb0EzK42cpIGtdo4ZeqCODqA_ihRncaJ4VvD1dUOypQc3kSmZpbMxMOpYYdfOpw_yJCvPaTgnIYaz1-nACO_EDsXV

What else can we do?

Well, an improvement on this app would be to text in a joke category and then return a joke that fulfils that.  You can check out one of my other Chuck Norris projects to see how you might do this and this blog to see how you can extract the message body from the request.

Azure functions are great for small sections of code that you want to reuse across different projects like token generators for example.

Azure functions on the Consumption plan will scale automatically so they are also great for high load, sporadic jobs.

oDX2Of0AWdCG-3KfMz5RQxqiPuSscy5QobP_-njIsz0CNJRZqw9czneIJADcOMJjaenwUmxUMzA21PVPpHFPvIAo7ulytEzZN6t37xdHTwtasUqvclad9WY22ekmLOfaOCdBSTLi

Let me know what cool ideas you have for Twilio and Azure functions and feel free to get in touch with any questions.  I can’t wait to see what you build!

 

Authors
Sign up and start building
Not ready yet? Talk to an expert.