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

58 ビュー (過去 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 Center および File ExchangeGet 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