Send a custom Agent Welcome Message in Salesforce Enhanced Channel

Send a custom Agent Welcome Message in Salesforce Enhanced Channel

Personalize Salesforce Enhanced Chat: How to Send a Custom Agent Welcome Message with Salesforce Lightning Web Component(LWC)?

Delivering exceptional customer service often comes down to the details. In a high-speed channel like Salesforce Enhanced Chat (or Messaging for In-App and Web), a personalized greeting when an agent accepts the chat can make a big difference, setting a warm and professional tone.

This guide provides a practical, code-driven approach to implementing a custom, personalized welcome message using a Lightning Web Component (LWC) and the Conversation Toolkit API in Salesforce.

The Power of the Personalized Greeting 🤝

By default, Salesforce Chat provides a standard “Agent joined the chat” message. While functional, a custom message like “Welcome to InfallibleTechie Support!!! My name is [Agent Name]. How can I help you today?” immediately humanizes the interaction. This custom message is sent automatically the moment the agent accepts the chat.

Step-by-Step Implementation with LWC

The key to this implementation is using the connectedCallback() lifecycle hook in an LWC that is configured on the MessagingSession record page. This setup ensures the component loads and executes the moment the agent views the accepted chat record.

1. The Lightning Web Component (LWC)

We’ll create a simple LWC named welcomeMessage. Note that this component doesn’t render any visible UI. Its sole purpose is to execute the personalized message logic.

A. HTML Template (welcomeMessage.html)

The template is intentionally left empty as the component’s function is programmatic.

<template>
</template>

B. JavaScript Controller (welcomeMessage.js)

The JavaScript file handles fetching the agent’s name and sending the message using the sendTextMessage function from the Conversation Toolkit API.

import { LightningElement, api, wire } from 'lwc';
import currentUserId from '@salesforce/user/Id';
import NAME_FIELD from "@salesforce/schema/User.Name";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import { sendTextMessage } from 'lightning/conversationToolkitApi';

// LWC component to send a personalized welcome message in chat
export default class WelcomeMessage extends LightningElement {
    // Chat session recordId, provided by parent context
    @api recordId;

    // Current user's Salesforce Id
    userId = currentUserId;

    // Wire adapter to fetch current user's Name field
    @wire(getRecord, {
        recordId: '$userId', // Use $ to reference reactive property
        fields: [NAME_FIELD]
    })
    userRecord;

    // Getter to extract user's name from the record
    get userName() {
        return getFieldValue(this.userRecord.data, NAME_FIELD);
    }

    // Lifecycle hook: called when component is inserted into DOM
    connectedCallback() {
        console.log('WelcomeMessage connectedCallback');
        // Wait for 2 seconds before sending the welcome message
        setTimeout(() => {
            console.log("This message appears after 2 seconds.");
            this.sendMessage();
        }, 2000);
    }

    // Sends a personalized welcome message to the chat
    async sendMessage() {
        console.log('recordId is', this.recordId);

        // Defensive: Check if userName is available before sending
        const name = this.userName || 'our agent';

        // Send the welcome message using Conversation Toolkit API
        let result = await sendTextMessage(
            this.recordId,
            { 
                text: 
                    'Welcome to InfallibleTechie Support!!! ' +
                    'My name is ' + name +
                    '. How can I help you today?'
            }
        );
        // Log the result of the send operation
        console.log('result is', JSON.stringify(result));
        console.log('message sent');
    }
}

C. Configuration File (js-meta.xml)

This file is crucial for making the component available on the correct record page and context. We expose the component and specifically target the MessagingSession object’s record page.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>64.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
              <object>MessagingSession</object>
            </objects>
            <supportedFormFactors>
                <supportedFormFactor type="Large" />
            </supportedFormFactors>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

2. Deployment and Setup

  1. Deploy the welcomeMessage LWC to your Salesforce org.
  2. Navigate to the Messaging Session Record Page in the Lightning App Builder.
  3. Edit the page layout that your chat agents use.
  4. Drag the newly created welcomeMessage LWC from the custom components list onto the canvas. A common practice is to place it in a hidden or low-visibility area, as it doesn’t render any UI.
  5. Save and Activate the page.

Now, the next time an agent accepts a Salesforce Enhanced Chat, the LWC will load, retrieve the agent’s name, and automatically send the personalized welcome message to the customer!

Leave a Reply