This Python tutorial will show you how to use Python and Flask to access the Slack API. I’ll show you how to connect to Slack using the API and the official SlackClient Python helper library. We’ll get an API access token and use it to access some data.
You can get more information from Slack API docs.
The Pre-Requisite –
- The system must have installed Python 2/3
- Flask web micro-framework
- Create a free Slack account with a team on which you have API access or sign up for the Slack Developer Hangout team
- Official Python slackclient code library.
- Slack API testing token
Table of Contents
Access Slack API
Let’s create a project that’ll contain all project-related files. We’ll also create a new virtualenv to isolate our application dependencies from other Python projects:
$ mkdir slackapi
$ virtualenv venv
Now, activate virtual env –
source venv/bin/activate
Install Slack Client Using pip
This library requires Python 3.6 and above. If you require Python 2, please use SlackClient – v1.x.
Check python version –
python --version
-- or --
python3 --version
Let’s install the slack client using pip –
//python 2 pip install slackclient==1.0.0 //python 3.6+ pip3 install slackclient
We require a Slack access token for our team and account.
Assuming you have obtained a Slack API access token, let us inject it into the environment variable-
export SLACK_TOKEN='slack token pasted here'
Let’s make a test.py
file, import the Slack client library, and add an access token to the client –
import os from slackclient import SlackClient SLACK_TOKEN = os.environ.get('SLACK_TOKEN') slack_client = SlackClient(SLACK_TOKEN)
Let’s get all channel lists –
created a python method to getall channels list.
def list_channels(): channels_call = slack_client.api_call("channels.list") if channels_call['ok']: return channels_call['channels'] return None if name == 'main': channels = list_channels() if channels: print("Fetching Channels: ") for channel in channels: print(channel['name'] + " (" + channel['id'] + ")") else: print("Unable to authenticate.")
in the above code, We have created a list_channels()
method and passed end point channels.list
, to get all channel list. if the response is ok then return channel list otherwise return null.
Finally, We have called list_channels()
method and iterate on channels objects. print the channel name and id as putput.
The final code –
import os from flask import Flask, request, Response from slackclient import SlackClient SLACK_TOKEN = os.environ.get('SLACK_TOKEN') slack_client = SlackClient(SLACK_TOKEN) app = Flask(name) @app.route('/get_channels', methods=['GET']) ef list_channels(): channels_call = slack_client.api_call("channels.list") if channels_call['ok']: return Response(channels_call['channels']), 200 return Response('No found channels'), 200 if name == 'main': app.run(debug = True)