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.
And yes, i have messages from every day chat, so 5 days are enough to get the data.
Any idea how to solve it?