6

Hello I have used this https://docs.rocket.chat/api/rest-api/methods/channels/history for get unread message via rest API.

Example Call

  1. (https://rcserver.rocket.chat/api/v1/im.history?roomId=ByehQjC44FwMeiLbX?&unreads=true)

  2. (https://rcserver.rocket.chat/api/v1/im.history?roomId=ByehQjC44FwMeiLbX?&unreads=”+ true)

Code

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(Constants.CONST_SITEURL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("X-Auth-Token", authToken);
client.DefaultRequestHeaders.Add("X-User-Id", userRcId);
HttpResponseMessage msgHistory = client.GetAsync(Constants.CONST_CHATHISTORY + userDetail.RC_RoomID + "&count=20&unreads=true").Result;
     if (msgHistory.IsSuccessStatusCode)
         {
           using (HttpContent content = msgHistory.Content)
                   {
                      var result = content.ReadAsStringAsync();
                      value = JObject.Parse(result.Result);
                    }
           directChatWindow = JsonConvert.DeserializeObject<DirectChatWindowBO>(value.ToString());
         }

I have try to above link and code but it will not give any unread property in result

Example Result

{
"messages": [
 {
  "_id": "7e6691fc-16sdfd3-ecbfsd8-317a-4076bb307e5dfsfd-4564",
  "rid": "CBsDHB7M8fsdfsdfN8G4X2BjsBDt5khnkenENacLN",
  "msg": "hittti",
  "ts": "2017-08-16T11:08:21.011Z",
  "u": {
    "_id": "CBsDHsdadsaB7M8N8G4X2Bj",
    "username": "xyz",
    "name": "xyz21"
  },
  "mentions": [],
  "channels": [],
  "_updatedAt": "2017-08-16T11:08:21.013Z"
},
{
  "_id": "eaf75056-bcxcvxcv40c-4a68-0128-c40503289d60",
  "rid": "CBsDHxcvB7M8cvxvxcvN8G4X2BjsBDt5kxcvhnkenENacLN",
  "msg": "hi",
  "ts": "2017-08-16T11:07:53.579Z",
  "u": {
    "_id": "CBsDHB7M8N8G4X2Bj",
    "username": "Abc",
    "name": "Abc123 "
  },
  "mentions": [],
  "channels": [],
  "_updatedAt": "2017-08-16T11:07:53.583Z"
}]
}

Please help me out. Thank You.

Anthony Horne
  • 2,522
  • 2
  • 29
  • 51
user3505487
  • 95
  • 2
  • 6

2 Answers2

9

As maintainer of the Rocket.Chat REST API, you actually brought to our attention a bug which has been present for a long time now (since we converted from coffeescript). I have submitted a pull request which fixes this issue, however to get the unreads to appear it does require changing how you use the im.history endpoint.

To get the unreads to appear you must also pass in the query parameter of oldest which is a string that can successfully be converted to a JavaScript Date object, see the Date.parse() documentation for details.

An example query url would look like:

http://localhost:3000/api/v1/channels.history?roomName=general&unreads=true&oldest=2017-01-01

Then a successful response which includes the unread information will look like the following:

{
    "messages": [
        {
            "_id": "pwiJmc7ZfEwebMEKP",
            "alias": "",
            "msg": "hello ;) ;)",
            "attachments": null,
            "parseUrls": true,
            "bot": null,
            "groupable": false,
            "ts": "2017-08-18T08:27:26.746Z",
            "u": {
                "_id": "HL2hEQSGask47a82K",
                "username": "graywolf336",
                "name": "graywolf336"
            },
            "rid": "GENERAL",
            "mentions": [],
            "channels": [],
            "_updatedAt": "2017-08-18T08:27:26.749Z"
        },
        {
            "_id": "YRch8iRsur7L6WF5B",
            "alias": "",
            "msg": "hello world",
            "attachments": null,
            "parseUrls": true,
            "bot": null,
            "groupable": false,
            "ts": "2017-08-18T08:21:50.072Z",
            "u": {
                "_id": "HL2hEQSGask47a82K",
                "username": "graywolf336",
                "name": "graywolf336"
            },
            "rid": "GENERAL",
            "mentions": [],
            "channels": [],
            "_updatedAt": "2017-08-18T08:21:50.073Z"
        }
    ],
    "firstUnread": {
        "_id": "3gJZbwLia6tuznPTk",
        "t": "uj",
        "rid": "GENERAL",
        "ts": "2017-07-31T22:53:20.579Z",
        "msg": "graywolf336",
        "u": {
            "_id": "HL2hEQSGask47a82K",
            "username": "graywolf336"
        },
        "groupable": false,
        "_updatedAt": "2017-07-31T22:53:20.579Z"
    },
    "unreadNotLoaded": 259,
    "success": true
}

As of August 8, 2017, this will not work until the pull request is merged. However after it is merged then this will work with development builds and once version 0.59 of Rocket.Chat is released then you can update your server and make usage of it.

Hopefully this helps, let me know if you have any questions and I will update my answer.

Disclaimer: I am an employee of Rocket.Chat and I do maintain the REST API code.

bradleyhilton
  • 376
  • 1
  • 3
  • 7
  • Will it be available for private group too? Because currently "firstUnread" block is not showing in private group history response. – PVR Aug 29 '17 at 07:49
  • @PVR Yes it will be enabled on channels, groups, and direct messages. A release has not been done which contains the code which fixes the issue, it will be on the next version of Rocket.Chat which will be 0.59. – bradleyhilton Aug 29 '17 at 16:49
  • hey thanks for your reply. Will wait for the next release. – PVR Aug 30 '17 at 18:08
  • Hello @bradleyhilton, I use this code now and we have the latest version of Rocket Chat installed in our server. But the counter gives wrong result. – Avishek Das Mar 22 '18 at 11:08
  • This the problem you're having @AvishekDas? https://github.com/RocketChat/Rocket.Chat/issues/11285 – Galatoni Jul 02 '18 at 13:24
  • No this is not. @Galatoni – Avishek Das Jul 04 '18 at 06:54
  • I'm currently working on something that consumed data provided by this endpoint. Unfortunately, it doesn't appear to track the correct counts as AvishekDas has pointed out. Is there anything that's currently in progress that might fix this problem @bradleyhilton? – Galatoni Jul 19 '18 at 09:26
0

You can use this in php

$unread = 0;

    $lists = apicall('im.list'); 
    foreach($lists->ims as $list){ 
        $data = apicall('im.counters?username='.$list->_id);

        $unread += $data->unreads;

    }

    $lists = apicall('channels.list'); 
    foreach($lists->channels as $list){ 
        $data = apicall('channels.counters?roomId='.$list->_id);

        $unread += $data->unreads;

    }

    echo $unread;



function apicall($url){
    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://shsdatabase.rocket.chat/api/v1/'.$url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'X-Auth-Token: '.$_SESSION['rocket_token'],
        'X-User-Id: '.$_SESSION['rocket_user_id']
      ),
    ));
    
    $response = json_decode(curl_exec($curl));
    
    curl_close($curl);
    
    return $response;

}