How can l get to send whatsapp message from matlab using twilio?
59 views (last 30 days)
Show older comments
% Twilio Setup for WhatsApp
accountSID = '%%%%'; % Twilio Account SID
authToken = ''; % Twilio Auth Token
twilioNumber = 'whatsapp:+120###'; % Twilio WhatsApp number
recipientNumber = 'whatsapp:+277%%%'; % recipient's WhatsApp number
% Initialize WhatsAppNotifier
notifier = WhatsAppNotifier(accountSID, authToken);
% Function to Send WhatsApp Message using Twilio Client Class
function sendWhatsAppMessage(client, to, from, message)
try
url = ['https://api.twilio.com/2010-04-01/Accounts/', client.AccountSID, '/Messages.json'];
options = weboptions('Username', client.AccountSID, 'Password', client.AuthToken, 'MediaType', 'application/x-www-form-urlencoded');
data = struct('To', to, 'From', from, 'Body', message);
response = webwrite(url, data, options);
disp('WhatsApp message sent: '), disp(response);
catch
disp('Failed to send WhatsApp message. Please check the phone numbers, account SID, and auth token.');
end
end
0 Comments
Answers (1)
Sameer
on 8 Nov 2024 at 10:23
Hi @ODENDAAL
To send a WhatsApp message from MATLAB using Twilio, you need to follow several steps. This involves setting up a Twilio account, obtaining necessary credentials, and using MATLAB to make an HTTP request to Twilio's API.
Here's how you can do it:
1. Sign up for a Twilio account and navigate to the Twilio Console. Under the Messaging section, find the option to send a WhatsApp message. Follow the instructions to connect your WhatsApp number with the Twilio sandbox.
2. Write MATLAB Code to Send a Message
Here's an example implementation and it worked for me:
function msg = sendMessage(sid, token, to, from, body)
% Function to send a WhatsApp message using Twilio API
% Construct the API endpoint URL
endpoint = sprintf('https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json', sid);
% Set up HTTP request options
options = weboptions('RequestMethod', 'post', ...
'Username', sid, ...
'Password', token, ...
'MediaType', 'application/x-www-form-urlencoded');
% Try to send the message and catch any errors
try
msg = webwrite(endpoint, 'To', to, 'From', from, 'Body', body, options);
catch err
msg = err.message;
end
end
%% Example usage:
% sid = 'your_account_sid';
% token = 'your_auth_token';
% to = 'whatsapp:+12345678901'; % Recipient's WhatsApp number
% from = 'whatsapp:+14155238886'; % Your Twilio WhatsApp number
% body = 'Hello from MATLAB via Twilio!';
% response = sendMessage(sid, token, to, from, body);
% disp(response);
Hope this helps!
0 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!