python-3.xslackslack-api

Python slack bot - Retrieves 0 messages from conversations history when latest and oldest are used in the request


I have an issue while using slack sdk to retrieve messages from Slack using chat bot.

I am using this simple python code:

import time
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token="xoxb-XXXXX")


def fetch_channel_history(channel_id, latest=None, oldest=None):
    try:
        result = client.conversations_history(
            channel=channel_id,
            latest=latest,
            oldest=oldest
        )

        # Check if the request was successful
        if result["ok"]:
            messages = result['messages']
            for message in messages:
                print(f"User {message['user'] if 'user' in message else 'Unknown'} said: {message['text']}")
        else:
            print("Failed to fetch messages")

    except SlackApiError as e:
        print(f"Error fetching conversations: {e.response['error']}")


current = time.time()
five_day_ago = current - 5 * 24 * 60 * 60  # 5 day
fetch_channel_history('channel-id', current, five_day_ago)

However, if i run it 10 times, it might be that only 1 time i get messages.... So, it is not reliable. If i remove the usage of lasted and oldest from the query, it always returns messages, in every run.

In cases the messages are empty, the response looks like this:

{'ok': True, 'latest': '17150713136.315238', 'oldest': '17137753136.315238', 'messages': [], 'has_more': False, 'pin_count': 0, 'channel_actions_ts': None, 'channel_actions_count': 0}

And yes, i have messages from every day chat, so 5 days are enough to get the data.

Any idea how to solve it?


Solution

  • After contacting Slack Support, they indicated that Slack SDK only accepts the epoch time which as 6 digits after decimal point. Otherwise, it will try to correct it, by shifting the dot one number on the right and then messing up the epoch time... In our case, python, in most of the times it generates epoch time with 7 digits after decimal points...

    I fixed it by only rounding the generated epoch time to 6 digits:

    current = round(time.time(), 6)
    five_day_ago = round(current - 5 * 24 * 60 * 60, 6)