send-image-message-by-id.js•2.57 kB
/**
* Function to send an image message via WhatsApp.
*
* @param {Object} args - Arguments for sending the image message.
* @param {string} args.recipientPhoneNumber - The recipient's phone number.
* @param {string} args.imageId - The ID of the image to be sent.
* @returns {Promise<Object>} - The result of the image message sending operation.
*/
const executeFunction = async ({ recipientPhoneNumber, imageId }) => {
const baseUrl = '<API_URL>'; // will be provided by the user
const token = process.env.BOTPE_MCP_API_KEY;
const version = '<Version>'; // will be provided by the user
const businessPhoneNumberId = '<PHONE_NUMBER_ID>'; // will be provided by the user
try {
// Construct the URL for the API request
const url = `${baseUrl}/${version}/${businessPhoneNumberId}/messages`;
// Prepare the message payload
const payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: recipientPhoneNumber,
type: "image",
image: {
id: imageId
}
};
// 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 image message:', error);
return {
error: `An error occurred while sending the image message: ${error instanceof Error ? error.message : JSON.stringify(error)}`
};
}
};
/**
* Tool configuration for sending an image message via WhatsApp.
* @type {Object}
*/
const apiTool = {
function: executeFunction,
definition: {
type: 'function',
function: {
name: 'send_image_message',
description: 'Send an image message via WhatsApp.',
parameters: {
type: 'object',
properties: {
recipientPhoneNumber: {
type: 'string',
description: 'The recipient\'s phone number.'
},
imageId: {
type: 'string',
description: 'The ID of the image to be sent.'
}
},
required: ['recipientPhoneNumber', 'imageId']
}
}
}
};
export { apiTool };