So, I'm gonna make this a short story rather than an article on 'How to send WhatsApp Messages from C# using Twilio'?
SETUP:
Before you start coding, you'll need to gather your Twilio account credentials.
- Login to Twilio and Save these details to authenticate
- Sandbox Opt-in Message
Send “join <your sandbox keyword>
” to your Sandbox number in WhatsApp to join your Sandbox, and we’ll reply with a confirmation that you’ve joined. Your sandbox keyword can be found in the console.
![Twilio Sandbox](hps://i.sstatic.net/Wu1e8.png "Twilio Sandbox")
CODE
using System;
using Twilio;
using Twilio.Types;
using Twilio.Rest.Api.V2010.Account;
using System.Linq;
public class WhatsAppMessenger : IMessenger
{
private readonly string accountSid;
private readonly string authToken;
private readonly string fromNumber;
private readonly List<string> userNumbers;
public WhatsAppMessenger()
{
accountSid = "ACCOUNT_SID";
authToken = "AUTH_TOKEN";
fromNumber = "whatsapp:+XXXXXXXXX";
userNumbers = new List<string>
{
"whatsapp:+XXXXXXXXX"
};
}
public void SendMessage(string body)
{
userNumbers.ForEach(num =>
{
this.SendMessage(num, body);
});
}
private bool SendMessage(string toNumber, string body)
{
bool isSuccess = false;
try
{
TwilioClient.Init(accountSid, authToken);
var messageOptions = new CreateMessageOptions(
new PhoneNumber(toNumber));
messageOptions.From = new PhoneNumber(fromNumber);
messageOptions.Body = body;
var message = MessageResource.Create(messageOptions);
Console.WriteLine($" Status : {message.Status} , Error : {message.ErrorMessage}");
isSuccess = true;
}
catch (Exception ex)
{
Console.WriteLine($"Some exception occured : {ex.ToString()}");
}
return isSuccess;
}
}
public interface IMessenger
{
void SendMessage(string body);
}
RESPONSE
This got me super excited and can't wait to explore and code more.
Additionally, please check out https://www.twilio.com/docs/whatsapp/quickstart/csharp for more reference.
#iSeeSharp