Slack API: How to get threads and messages in their particular order with respect to time?

Viewed 27

I have a slack script which gets messages every week for the last week and creates some reports. I am using conversations_history method to retrieve messages for the past week. Using the conversation_replies method, I can retrieve all the threaded messages as well but I cannot get them in the exact order of the conversation. For the report I need to create now, this is a vital part of it. How do I get them all to be in a particular order?

My code to get messages:

response = client.conversations_history(
        channel=channel_ID_list[i],
        limit=MESSAGES_PER_PAGE,
        latest=UNIXTime,
    )
    assert response["ok"]
    messages_all = response['messages']
    # print(response["messages"])

    # get additional pages if below max message and if they are any
    while len(messages_all) + MESSAGES_PER_PAGE <= MAX_MESSAGES and response['has_more']:
        page += 1
        print("Retrieving page {}".format(page))
        sleep(1)   # need to wait 1 sec before next call due to rate limits
        response = client.conversations_history(
            channel=channel_ID_list[i],
            limit=MESSAGES_PER_PAGE,
            cursor=response['response_metadata']['next_cursor']
        )
        assert response["ok"]
        messages = response['messages']
        messages_all = messages_all + messages


    response = client.conversations_history(
        channel=channel_ID_list[i],
        limit=MESSAGES_PER_PAGE,
    )
    assert response["ok"]
    messages_all = response['messages']

    # get additional pages if below max message and if they are any
    while len(messages_all) + MESSAGES_PER_PAGE <= MAX_MESSAGES and response['has_more']:
        page += 1
        print("Retrieving page {}".format(page))
        sleep(1)   # need to wait 1 sec before next call due to rate limits
        response = client.conversations_history(
            channel=channel_ID_list[i],
            limit=MESSAGES_PER_PAGE,
            cursor=response['response_metadata']['next_cursor']
        )
        assert response["ok"]
        messages = response['messages']
    # print(messages_all)

Note: I know that they respond with a unix timestamp in each messages. the ts the same for a parent message and its threaded messages. The thread_ts response will be a seperate entity than the ts that is the same for the parent message and threaded message. Just wanted to share this information in case it helps with solving this question of mine.

EDIT: Example data-

{
   "ok":true,
   "messages":[
      {
         "client_msg_id":"xxxxxxxx",
         "type":"message",
         "text":"Main thread message 1",
         "user":"xxxxxxxxx",
         "ts":"1663055350.830049",
         "team":"xxxxxxxx",
         "blocks":[
            {
               "type":"rich_text",
               "block_id":"YxH0A",
               "elements":[
                  {
                     "type":"rich_text_section",
                     "elements":[
                        {
                           "type":"text",
                           "text":"Main thread message 1"
                        }
                     ]
                  }
               ]
            }
         ],
         "thread_ts":"1663055350.830049",
         "reply_count":3,
         "reply_users_count":1,
         "latest_reply":"1663055498.014179",
         "reply_users":[
            "xxxxxxxx"
         ],
         "is_locked":false,
         "subscribed":false
      },
}
1 Answers

If your API does not provide a native way to get the data in the right order, you can easily sort the list using python's built-in sorted() function, using the key argument to specify what to compare. E.g.:

import json

data = json.loads("""
{
  "ok": true,
  "messages": [
    { "text": "fourth", "ts": "4" },
    { "text": "second", "ts": "2" },
    { "text": "first",  "ts": "1" },
    { "text": "third",  "ts": "3" }
  ]
}
""")

print(sorted(data['messages'], key=lambda m: float(m['ts'])))

Will print out:

[{'text': 'first', 'ts': '1'}, {'text': 'second', 'ts': '2'}, {'text': 'third', 'ts': '3'}, {'text': 'fourth', 'ts': '4'}]
Related