send-reply-button.js•3.59 kB
/**
* Function to send a reply button message via WhatsApp API.
*
* @param {Object} args - Arguments for sending the message.
* @param {string} args.recipientPhoneNumber - The phone number of the recipient.
* @param {string} args.buttonText - The text to display on the button.
* @param {Array<Object>} args.buttons - An array of button objects containing id and title.
* @returns {Promise<Object>} - The result of the message sending operation.
*/
const executeFunction = async ({ recipientPhoneNumber, buttonText, buttons }) => {
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`;
// Create the message payload
const messagePayload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: recipientPhoneNumber,
type: "interactive",
interactive: {
type: "button",
body: {
text: buttonText
},
action: {
buttons: buttons.map(button => ({
type: "reply",
reply: {
id: button.id,
title: button.title
}
}))
}
}
};
// 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(messagePayload)
});
// 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 reply button message:', error);
return {
error: `An error occurred while sending the message: ${error instanceof Error ? error.message : JSON.stringify(error)}`
};
}
};
/**
* Tool configuration for sending a reply button message via WhatsApp API.
* @type {Object}
*/
const apiTool = {
function: executeFunction,
definition: {
type: 'function',
function: {
name: 'send_reply_button',
description: 'Send a reply button message via WhatsApp API.',
parameters: {
type: 'object',
properties: {
recipientPhoneNumber: {
type: 'string',
description: 'The phone number of the recipient.'
},
buttonText: {
type: 'string',
description: 'The text to display on the button.'
},
buttons: {
type: 'array',
items: {
type: 'object',
properties: {
id: {
type: 'string',
description: 'Unique identifier for the button.'
},
title: {
type: 'string',
description: 'Title of the button.'
}
},
required: ['id', 'title']
},
description: 'An array of button objects containing id and title.'
}
},
required: ['recipientPhoneNumber', 'buttonText', 'buttons']
}
}
}
};
export { apiTool };