How can l get to send whatsapp message from matlab using twilio?

조회 수: 59 (최근 30일)
ODENDAAL
ODENDAAL 2024년 11월 6일 12:10
답변: Sameer 2024년 11월 8일 10:23
% 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

답변 (1개)

Sameer
Sameer 2024년 11월 8일 10:23
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!

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품


릴리스

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by