Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

3.9 KB
Raw Blame
import { whatsappAuth } from '../auth';
import { AuthenticationType, httpClient, HttpMethod } from '@activepieces/pieces-common';
import { createAction, Property } from '@activepieces/pieces-framework';
import { commonProps, WHATSAPP_API_BASE } from '../common/utils';
import { messageSendOutputSchema } from '../output-schemas';

export const sendTemplateMessageAction = createAction({
	auth: whatsappAuth,
	name: 'send-template-message',
	outputSchema: messageSendOutputSchema,
	classification: 'WRITE',
	displayName: 'Send Template Message',
	description: 'Send an approved template, filling in its placeholders.',
	audience: 'human',
	aiMetadata: { description: 'Sends a pre-approved WhatsApp message template to a recipient, filling its header, body, and button placeholders from the supplied fields. Choose this to initiate conversations outside the 24-hour customer service window or for notifications/marketing where a registered template is required; the template must already be approved in the WhatsApp Business account. Requires the sender phone number ID, recipient phone number, and the template ID (its name and language are resolved automatically). Not idempotent — each call delivers a new message.', idempotent: false },
	props: {
		phone_number_id: commonProps.phone_number_id,
		to: Property.ShortText({
			displayName: 'To',
			description: "Recipient's phone number in international format.",
			placeholder: '15551234567',
			required: true,
		}),
		message_template_id: commonProps.message_template_id,
		message_template_fields: commonProps.message_template_fields,
	},
	async run(context) {
		const phoneNumberId = context.propsValue.phone_number_id as string;
		const recipientPhoneNumber = context.propsValue.to as string;
		const templateId = context.propsValue.message_template_id as string;
		const templateFields = context.propsValue.message_template_fields;

		// construct components object
		// https://developers.facebook.com/docs/whatsapp/cloud-api/reference/messages#components-object
		const components = [];
		const headerParameters = [];
		const bodyParameters = [];
		const buttonParameters = [];

		for (const [key, value] of Object.entries(templateFields)) {
			if (key.startsWith('header_')) {
				headerParameters.push({ type: 'text', text: value });
			} else if (key.startsWith('body_')) {
				bodyParameters.push({ type: 'text', text: value });
			} else if (key.startsWith('button_')) {
				buttonParameters.push({ type: 'text', text: value });
			}
		}

		if (headerParameters.length) {
			components.push({
				type: 'header',
				parameters: headerParameters,
			});
		}
		if (bodyParameters.length) {
			components.push({
				type: 'body',
				parameters: bodyParameters,
			});
		}
		if (buttonParameters.length) {
			components.push({
				type: 'button',
				sub_type: 'url',
				index: 0,
				parameters: buttonParameters,
			});
		}

		// fetch template language code
		const templateData = await httpClient.sendRequest({
			method: HttpMethod.GET,
			url: `${WHATSAPP_API_BASE}/${templateId}`,
			authentication: {
				type: AuthenticationType.BEARER_TOKEN,
				token: context.auth.props.access_token,
			},
			queryParams: {
				fields: 'id,name,language',
			},
		});

		const templateLanguage = templateData.body['language'];
		const templateName = templateData.body['name'];

		// https://developers.facebook.com/docs/whatsapp/cloud-api/guides/send-message-templates/#text-based
		const response = await httpClient.sendRequest({
			method: HttpMethod.POST,
			url: `${WHATSAPP_API_BASE}/${phoneNumberId}/messages`,
			authentication: {
				type: AuthenticationType.BEARER_TOKEN,
				token: context.auth.props.access_token,
			},
			body: {
				messaging_product: 'whatsapp',
				recipient_type: 'individual',
				to: recipientPhoneNumber,
				type: 'template',
				template: {
					name: templateName,
					language: {
						code: templateLanguage,
					},
					components,
				},
			},
		});

		return response.body;
	},
});