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

How read slack channel messages using python-slackclient

我想从我的“通用”松弛频道获取消息,可能带有检索最近 50 条消息等参数。

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

python-slackclient中是否有此功能。或者任何解决方法?

您正在寻找 conversations.history method, which pulls the last 100 message events of a conversation. The 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)