<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Sapnesh Naik</title>
    <description>The latest articles on Forem by Sapnesh Naik (@sapneshnaik).</description>
    <link>https://forem.com/sapneshnaik</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F672130%2F44efce87-8e73-47cb-a084-d7dbc7da0ca3.jpg</url>
      <title>Forem: Sapnesh Naik</title>
      <link>https://forem.com/sapneshnaik</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sapneshnaik"/>
    <language>en</language>
    <item>
      <title>How to Add a Real-time Unread Conversation Counter to a TalkJS Chat</title>
      <dc:creator>Sapnesh Naik</dc:creator>
      <pubDate>Wed, 04 Aug 2021 07:19:37 +0000</pubDate>
      <link>https://forem.com/talkjs/how-to-add-a-real-time-unread-conversation-counter-to-a-talkjs-chat-2o05</link>
      <guid>https://forem.com/talkjs/how-to-add-a-real-time-unread-conversation-counter-to-a-talkjs-chat-2o05</guid>
      <description>&lt;p&gt;In this tutorial, we’ll learn how to add a real-time unread conversations counter for TalkJS Inbox using the TalkJS Session. We will do this by registering an event handler to listen for unread conversations and render the counter accordingly on a web page.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setting up a Session
&lt;/h2&gt;

&lt;p&gt;A &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Session/" rel="noopener noreferrer"&gt;TalkJS Session&lt;/a&gt; represents a user’s active browser tab. The Session is also responsible for authenticating users and your application with TalkJS.&lt;/p&gt;

&lt;p&gt;Here, we create a &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/User.html" rel="noopener noreferrer"&gt;TalkJs user&lt;/a&gt; and bind that user to an &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Inbox/" rel="noopener noreferrer"&gt;Inbox &lt;/a&gt;instance using the TalkJs Session. Let’s define a TalkJS session using the &lt;em&gt;new Talk.Session(options)&lt;/em&gt; constructor and pass our appID and &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/User/" rel="noopener noreferrer"&gt;User&lt;/a&gt; object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var user = new Talk.User({
    id: "124582", //unique ID for a new user or an existing user's ID
    name: "Chris Pratt",
    email: "chris@example.com",
    photoUrl: "https://i.picsum.photos/id/1025/4951/3301.jpg",
    welcomeMessage: "Hey there,welcome to TalkJS!",
    role: "default"
});

window.talkSession = new Talk.Session({
    appId: "APP_ID", // replace this with your real APP ID
    me: user
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After setting up the Session, it is now time to create a TalkJS inbox so that our user can chat with other TalkJS users.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var inbox = talkSession.createInbox();
// Mount TalkJS Inbox to a Div with id "talkjs-container"
inbox.mount(document.getElementById("talkjs-container"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FIc4oMOr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FIc4oMOr.png" title="TalkJS Demo" alt="alt_text" width="800" height="513"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: Other than plain JavaScript, TalkJs SDK supports Vue, Angular, and React. And the API will be the same across these frameworks. You can check out our &lt;a href="https://talkjs.com/docs/" rel="noopener noreferrer"&gt;docs&lt;/a&gt; for more information.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Listening for Unread Conversation Changes
&lt;/h2&gt;

&lt;p&gt;Now that our Inbox is set up, we can start listening for any unread conversations. This is made easy by the TalkJS &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Session/#Session__unreads" rel="noopener noreferrer"&gt;Session.unreads&lt;/a&gt; object. &lt;/p&gt;

&lt;p&gt;The “&lt;em&gt;On&lt;/em&gt;” method of the &lt;em&gt;Session.unreads&lt;/em&gt; object fires a “&lt;strong&gt;change&lt;/strong&gt;” event right after TalkJS loads, and every time the amount of unread conversations changes. The event handler gets an array of objects with information about the &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Session/#UnreadConversation" rel="noopener noreferrer"&gt;unread conversations&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.talkSession.unreads.on("change", function (unreadConversations) {
    console.log(unreadConversations)
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The _unreadConversations_is a JSON array that looks something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[
    {
        "lastMessage": {
            "conversation": {
                "id": "unread1",
                "custom": {
                    "category": "test123"
                },
                "topicId": null,
                "subject": "TalkJS Unread Message Counter tutorial",
                "welcomeMessages": null,
                "photoUrl": null
            },
            "isByMe": false,
            "senderId": "135487",
            "sender": {
                "id": "135487",
                "name": "Stella Admin",
                "welcomeMessage": "Hey there! How are you? :-)",
                "photoUrl": "https://picsum.photos/200",
                "role": "Admin",
                "configuration": "Admin",
                "custom": {},
                "availabilityText": null,
                "locale": null,
                "email": "&amp;lt;suppressed&amp;gt;",
                "phone": "&amp;lt;suppressed&amp;gt;"
            },
            "body": "New conversation",
            "type": "text",
            "timestamp": 1627806520159,
            "read": false,
            "origin": "web",
            "custom": {
                "textMessage": "true"
            },
            "attachment": null,
            "location": null
        }
    }
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Rendering the Unread Counter
&lt;/h2&gt;

&lt;p&gt;Now that we have figured out how to get the data on unread conversations of a user, we can use the data to display information to the user however we want!&lt;/p&gt;

&lt;p&gt;Let me show an example of this using a simple HTML span tag and JavaScript to update the unread conversations counter.&lt;/p&gt;

&lt;p&gt;Define a heading that contains the placeholder for the unread counter in a span tag.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div&amp;gt;
    &amp;lt;h1&amp;gt;You have &amp;lt;span id="unreadCount" class="bold_blue"&amp;gt; 0 &amp;lt;/span&amp;gt; unread conversations.&amp;lt;/h1&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Define an &lt;em&gt;event handler&lt;/em&gt; for the &lt;em&gt;Session.unreads.on()&lt;/em&gt; method that updates the unread counter whenever the TalkJS app loads or the unread conversation data changes. We can check the length of the array provided to the &lt;em&gt;Handler&lt;/em&gt; to determine the number of unread conversations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;window.talkSession.unreads.on("change", function (unreadConversations) {
    var amountOfUnreads = unreadConversations.length;
    document.getElementById("unreadCount").textContent= amountOfUnreads;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FJ0h69zQ.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FJ0h69zQ.gif" title="TalkJS Unread Counter Demo GIF" alt="alt_text" width="1452" height="892"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That’s it! This was a simple example, but as you have plenty of information available for an unread conversation, you can get creative and implement better UX-friendly ways to display the counter!&lt;/p&gt;

&lt;p&gt;If you run into any issues, please get in touch via the popup on &lt;a href="https://talkjs.com/" rel="noopener noreferrer"&gt;our website&lt;/a&gt; or send an email to &lt;a href="//mailto:dev@talkjs.com"&gt;dev@talkjs.com&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>talkjs</category>
      <category>sessionunreads</category>
      <category>talkjsinbox</category>
      <category>unreadcounter</category>
    </item>
    <item>
      <title>How to Hide Some Chat Messages for Certain Users in a TalkJS Chat</title>
      <dc:creator>Sapnesh Naik</dc:creator>
      <pubDate>Thu, 22 Jul 2021 13:22:22 +0000</pubDate>
      <link>https://forem.com/talkjs/how-to-hide-some-chat-messages-for-certain-users-in-a-talkjs-chat-23g4</link>
      <guid>https://forem.com/talkjs/how-to-hide-some-chat-messages-for-certain-users-in-a-talkjs-chat-23g4</guid>
      <description>&lt;p&gt;In this tutorial, we’ll learn how to hide specific chat messages for users using the &lt;a href="https://talkjs.com" rel="noopener noreferrer"&gt;TalkJS Chat API&lt;/a&gt; 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.&lt;/p&gt;

&lt;h2&gt;
  
  
  What Are Message Filters?
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html#Chatbox.setMessageFilter" rel="noopener noreferrer"&gt;TalkJs message filters&lt;/a&gt; are used to control which messages show up in the Chatbox UI. You can filter messages based on type, origin, sender, and custom attributes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;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.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Applying Message Filters in a Chat UI
&lt;/h2&gt;

&lt;p&gt;To apply filters to a Chatbox, use the &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html#Chatbox.setMessageFilter" rel="noopener noreferrer"&gt;setMessageFilter&lt;/a&gt; method and pass a &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Other_interfaces.html#MessagePredicate" rel="noopener noreferrer"&gt;MessagePredicate&lt;/a&gt; to apply filters based on Custom attributes, sender, origin, and type. &lt;/p&gt;

&lt;p&gt;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 &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/User.html" rel="noopener noreferrer"&gt;TalkJs user&lt;/a&gt; and bind that user object to a new &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html" rel="noopener noreferrer"&gt;Chatbox&lt;/a&gt; instance using the &lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Session.html" rel="noopener noreferrer"&gt;TalkJs session&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;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 &lt;a href="https://talkjs.com/docs/" rel="noopener noreferrer"&gt;docs&lt;/a&gt; for more information.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
    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: "&amp;lt;appID&amp;gt;",
            me: me
        });

        var chatbox = talkSession.createChatbox();
        chatbox.mount(document.getElementById("talkjs-container"));
    });
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FwzK5GUa.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FwzK5GUa.png" title="image_tooltip" alt="Demo Image" width="800" height="530"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Fig: Demo VanillaJS application&lt;/p&gt;

&lt;h3&gt;
  
  
  Only Showing Text Messages
&lt;/h3&gt;

&lt;p&gt;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 &lt;strong&gt;&lt;a href="https://talkjs.com/docs/Reference/JavaScript_Chat_SDK/Chatbox.html#Chatbox.on__sendMessage__" rel="noopener noreferrer"&gt;on("sendMessage")&lt;/a&gt;&lt;/strong&gt; method.&lt;/p&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;chatbox.on("sendMessage", function(ev) {
    if (!ev.message.attachment) {
        ev.override({
            custom: {
                textMessage: "true"
            }
        });
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('filterTextMessages').onclick = function filter() {
    chatbox.setMessageFilter({
        custom: {
            textMessage: "exists"
        }
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FdjygaZq.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FdjygaZq.gif" title="Show only text messages" alt="Show only text messages" width="800" height="514"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Only Showing Messages with Attachments
&lt;/h3&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('filterAttachments').onclick = function filter() {
    chatbox.setMessageFilter({
        custom: {
            textMessage: "!exists"
        }
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FeWFhbvW.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FeWFhbvW.gif" title="Show only attachments" alt="Show only attachments" width="760" height="488"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Only Showing Admin Messages (Filter Based on Sender's Role)
&lt;/h3&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;Let’s take an example and show only those messages sent by users with the role “Admin.”&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('showAdminMessages').onclick = function filter() {
    chatbox.setMessageFilter({sender: {role: ["==", "Admin"]}})
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FokPSixh.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FokPSixh.gif" title="Show only admin messages" alt="Show only admin messages" width="1370" height="882"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Filtering out Messages from Banned Users
&lt;/h3&gt;

&lt;p&gt;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.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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"]
        }
    })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FT29u2I8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FT29u2I8.gif" title="Hide messages from banned users" alt="Hide messages from banned users" width="1370" height="882"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Reset Filters
&lt;/h3&gt;

&lt;p&gt;Finally, to reset or remove all filters, just call the setMessageFilter method again and pass NULL; this should clear all current filters.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;document.getElementById('resetFilters').onclick = function reset() {
    chatbox.setMessageFilter(null)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you run into any issues, please get in touch via the popup on &lt;a href="https://talkjs.com/" rel="noopener noreferrer"&gt;our website&lt;/a&gt; or send an email to &lt;a href="//mailto:dev@talkjs.com"&gt;dev@talkjs.com&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>talkjs</category>
      <category>talkjsfilters</category>
    </item>
  </channel>
</rss>
