Package: slackclient
Python slackclientImportant NoticeThisslackclientPyPI project is in maintenance mode nowandslack-sdkproject is the successor. The v3 SDK provides more functionalities such as Socket Mode, OAuth flow module, SCIM API, Audit Logs API, better asyncio support, retry handlers, and many more.Refer tothe migration guideto learn how to smoothly migrate your existing code.OverviewThe Pythonslackclientlibrary is a developer kit for interfacing with the Slack Web API and Real Time Messaging (RTM) API on Python 3.6 and above.Comprehensive documentation on using the Slack Python can be found athttps://slack.dev/python-slackclient/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.ThePython slackclientallows interaction with:The Slack web api methods available at ourApi Docs siteInteraction with ourRTM APIIf you want to use ourEvents APIand Interactivity features, please check the [Bolt for Python][bolt-python] library. Details on the Tokens and Authentication can be found in ourAuth Guide.Details on the Tokens and Authentication can be found in ourAuth Guide.Table of contentsRequirementsInstallationGetting started tutorialBasic Usage of the Web ClientSending a message to SlackUploading files to SlackBasic Usage of the RTM ClientAsync usageSlackclient as a scriptSlackclient in a frameworkAdvanced OptionsSSLProxyDNS performanceExampleMigrating from v1SupportRequirementsThis library requires Python 3.6 and above. If you require Python 2, please use ourSlackClient - 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 usepython3before your commands to ensure you use the correct Python path. e.g.python3 --versionpython--version

--or--

python3--versionInstallationWe recommend usingPyPIto install the Slack Developer Kit for Python.$pip3installslackclientGetting started tutorialWe've created thistutorialto 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 ClientSlack 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 availablehere. More detailed examples can be found in ourBasic Usageguide.Sending a message to SlackOne 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 thechannel_idwhere possible. Also, if your app's bot user is not in a channel yet, invite the bot user before running the code snippet (or addchat:write.publicto Bot Token Scopes for posting in any public channels).importosfromslackimportWebClientfromslack.errorsimportSlackApiErrorclient=WebClient(token=os.environ['SLACK_API_TOKEN'])try:response=client.chat_postMessage(channel='#random',text="Hello world!")assertresponse["message"]["text"]=="Hello world!"exceptSlackApiErrorase:# You will get a SlackApiError if "ok" is Falseasserte.response["ok"]isFalseasserte.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 theassertstatement.Uploading files to SlackWe'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 callhereimportosfromslackimportWebClientfromslack.errorsimportSlackApiErrorclient=WebClient(token=os.environ['SLACK_API_TOKEN'])try:filepath="./tmp.txt"response=client.files_upload(channels='#random',file=filepath)assertresponse["file"]# the uploaded fileexceptSlackApiErrorase:# You will get a SlackApiError if "ok" is Falseasserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'print(f"Got an error:{e.response['error']}")Basic Usage of the RTM ClientTheReal Time Messaging (RTM) APIis a WebSocket-based API that allows you to receive events from Slack in real time and send messages as users.If you prefer events to be pushed to you instead, we recommend using the HTTP-basedEvents APIinstead. Most event types supported by the RTM API are also available in the Events API. You can check out ourPython Slack Events Adaptorif you want to use this API instead.An RTMClient allows apps to communicate with the Slack Platform's RTM API.The event-driven architecture of this client allows you to simply link callbacks to their corresponding events. When an event occurs this client executes your callback while passing along any information it receives. We also give you the ability to call our web client from inside your callbacks.In our example below, we watch for amessage eventthat contains "Hello" and if its received, we call thesay_hello()function. We then issue a call to the web client to post back to the channel saying "Hi" to the user.importosfromslackimportRTMClientfromslack.errorsimportSlackApiError@RTMClient.run_on(event='message')defsay_hello(**payload):data=payload['data']web_client=payload['web_client']rtm_client=payload['rtm_client']if'text'indataand'Hello'indata.get('text',[]):channel_id=data['channel']thread_ts=data['ts']user=data['user']try:response=web_client.chat_postMessage(channel=channel_id,text=f"Hi <@{user}>!",thread_ts=thread_ts)exceptSlackApiErrorase:# You will get a SlackApiError if "ok" is Falseasserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'print(f"Got an error:{e.response['error']}")rtm_client=RTMClient(token=os.environ["SLACK_API_TOKEN"])rtm_client.start()Please note that the default way of creating Slack apps no longer supports RTM API. Events using the RTM APImustuse a classic Slack app (with a plainbotscope).If you already have a classic Slack app, you can use those credentials. If you don't and need to use the RTM API, you can create a classic Slack app fromthis link. You can learn more in theAPI documentation.Also, even if the Slack app configuration pages encourage you to upgrade to the newer permission model, don't upgrade it and keep using the "classic" bot permission.Async usageslackclient v2 and higher usesAIOHttpunder the hood for asynchronous requests andurllibfor synchronous requests.Normal usage of the library does not run it in async, hence a kwarg ofrun_async=Trueis needed.When in async mode its important to remember to await or run/run_until_complete the call.Slackclient as a scriptimportasyncioimportosfromslackimportWebClientfromslack.errorsimportSlackApiErrorclient=WebClient(token=os.environ['SLACK_API_TOKEN'],run_async=True)future=client.chat_postMessage(channel='#random',text="Hello world!")loop=asyncio.get_event_loop()try:# run_until_complete returns the Future's result, or raise its exception.response=loop.run_until_complete(future)assertresponse["message"]["text"]=="Hello world!"exceptSlackApiErrorase:asserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'print(f"Got an error:{e.response['error']}")finally:loop.close()Slackclient in a frameworkIf you are using a framework invoking the asyncio event loop like : sanic/jupyter notebook/etc.importosfromslackimportWebClientfromslack.errorsimportSlackApiErrorclient=WebClient(token=os.environ['SLACK_API_TOKEN'],run_async=True# turn async mode on)# Define this as an async functionasyncdefsend_to_slack(channel,text):try:# Don't forget to have await as the client returns asyncio.Futureresponse=awaitclient.chat_postMessage(channel=channel,text=text)assertresponse["message"]["text"]==textexceptSlackApiErrorase:asserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'raisee# https://sanicframework.org/fromsanicimportSanicfromsanic.responseimportjsonapp=Sanic()# e.g., http://localhost:3000/?text=foo&text=bar@app.route('/')asyncdeftest(request):text='Hello World!'if'text'inrequest.args:text="\t".join(request.args['text'])try:awaitsend_to_slack(channel="#random",text=text)returnjson({'message':'Done!'})exceptSlackApiErrorase:returnjson({'message':f"Failed due to{e.response['error']}"})if__name__=='__main__':app.run(host='0.0.0.0',port=3000)Advanced OptionsSSLYou can provide a custom SSL context or disable verification by passing thessloption, supported by both the RTM and the Web client.For async requests, see theAIOHttp SSL documentation.For sync requests, see theurllib SSL documentation.ProxyA proxy is supported when making async requests, pass theproxyoption, supported by both the RTM and the Web client.For async requests, seeAIOHttp Proxy documentation.For sync requests, setting eitherHTTPS_PROXYenv variable or theproxyoption works.DNS performanceUsing 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":$pip3installslackclient[optional]ExampleimportosfromslackimportWebClientfromsslimportSSLContextsslcert=SSLContext()# pip3 install proxy.py# proxy --port 9000 --log-level dproxyinfo="http://localhost:9000"client=WebClient(token=os.environ['SLACK_API_TOKEN'],ssl=sslcert,proxy=proxyinfo)response=client.chat_postMessage(channel="#random",text="Hello World!")print(response)Migrating from v1If 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!SupportWe no longer provide support for v1 or v2 of this SDK and only maintain the latest v3 version. If you would like support from this project's maintainers please consider updating to the latest version of the SDK first. Otherwise, you may visit theSlack Communityfor getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.