我在使用 slack sdk 使用聊天机器人从 Slack 检索消息时遇到问题。
我正在使用这个简单的Python代码:
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)
但是,如果我运行10次,可能只有1次我收到消息......所以,它不可靠。如果我从查询中删除“lasted”和“oldested”的使用,它在每次运行中总是返回消息。
如果消息为空,响应如下所示:
{'ok': True, 'latest': '17150713136.315238', 'oldest': '17137753136.315238', 'messages': [], 'has_more': False, 'pin_count': 0, 'channel_actions_ts': None, 'channel_actions_count': 0}
是的,我每天都会收到聊天消息,所以 5 天足以获取数据。
知道如何解决吗?
联系Slack Support后,他们表示Slack SDK只接受小数点后6位的纪元时间。否则,它会尝试纠正它,通过将右侧的点移一位数字,然后弄乱纪元时间...在我们的例子中,Python,在大多数情况下,它会生成小数点后 7 位的纪元时间。 ..
我通过仅将生成的纪元时间四舍五入到 6 位数字来修复它:
current = round(time.time(), 6)
five_day_ago = round(current - 5 * 24 * 60 * 60, 6)