Monu
Monu

Reputation: 907

How read slack channel messages using python-slackclient

I want to get messages from my slack channel "general", may be with parameter like retrieve last 50 Messages.

I checked documents, there are all stuff like sending message, listing channels, leaving channels, finding channel ID's etc. But I didn't found anything which can help me to get channel's messages "once" using that channel ID.

Is this function available in python-slackclient. Or any workaround?

Upvotes: 2

Views: 4731

Answers (2)

parvesh
parvesh

Reputation: 458

After getting Channel ID's you can use api_calls to retrieve messages like this

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

Upvotes: 1

RJ Adriaansen
RJ Adriaansen

Reputation: 9639

You are looking for the conversations.history method, which pulls the last 100 message events of a conversation. The sample code is pretty straightforward:

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))

Upvotes: 2

Related Questions