如何使用 python-slackclient 读取松弛通道消息

问题描述

我想从我的 slack 频道“general”获取消息,可能带有像retrieve last 50 Messages这样的参数。

我检查了 documents,有发送消息、列出频道、离开频道、查找频道 ID 等所有内容。但我没有找到任何可以帮助我“一次”获取频道消息的内容频道 ID。

这个函数在python-slackclient.js中是否可用?或者有什么解决方法

解决方法

您正在寻找 conversations.history 方法,该方法提取对话的最后 100 个消息事件。 sample code 非常简单:

import os
# Import WebClient from Python SDK (github.com/slackapi/python-slack-sdk)
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# WebClient insantiates a client that can call API methods
# When using Bolt,you can use either `app.client` or the `client` passed to listeners.
client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))
# Store conversation history
conversation_history = []
# ID of the channel you want to send the message to
channel_id = "C12345"

try:
    # Call the conversations.history method using the WebClient
    # conversations.history returns the first 100 messages by default
    # These results are paginated,see: https://api.slack.com/methods/conversations.history$pagination
    result = client.conversations_history(channel=channel_id)

    conversation_history = result["messages"]

    # Print results
    logger.info("{} messages found in {}".format(len(conversation_history),id))

except SlackApiError as e:
    logger.error("Error creating conversation: {}".format(e))
,

获得频道 ID 后,您可以使用 api_calls 来检索这样的消息

history = client.api_call(api_method='conversations.history',data={'channel':'CHANNEL_ID_HERE'})
print(history)