JavaScript

Show the Message History

You want your users to see the events in the Conversation. You can filter based on the kind of event to determine how to format the event to be added to the message feed. Add a handleEvent function with this code to chat.js:

function handleEvent(event) {
    let formattedMessage;
    switch (event.kind) {
        case "member:invited":
            formattedMessage = `${event.body.user.name} was invited.<br/>`;
            break;
        case "member:joined":
            formattedMessage = `${event.body.user.name} joined.<br/>`;
            break;
        case "member:left":
            formattedMessage = `${event.body.user.name} left.<br/>`;
            break;
        case "message:text":
            const sender = {
                displayName: event.from.displayName,
                memberId: event.from.memberId,
                userName: event.from.user.name,
                userId: event.from.user.id,
            };
            formattedMessage = formatMessage(sender, event);
            break;
    }
    messageFeed.innerHTML = messageFeed.innerHTML + formattedMessage;
}

In this example, you will use the identity of the user to distinguish between messages sent by them and those received from other users by displaying them in a different color. Create a formatMessage function for this, by adding the following code to chat.js:

function formatMessage(sender, message) {
    const rawDate = new Date(Date.parse(message.timestamp));
    const options = {
        weekday: "long",
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
    };
    const formattedDate = rawDate.toLocaleDateString(undefined, options);
    let text = "";

    if (message.from.memberId !== myMember.id) {
        text = `<span style="color:red">${sender.userName.replace(/</g,"&lt;")} (${formattedDate}): <b>${message.body.text.replace(/</g,"&lt;")}</b></span>`;
    } else {
        text = `me (${formattedDate}): <b>${message.body.text.replace(/</g,"&lt;")}</b>`;
    }
    return text + "<br />";
}

Finally, you need to set up an event listener for any new incoming events. You can do this by listening for conversationEvent on the client. Add the following to the bottom of the run function:

client.on("conversationEvent", (event) => {
    handleEvent(event);
});