send-audio-message-by-url.js•2.88 kB
/**
* Function to send an audio message via WhatsApp.
*
* @param {Object} args - Arguments for sending the audio message.
* @param {string} args.recipientPhoneNumber - The recipient's phone number.
* @param {string} args.audioLink - The URL link to the audio file.
* @param {string} args.businessPhoneNumberId - The business phone number ID.
* @param {string} args.version - The API version.
* @returns {Promise<Object>} - The response from the API after sending the audio message.
*/
const executeFunction = async ({ recipientPhoneNumber, audioLink, businessPhoneNumberId, version }) => {
const baseUrl = '<API_URL>'; // will be provided by the user
const token = process.env.BOTPE_MCP_API_KEY;
try {
// Construct the URL for the API request
const url = `${baseUrl}/${version}/${businessPhoneNumberId}/messages`;
// Create the message payload
const payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: recipientPhoneNumber,
type: "audio",
audio: {
link: audioLink
}
};
// Set up headers for the request
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
};
// Perform the fetch request
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(payload)
});
// Check if the response was successful
if (!response.ok) {
const errorData = await response.json();
throw new Error(JSON.stringify(errorData));
}
// Parse and return the response data
const data = await response.json();
return data;
} catch (error) {
console.error('Error sending audio message:', error);
return {
error: `An error occurred while sending the audio message: ${error instanceof Error ? error.message : JSON.stringify(error)}`
};
}
};
/**
* Tool configuration for sending audio messages via WhatsApp.
* @type {Object}
*/
const apiTool = {
function: executeFunction,
definition: {
type: 'function',
function: {
name: 'send_audio_message',
description: 'Send an audio message via WhatsApp.',
parameters: {
type: 'object',
properties: {
recipientPhoneNumber: {
type: 'string',
description: 'The recipient\'s phone number.'
},
audioLink: {
type: 'string',
description: 'The URL link to the audio file.'
},
businessPhoneNumberId: {
type: 'string',
description: 'The business phone number ID.'
},
version: {
type: 'string',
description: 'The API version.'
}
},
required: ['recipientPhoneNumber', 'audioLink', 'businessPhoneNumberId', 'version']
}
}
}
};
export { apiTool };