2 min read 2 days ago

Modify a Reply

You can do that by using the mwai_ai_reply filter. This filter is triggered every time before the chatbot sends a response to the user, giving you the opportunity to run custom processes or modify the output just before it’s displayed.

For example, if a user asks about their shipping status, you can intercept the reply, append relevant delivery information, and even include a link redirecting them to their order page. We are forcing this data into the reply so this might be good example if you want all of your chatbot messages to have a footer of some kind showing specific information that YOU wrote.

Note that this filter only modifies the reply after it has already been generated by the AI model—it does not affect the model’s input or context. Think of it as a post-processing step, not something that influences the AI’s reasoning. If this what you want, you can modify the Query instead.

add_filter('mwai_ai_reply', 'my_mwai_reply', 10, 2);

function my_mwai_reply($reply, $query){
	// First we'll check if the user is talking about their shipping number.
	$last_message = $query->get_message();
	$keywords = ['shipping', 'number', 'track', 'order', 'delivery'];
	$is_shipping_query = preg_match_all('/' . implode('|', $keywords) . '/i', $last_message) > 0;

	// If it's the case, we will get the user's last order from our database.
	if ($is_shipping_query) {
		$user = wp_get_current_user();
		// We'll get the last shipping number from the user's meta. You could also get it from your database.
		$shipping_number = get_user_meta($user->ID, 'last_shipping_number', true);

		//if we have a valid shipping number, we'll check our Zapier webhook to get the latest status of the order.
		if ($shipping_number) {
			$zapier_url = 'https://hooks.zapier.com/hooks/catch/shipping_number/status/';
			$zapier_response = wp_remote_post($zapier_url, array(
				'method' => 'POST',
				'body' => array(
					'shipping_number' => $shipping_number
				)
			));

			$estimated_delivery_date = $zapier_response['estimated_delivery_date'];

			// We'll return a message to the user with the estimated delivery date and a link to the order page.
			$reply->set_reply("Your order will be delivered on $estimated_delivery_date. You can track your order <a href='https://myshop.com/orders/$shipping_number'>here</a>.");
		} 
	}

	return $reply;
}