繁体   English   中英

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

[英]How read slack channel messages using python-slackclient

我想从我的松弛频道“general”获取消息,可能带有检索最后 50 条消息之类的参数。

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

这个 function 在 python-slackclient 中可用吗? 或者任何解决方法?

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM