torogitar
torogitar

Reputation: 23

Find channel name of message with SlackClient

I am trying to print the channel a message was posted to in slack with the python SlackClient. After running this code I only get an ID and not the channel name.

import time
import os
from slackclient import SlackClient

BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')

def main():
    # Creates a slackclient instance with bots token
    sc = SlackClient(BOT_TOKEN)

    #Connect to slack
    if sc.rtm_connect():
        print "connected" 
        while True:
            # Read latest messages
            for slack_message in sc.rtm_read():
                message = slack_message.get("text")
                print message
                channel = slack_message.get("channel")
                print channels
            time.sleep(1)


if __name__ == '__main__':
    main()

This is the output:

test
U1K78788H

Upvotes: 1

Views: 2725

Answers (2)

Abhinav Rai
Abhinav Rai

Reputation: 144

This will always produce a channel id and not channel name. You must call channels.info to get the channel name.

import time
import os
from slackclient import SlackClient

BOT_TOKEN = os.environ.get('SLACK_BOT_TOKEN')

def main():
# Creates a slackclient instance with bots token
sc = SlackClient(BOT_TOKEN)

#Connect to slack
if sc.rtm_connect():
    print "connected" 
    while True:
        # Read latest messages
        for slack_message in sc.rtm_read():
            message = slack_message.get("text")
            print message
            channel = slack_message.get("channel")
            print channel
            channel_info=sc.api_call("channels.info",channel=channel)
            print channel_info["channel"]["name"]
        time.sleep(1)


if __name__ == '__main__':
    main()

This will also print channel Name. Another way is that you can store names of all the channels with their channel_id in a dictionary beforehand. And then get the channel name with id as key.

Upvotes: 2

Matthieu
Matthieu

Reputation: 1239

I'm not sure what you are outputting. Shouldn't "channels" be "channel" ? Also, I think this output is the "user" field. The "Channel" field should yield an id starting with C or G (doc).

{
    "type": "message",
    "channel": "C2147483705",
    "user": "U2147483697",
    "text": "Hello world",
    "ts": "1355517523.000005"
}

Then, use either the python client to retrieve the channel name, if it stores it (I don't know the Python client), or use the web API method channels.info to retrieve the channel name.

Upvotes: 0

Related Questions