Python and Slack: A Natural Match

Python and Slack: A Natural MatchHow to send Slack messages, post plots, and monitor machine learning models programmatically with PythonWilliam KoehrsenBlockedUnblockFollowFollowingDec 1Life opens up when you learn just how much you can do with Python..Anything you can do in apps like Spotify (Spotipy library), Twitter (python-twitter), Wikipedia (Wikipedia API ), and Slack (Slacker for Python), can be accomplished through Python code.This means you’re not constrained to interacting with these services in an app, but instead, can write code to automate complex workflows or build new tools.In this article, we’ll see how to use the Slacker Python library to programmatically interact with Slack..The complete code is available as a Jupyter Notebook on GitHub.Real-time monitoring of machine learning in Slack.Introduction to SlackerSlacker is a Python interface to the Slack API..No matter what you want to do in Slack, you can do it through this library as long as you’re willing to do a little searching!Getting StartedFirst off, you need to create a Slack workspace..Make sure to keep your token in a safe location!Authenticate with Slacker using your API token as follows:from slacker import Slacker# Authenticate with slackerslack = Slacker(slack_api_token)Check that you’re connected by printing out the name of the workspace:# Check for successif slack.api.test().successful: print( f"Connected to {slack.team.info().body['team']['name']}.")else: print('Try Again!')Connected to Data Analysis.Interacting with SlackAnything (okay nearly anything) you can do in slack you can do through the Python interface to the API..The easiest way to pick these out is to go to Slack, search for the emoji you want, and copy the code that appears:Searching for an emoji code.Want to create a new channel and set the purpose?.Two lines of python code:# Create a new channel and set purposeslack.channels.create('python_content_new')slack.channels.set_purpose('python_content_new', 'Data Science and Python')Posting MessagesOf course we don’t just want to be passive consumers of information..Fortunately, Slacker lets us easily post to any channel:# Post a messageslack.chat.post_message(channel='python_content', text='Have a great day!', username='Python Test', icon_url='http://devarea.com/wp-content/uploads/2017/11/python-300×300.png')If we set the username then the messages are posted as bots..Furthermore, if we realize these apps have Python access to their APIs, we can programmatically control them for great efficiency.In this article we saw how to interact with Slack through the Slacker library in Python.. More details

Leave a Reply