It is time to send your first message using the Slack API and Python.
Sending a message is very simple, even for Python beginners. I will show you the step-by-step code to send a message to Slack with Python.
If you know nothing about python, I suggest that you check out my complete guide on Python for SEO.
Let’s dive into it.
Get Slack Credentials
All you need is to get your Slack API Credentials Webhooks added to a credentials.json
file.
Install the Requests Python Package
In this tutorial, you will need the requests package. In Terminal type:
$ pip install requests
Define Message and Credentials Location
credentials = 'credentials.json'
message = 'My first automated slack post'
Read Your Credentials
- Now we will read the json file where the webhook is.
import json
def get_credentials(credentials):
'''
Read credentials from JSON file.
'''
with open(credentials, 'r') as f:
creds = json.load(f)
return creds['slack_webhook']
2. Alternatively, you could add your credentials straight into the code, but it is less recommended since you could share your private credentials by error.
You would do it this way.
credentials = 'https://hooks.slack.com/services/XXXXXXXXXXX'
Both 1 and 2 are viable ways to run the code.
Create the Function to post to Slack
Now let’s define the function to let us post to slack.
The function uses requests
to post to Slack.
def post_to_slack(message,credentials):
data = {'text':message}
url = get_credentials(credentials)
requests.post(url,json=data, verify=False)
Run the Code
Now, let’s run the code:
if __name__ == '__main__':
post_to_slack(message,credentials)
The if name equals main line checks whether you are running the module or importing it. If you are importing it, post_to_slack()
will not run.
Full Code
#!/usr/bin/env python
import json
import requests
credentials = 'credentials.json'
message = 'My first automated slack post'
def get_credentials(credentials):
'''
Read credentials from JSON file.
'''
with open(credentials, 'r') as f:
creds = json.load(f)
return creds['slack_webhook']
def post_to_slack(message,credentials):
data = {'text':message}
url = get_credentials(credentials)
requests.post(url,json=data, verify=False)
if __name__ == '__main__':
post_to_slack(message,credentials)
This is it, you now have sent your first message to Slack using the API and Python. Next step is to try to make an automated robots.txt checker.
SEO Strategist at Tripadvisor, ex- Seek (Melbourne, Australia). Specialized in technical SEO. Writer in Python, Information Retrieval, SEO and machine learning. Guest author at SearchEngineJournal, SearchEngineLand and OnCrawl.