How to Hide Some Chat Messages for Certain Users in a TalkJS Chat
Tags: talkjs, talkjsfilters
Published: 2021-07-22 13:22:22


In this tutorial, we’ll learn how to hide specific chat messages for users using the [TalkJS Chat API](https://talkjs.com) message filters. We will also learn how to combine TalkJS custom message attributes with message filters to implement a wide variety of use cases for filtering chat messages.


## What Are Message Filters?

[TalkJs message filters](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html#Chatbox.setMessageFilter) are used to control which messages show up in the Chatbox UI. You can filter messages based on type, origin, sender, and custom attributes.

_Note: Messages are only filtered in the message list (Chatbox UI). The inbox UI's conversation feed will always show the last message sent to the conversation, regardless of the message filter set._



## Applying Message Filters in a Chat UI

To apply filters to a Chatbox, use the [setMessageFilter](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html#Chatbox.setMessageFilter) method and pass a [MessagePredicate](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Other_interfaces.html#MessagePredicate) to apply filters based on Custom attributes, sender, origin, and type. 

Let’s see different examples of filters that can be applied in a Chat UI using a simple Vanilla Js implementation of TalkJS Chatbox. Here, we create a [TalkJs user](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/User.html) and bind that user object to a new [Chatbox](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html) instance using the [TalkJs session](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Session.html).

Note that, apart from plain JavaScript, TalkJs SDK supports Vue, Angular, and React. And the API will be the same across these frameworks. You can check out our [docs](https://talkjs.com/docs/) for more information.


```
<script>
    Talk.ready.then(function() {
        var me = new Talk.User({
            id: "333333",
            name: "Chris Pratt",
            email: "chris@example.com",
            photoUrl: "https://i.picsum.photos/id/1025/4951/3301.jpg?hmac=_aGh5AtoOChip_iaMo8ZvvytfEojcgqbCH7dzaz-H8Y",
            welcomeMessage: "Hey there! How are you? :-)",
            role: "Accountant"
        });

  window.talkSession = new Talk.Session({
            appId: "<appID>",
            me: me
        });

        var chatbox = talkSession.createChatbox();
        chatbox.mount(document.getElementById("talkjs-container"));
    });
</script>
```




![Demo Image](https://i.imgur.com/wzK5GUa.png "image_tooltip")


Fig: Demo VanillaJS application


### Only Showing Text Messages

A chat can contain text messages, attachments, and locations. To show only text messages in a Chat, you can first add a custom attribute to every message sent using the **[on("sendMessage")](https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html#Chatbox.on__sendMessage__)** method.

Specifically, we’re adding a custom attribute named “textMessage” to every message sent except for attachments. The value of the custom attribute does not matter here as we’ll not be using it. We just need to have the custom attribute present for all text messages.


```
chatbox.on("sendMessage", function(ev) {
    if (!ev.message.attachment) {
        ev.override({
            custom: {
                textMessage: "true"
            }
        });
    }
});
```


Now, to show only text messages in a Chatbox, simply filter out messages with the “textMessage'' custom attribute set using the “exists'' check. As an example, I’m adding the filter on the click of a button here.


```
document.getElementById('filterTextMessages').onclick = function filter() {
    chatbox.setMessageFilter({
        custom: {
            textMessage: "exists"
        }
    })
}
```





![Show only text messages](https://i.imgur.com/djygaZq.gif "Show only text messages")



### Only Showing Messages with Attachments

We can use the same custom “textMessage” attribute, but with “!exists” check and filter out just the attachments. This filter will omit all messages with the “textMessage” attribute present, leaving us with only those messages with attachments.


```
document.getElementById('filterAttachments').onclick = function filter() {
    chatbox.setMessageFilter({
        custom: {
            textMessage: "!exists"
        }
    })
}
```





![Show only attachments](https://i.imgur.com/eWFhbvW.gif "Show only attachments")



### Only Showing Admin Messages (Filter Based on Sender's Role)

Every TalkJS user has a role assigned to them during creation, and you can filter the messages based on this role using the “sender” FieldPredicate.

Let’s take an example and show only those messages sent by users with the role “Admin.”


```
document.getElementById('showAdminMessages').onclick = function filter() {
    chatbox.setMessageFilter({sender: {role: ["==", "Admin"]}})
}
```






![Show only admin messages](https://i.imgur.com/okPSixh.gif "Show only admin messages")



### Filtering out Messages from Banned Users

In your chat application, you will sometimes need to block or filter messages from banned users for various reasons. You can change the user’s role to “Banned” and then filter out messages in a chatbox based on the Sender role.


```
var me = new Talk.User({
    id: "154721",
    name: "Matt Wong ",
    email: "mattwong@example.com",
    photoUrl: "https://picsum.photos/id/237/200/300",
    welcomeMessage: "Hey there! How are you? :-)",
    role: "Banned",
});

document.getElementById('hideBannerUserMessages').onclick = function banned() {
    chatbox.setMessageFilter({
        sender: {
            role: ["!=", "Banned"]
        }
    })
}
```




![Hide messages from banned users](https://i.imgur.com/T29u2I8.gif "Hide messages from banned users")



### Reset Filters

Finally, to reset or remove all filters, just call the setMessageFilter method again and pass NULL; this should clear all current filters.


```
document.getElementById('resetFilters').onclick = function reset() {
    chatbox.setMessageFilter(null)
}
```


If you run into any issues, please get in touch via the popup on [our website](https://talkjs.com/) or send an email to [dev@talkjs.com](mailto:dev@talkjs.com).