Author: Ashwini H
By leveraging Salesforce’s Platform Events and Apex controllers, it’s possible to create a Chatbot that can provide personalized responses to user inquiries.
In this example, we have built a Chatbot that can respond to customer product inquiries. When a customer submits a product inquiry, a Platform Event is created and sent to Salesforce. Our Lightning web component subscribes to this event and uses an Apex controller to retrieve the details of the requested product. The Chatbot then provides the customer with the relevant product details in a conversational format.
Platform Events to create Chatbot:
Platform Event notifies the Chatbot whenever a new product inquiry is submitted. The Chatbot can then process the information and generate a response based on the inquiry. This allows for real-time interaction between the user and the Chatbot, providing a more seamless and efficient experience. Additionally, using Platform Event can help you avoid the need for polling or constantly checking for new inquiries, reducing the amount of unnecessary resource usage and improving overall performance.
Steps:
- Create a Platform Event:
- Go to Setup -> Platform Events -> New Platform Event.
- Enter the required details like Event Label, API Name, and Description. Let’s call this event “Product_Inquiry_Received__e”.
- Add any additional fields you want to include in the event, such as “Customer_Name__c”, “Product_Name__c”, “Inquiry_Message__c”, and “Timestamp__c”.

- Creating a custom object for product inquiries:
Note: This step is optional, but it can help you to store and manage the information related to the product inquiries.
- Go to Setup -> Object Manager -> Create -> Custom Object.
- Enter the required details like Object Label, Object Name, and Description. Let’s call this object “Product_Inquiry__c”.
- Add any additional fields you want to include in the object, such as “Customer_Name__c”, “Product_Name__c”, “Inquiry_Message__c”, and “Timestamp__c”.
- You can also create any required relationships with other objects in your Salesforce org.
- Click “Save” to create the custom object.
- Create Apex Trigger:
In the Apex Trigger code, add code to call the Chatbot service when the Platform Event is received.
trigger Product_Inquiry on Product_Inquiry__c (after insert) {
List<Product_Inquiry_Received__e> eventList = new List<Product_Inquiry_Received__e>();
for (Product_Inquiry__c inquiry : Trigger.new) {
// Create a new Platform Event for each Product Inquiry record
Product_Inquiry_Received__e event = new Product_Inquiry_Received__e();
event.Customer_Name__c = inquiry.Customer_Name__c;
event.Product_Name__c = inquiry.Product_Name__c;
event.Inquiry_Message__c = inquiry.Inquiry_Message__c;
event.Timestamp__c = System.now();
eventList.add(event);
}
// Publish the Platform Event
EventBus.publish(eventList);
}
- Create Apex Controller:
The controller method ‘ProductInquiryController ’ is called in LWC to fetch Product details and provide them to the LWC for rendering. It acts as a bridge between the front-end LWC and the Apex.
public with sharing class ProductInquiryController {
@AuraEnabled(cacheable=true)
public static Product2 getProductDetails(String productName) {
List<Product2> products = [SELECT Id, Name, Description, ProductCode FROM Product2 WHERE Name = :productName LIMIT 1];
if (!products.isEmpty()) {
return products[0];
}
return null;
}
}
- Add Lightening web Component:
In the Lightning Web Component code, add code to listen for the Apex trigger and display the Chatbot UI. Here is an example code:
import { LightningElement, track, api, wire } from 'lwc';
import { subscribe, unsubscribe } from 'lightning/empApi'; // Removed onError, setDebugFlag, and isEmpEnabled since they are not used in this component
import getProductDetails from '@salesforce/apex/ProductInquiryController.getProductDetails';
import ProductCode from '@salesforce/schema/PricebookEntry.ProductCode';
import { loadStyle } from 'lightning/platformResourceLoader';
import style from '@salesforce/resourceUrl/style';
export default class ProductInquiryChatbot extends LightningElement {
@api recordId;
@track message = '';
@track messages = [];
subscription = null;
// Load external stylesheet
renderedCallback() {
Promise.all([
loadStyle(this, style)
]);
}
// Subscribe to the Platform Event when the component is connected to the DOM
connectedCallback() {
const channel = '/event/Product_Inquiry_Received__e';
this.subscription = subscribe(channel, -1, this.handleEvent.bind(this), { scope: '' });
}
// Unsubscribe from the Platform Event when the component is disconnected from the DOM
disconnectedCallback() {
unsubscribe(this.subscription, response => {
console.log('Unsubscribed from channel ' + JSON.stringify(response));
});
}
// Update the message property when the input value changes
handleInput(event){
this.message = event.target.value;
}
// Handle form submission
handleSubmit(event) {
event.preventDefault();
const message = this.message.trim();
if (message) {
// Add the message to the messages array
const timestamp = new Date().toLocaleString();
this.messages.push({ text: message, timestamp: timestamp });
this.message = '';
// Send a response using the chatbot service
this.sendResponse(message);
}
}
// Handle the Platform Event when it is received
handleEvent(event) {
const message = event.data.payload.Inquiry_Message__c;
const timestamp = event.data.payload.Timestamp__c;
this.messages.push({ text: message, timestamp: timestamp });
this.sendResponse(message);
}
// Send a response based on the user's message
sendResponse(message) {
const timestamp = new Date().toLocaleString();
if(message.toLowerCase() == 'hello' || message.toLowerCase() == 'hi'){
// Greet the user
const response = 'Greetings, Please type the Product details you are looking for';
this.messages.push({ text: response, timestamp: timestamp });
} else {
// Call the Apex method to get product details
getProductDetails({ productName: message })
.then(result => {
if (result) {
// Update the message with product details
const { Name, ProductCode, Description } = result;
const response = `Product Details:<br>Name: ${Name}<br>Product Code: ${ProductCode}<br>Description: ${Description}`;
this.messages.push({ text: response, timestamp: timestamp, className: 'product-details' });
}
else {
const response = `Sorry, we could not find any product with the name "${message}"`;
this.messages.push({ text: response, timestamp: timestamp });
}
})
.catch(error => {
console.error(error);
});
}
}
}
<template>
<div>
<h1>Welcome to the Product Inquiry Chatbot</h1>
<ul>
<template for:each={messages} for:item="message">
<li key={message.timestamp}>
<p>{message.text}</p>
<p>{message.timestamp}</p>
</li>
</template>
</ul>
<form onsubmit={handleSubmit}>
<input type="text" value={message} oninput={handleInput} />
<button type="submit">Send</button>
</form>
</div>
</template>
- Bring out in frontend:
Add the LWC to the record page. Try creating a new record in the Product Inquiry object and submit. Chatbot will handle the request and send you the response.

