• Stars
    star
    3,840
  • Rank 11,446 (Top 0.3 %)
  • Language
    Python
  • License
    MIT License
  • Created about 10 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Slack Developer Kit for Python

Python Slack SDK

The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you can pick just those that fit for your needs. This SDK offers a corresponding package for each of Slack’s APIs. They are small and powerful when used independently, and work seamlessly when used together, too.

Comprehensive documentation on using the Slack Python can be found at https://slack.dev/python-slack-sdk/

pypi package Build Status Python Version codecov contact

Whether you're building a custom app for your team, or integrating a third party service into your Slack workflows, Slack Developer Kit for Python allows you to leverage the flexibility of Python to get your project up and running as quickly as possible.

The Python Slack SDK allows interaction with:

If you want to use our Events API and Interactivity features, please check the Bolt for Python library. Details on the Tokens and Authentication can be found in our Auth Guide.

slackclient is in maintenance mode

Are you looking for slackclient? The website is live here just like before. However, the slackclient project is in maintenance mode now and this slack_sdk is the successor. If you have time to make a migration to slack_sdk v3, please follow our migration guide to ensure your app continues working after updating.

Table of contents

Requirements


This library requires Python 3.6 and above. If you require Python 2, please use our SlackClient - v1.x. If you're unsure how to check what version of Python you're on, you can check it using the following:

Note: You may need to use python3 before your commands to ensure you use the correct Python path. e.g. python3 --version

python --version

-- or --

python3 --version

Installation

We recommend using PyPI to install the Slack Developer Kit for Python.

$ pip install slack_sdk

Getting started tutorial


We've created this tutorial to build a basic Slack app in less than 10 minutes. It requires some general programming knowledge, and Python basics. It focuses on the interacting with Slack's Web and RTM API. Use it to give you an idea of how to use this SDK.

Read the tutorial to get started!

Basic Usage of the Web Client


Slack provide a Web API that gives you the ability to build applications that interact with Slack in a variety of ways. This Development Kit is a module based wrapper that makes interaction with that API easier. We have a basic example here with some of the more common uses but a full list of the available methods are available here. More detailed examples can be found in our guide.

Sending a message to Slack

One of the most common use-cases is sending a message to Slack. If you want to send a message as your app, or as a user, this method can do both. In our examples, we specify the channel name, however it is recommended to use the channel_id where possible. Also, if your app's bot user is not in a channel yet, invite the bot user before running the code snippet (or add chat:write.public to Bot Token Scopes for posting in any public channels).

import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])

try:
    response = client.chat_postMessage(channel='#random', text="Hello world!")
    assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

Here we also ensure that the response back from Slack is a successful one and that the message is the one we sent by using the assert statement.

Uploading files to Slack

We've changed the process for uploading files to Slack to be much easier and straight forward. You can now just include a path to the file directly in the API call and upload it that way. You can find the details on this api call here

import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])

try:
    filepath="./tmp.txt"
    response = client.files_upload(channels='#random', file=filepath)
    assert response["file"]  # the uploaded file
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

Async usage

AsyncWebClient in this SDK requires AIOHttp under the hood for asynchronous requests.

AsyncWebClient in a script

import asyncio
import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.errors import SlackApiError

client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])

async def post_message():
    try:
        response = await client.chat_postMessage(channel='#random', text="Hello world!")
        assert response["message"]["text"] == "Hello world!"
    except SlackApiError as e:
        assert e.response["ok"] is False
        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
        print(f"Got an error: {e.response['error']}")

asyncio.run(post_message())

AsyncWebClient in a framework

If you are using a framework invoking the asyncio event loop like : sanic/jupyter notebook/etc.

import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.errors import SlackApiError

client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])
# Define this as an async function
async def send_to_slack(channel, text):
    try:
        # Don't forget to have await as the client returns asyncio.Future
        response = await client.chat_postMessage(channel=channel, text=text)
        assert response["message"]["text"] == text
    except SlackApiError as e:
        assert e.response["ok"] is False
        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
        raise e

from aiohttp import web

async def handle_requests(request: web.Request) -> web.Response:
    text = 'Hello World!'
    if 'text' in request.query:
        text = "\t".join(request.query.getall("text"))
    try:
        await send_to_slack(channel="#random", text=text)
        return web.json_response(data={'message': 'Done!'})
    except SlackApiError as e:
        return web.json_response(data={'message': f"Failed due to {e.response['error']}"})


if __name__ == "__main__":
    app = web.Application()
    app.add_routes([web.get("/", handle_requests)])
    # e.g., http://localhost:3000/?text=foo&text=bar
    web.run_app(app, host="0.0.0.0", port=3000)

Advanced Options

SSL

You can provide a custom SSL context or disable verification by passing the ssl option, supported by both the RTM and the Web client.

For async requests, see the AIOHttp SSL documentation.

For sync requests, see the urllib SSL documentation.

Proxy

A proxy is supported when making async requests, pass the proxy option, supported by both the RTM and the Web client.

For async requests, see AIOHttp Proxy documentation.

For sync requests, setting either HTTPS_PROXY env variable or the proxy option works.

DNS performance

Using the async client and looking for a performance boost? Installing the optional dependencies (aiodns) may help speed up DNS resolving by the client. We've included it as an extra called "optional":

$ pip install slack_sdk[optional]

Example

import os
from slack_sdk import WebClient
from ssl import SSLContext

sslcert = SSLContext()
# pip3 install proxy.py
# proxy --port 9000 --log-level d
proxyinfo = "http://localhost:9000"

client = WebClient(
    token=os.environ['SLACK_BOT_TOKEN'],
    ssl=sslcert,
    proxy=proxyinfo
)
response = client.chat_postMessage(channel="#random", text="Hello World!")
print(response)

Migrating from v2

If you're migrating from slackclient v2.x of slack_sdk to v3.x, Please follow our migration guide to ensure your app continues working after updating.

Check out the Migration Guide here!

Migrating from v1

If you're migrating from v1.x of slackclient to v2.x, Please follow our migration guide to ensure your app continues working after updating.

Check out the Migration Guide here!

Support


If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:

Use our Github Issue Tracker for reporting bugs or requesting features. Visit the Slack Community for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.

Contributing

We welcome contributions from everyone! Please check out our Contributor's Guide for how to contribute in a helpful and collaborative way.

More Repositories

1

node-slack-sdk

Slack Developer Kit for Node.js
TypeScript
3,270
star
2

bolt-js

A framework to build Slack apps using JavaScript
TypeScript
2,736
star
3

hubot-slack

Slack Developer Kit for Hubot
CoffeeScript
2,300
star
4

bolt-python

A framework to build Slack apps using Python
Python
1,053
star
5

slack-github-action

Send data into Slack using this GitHub Action!
JavaScript
953
star
6

python-rtmbot

A framework for receiving and interacting with events from Slack's RTM API
Python
680
star
7

java-slack-sdk

Slack Developer Kit (including Bolt for Java) for any JVM language
Java
573
star
8

python-slack-events-api

Slack Events API adapter for Python (Flask required)
Python
342
star
9

Slack-Python-Onboarding-Tutorial

a simple python onboarding bot and tutorial for Slack
Python
251
star
10

slack-api-specs

Open API specifications for platform products by Slack
220
star
11

steno

📼 Slack app testing companion - Record and Replay your HTTP requests, both incoming and outgoing
TypeScript
184
star
12

deno-slack-sdk

SDK for building Run on Slack apps using Deno
TypeScript
160
star
13

template-slash-command-and-dialogs

Sample Slack app that uses a Slash Command and interactive message to create helpdesk tickets
JavaScript
141
star
14

node-slack-interactive-messages

Slack Buttons, Menus, and Dialogs made simpler for Node
JavaScript
133
star
15

build-this-bot-workshop

Learn how to build a bot on Slack using Python
127
star
16

reacjilator

A translation bot that translates a message when a user reacted with an emoji 🇨🇳 🇮🇹 🇹🇭 🇫🇷 🇯🇵 🇮🇳 🇺🇸 🇧🇬 🇹🇼 🇦🇪 🇰🇷
JavaScript
110
star
17

onboarding-example

A demonstration of how to build an onboarding app using Slack's Events API
JavaScript
99
star
18

node-tasks-app

Tasks App is a sample Task Management app built on the Slack Platform.
JavaScript
98
star
19

python-message-menu-example

A tutorial for adding Slack message menus to your Python app
Python
97
star
20

slack-platform-assets

Images, templates, and Sketch files to aid designing and presenting your Slack apps
94
star
21

node-slack-events-api

Slack Events API for Node
JavaScript
93
star
22

sample-message-menus-node

An example Slack app that demonstrates use of message menus
JavaScript
91
star
23

python-dialog-example

An example app to demonstrate Slack dialogs
Python
77
star
24

template-announcement-approvals

Sample Slack app that uses the Events API and interactive message to implement an approvals workflow
JavaScript
74
star
25

Slack-Ruby-Onboarding-Tutorial

An example Slack bot written in Ruby
Ruby
64
star
26

bolt-js-getting-started-app

Getting Started Slack app using ⚡️ Bolt for JavaScript
JavaScript
54
star
27

sample-app-unfurls

An example Slack app that demonstrates use of App Unfurls
JavaScript
45
star
28

app-interaction-patterns

A collection of common workflows and interaction patterns for Slack apps.
41
star
29

oauth-tutorial

Slack OAuth setup tutorial using a simple slash command bot
JavaScript
39
star
30

template-triage-bot

Triage Channel Stats w/ Bolt for JS & Shortcuts ⚡️
JavaScript
39
star
31

template-actionable-notifications

Sample Slack app to illustrate how incoming webhooks and interactive messages can be used to build a helpdesk integration
JavaScript
35
star
32

deno-slack-api

Slack API Client for Deno Run on Slack projects
TypeScript
35
star
33

template-terms-of-service

Sample Slack app that uses the Events API and interactive messages to send new users a Terms of Service or welcome message
JavaScript
35
star
34

app-directory-assets

A collection of design assets to help build an app directory submission
34
star
35

template-incident-management

A sample of managing incidents via Slack
TypeScript
34
star
36

template-channel-webhooks

Sample Slack app that uses a Bot to create per-channel webhooks
JavaScript
31
star
37

TalkBot

Building a Twilio-powered Slack bot with Node.js
JavaScript
30
star
38

python-slack-discovery-sdk

This project aims to make using Slack's Discovery APIs easier.
Python
28
star
39

template-channel-naming

Sample Slack app that uses the Events API and interactive message to help enforce channel naming conventions
JavaScript
28
star
40

workflow-powerups

TypeScript
27
star
41

template-action-and-dialog

A sample Slack app "ClipIt", which allows user to clip a message using a message action
JavaScript
27
star
42

sample-message-menus-ruby

An example Slack app in Ruby that demonstrates use of message menus
Ruby
23
star
43

definition-app

A Slack app for storing and accessing company specific phrases
TypeScript
23
star
44

template-account-binding

A sample Slack app that shows you how to bind a Slack user to a user on another system
JavaScript
22
star
45

admin_app_management

Sample application to manage your applications within a Slack organization
TypeScript
20
star
46

pycon-2018

Sample app for Pycon 2018 Slack app workshop
Python
15
star
47

slack-reporting-tool

A Slack app to help administer workspaces by letting team members report offensive messages
TypeScript
15
star
48

deno-slack-runtime

Helper library for running a Run on Slack Deno function
TypeScript
13
star
49

pycon-2019

Pycon 2019 Workshop
Python
12
star
50

deno-slack-hooks

Helper library implementing the contract between the Slack CLI and Slack application SDKs
TypeScript
11
star
51

python-link-button-example

An example app using Slack link buttons and deep links
Python
10
star
52

deno-slack-hub

Connectors used to build coded workflows for Run on Slack apps using Deno
TypeScript
9
star
53

deno-slack-builder

Library for building a Run on Slack Deno project.
TypeScript
9
star
54

bolt-examples-aws-re-invent-2020

A collection of examples to get started with deploying modern ⚡️ Slack apps to AWS Lambda and Amazon Lightsail containers
Java
8
star
55

WeAreDevs

WeAreDevelopers Slack Workshop
Python
7
star
56

manifest-schema

Provide JSON schemas that define Slack's manifest.json file
Python
6
star
57

python-slack-hooks

Helper library implementing the contract between the Slack CLI and Bolt for Python
Python
5
star
58

template-message-linking

Sample Slack APP that uses the Events API to link to a conversation happening in one channel to another
JavaScript
5
star
59

bolt-python-getting-started-app

Getting Started Slack app using ⚡️ Bolt for Python
Python
4
star
60

easy-peasy-bot-custom-integration

DEPRECATED use https://github.com/slackapi/easy-peasy-bot instead
JavaScript
3
star
61

sample-incident-management

JavaScript
3
star
62

sample-code-index

An index of the most up-to-date sample code created by the Slack team
3
star
63

slack-health-score

A GitHub Action to report software project health score
JavaScript
3
star
64

deno-simple

TypeScript
2
star
65

deno-reverse-string

TypeScript
2
star
66

slack-app-time-off

Time-Off Request sample app for Slack's Next Generation Platform
TypeScript
1
star
67

deno-metadata-event

TypeScript
1
star
68

sunny-picnics

🌤🌳🌻🧺🐜👒
1
star
69

deno-budget-calculator

TypeScript
1
star
70

deno-environment-variables

TypeScript
1
star
71

deno-testing-functions

TypeScript
1
star
72

template-ts-clip-message

TypeScript
1
star
73

slack-connect-sample

A sample app which shows off the functionality of the Slack Connect APIs.
JavaScript
1
star
74

deno-slack-protocols

Implements the rules for communication between Slack CLI and any Slack app development SDKs
TypeScript
1
star