WhatsApp Bot | Get Daily Jokes on WhatsApp using Azure Functions and Twilio

This is the WhatsApp Bot that gets the Jokes, daily to your WhatsApp number. I have scheduled the job to get executed daily at the scheduled time.

Pre-requisites

  1. Visual Studio
  2. Cloud Templates
  3. Twilio Account

Visual Studio links are available on the Download page.

Creating Azure Function in Visual Studio

Launch Visual Studio and Create a new project. Select Cloud as Project Type and choose Azure Function.

Give the name of the project “WhatsAppBot-JokesScheduler” and save it to the desired location. Select checkbox place solution and project in the same directory.

Select Azure Functions v3 (.NET Core) and Time Trigger. Keep the CRON expression default. You can change it to your convenience in the code.

Install the NuGet Package – Twilio. Replace the code with the below code.

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

namespace JokesScheduler
{
    public static class Function1
    {
        [FunctionName("JokesDaily")]
        public static async Task RunAsync([TimerTrigger("34 9 * * *")] TimerInfo myTimer, ILogger log)
        {
            var accountSid = "<Account SID>";
            var authToken = "<Authentication Token>";
            TwilioClient.Init(accountSid, authToken);

            var messageOptions = new CreateMessageOptions(
                new PhoneNumber("whatsapp:+91xxxxxxxxxx"));
            messageOptions.From = new PhoneNumber("whatsapp:+14xxxxxxxxx");

            var response = await getJokes();
            var jokesModel = JsonConvert.DeserializeObject<Rootobject>(response);


            messageOptions.Body = jokesModel.setup;
            var message = MessageResource.Create(messageOptions);

            messageOptions.Body = jokesModel.punchline;
            message = MessageResource.Create(messageOptions);

        }

        public static async Task<string> getJokes()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://official-joke-api.appspot.com/jokes/random");
            client.DefaultRequestHeaders.Accept.Clear();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, client.BaseAddress);

            var response = await MakeRequestAsync(request, client);
            return response;
        }

        private static async Task<string> MakeRequestAsync(HttpRequestMessage getRequest, HttpClient client)
        {
            var response = await client.SendAsync(getRequest).ConfigureAwait(false);
            var responseString = string.Empty;
            try
            {
                response.EnsureSuccessStatusCode();
                responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            catch (HttpRequestException)
            {

            }

            return responseString;
        }
    }


    public class Rootobject
    {
        public int id { get; set; }
        public string type { get; set; }
        public string setup { get; set; }
        public string punchline { get; set; }
    }

}

Replace the configuration details in the code – Twilio Account SID, Twilio Authentication Token, Your WhatsApp number, and Twilio Number.

To get the Twilio configuration details, go to my post on Create WhatsApp Bot -> Configure Twilio Channel. SID and Authentication are available on the Console Dashboard page.

Now run the project in Visual Studio using Cntrl+F5. Before running change the CRON expression based on your schedule. My scheduled time is Daily at 9:34 AM.

Below is the output you will get on WhatsApp. Also, you can check the next occurrence of execution in Console output.

Thank you All!!! Hope you find this useful. You can publish the function in Azure. Refer the article here.

If you liked our content and it was helpful, you can buy us a coffee or a pizza. Thank you so much.


Up ↑

%d bloggers like this: