DEV Community

Derrick Sherrill for WayScript

Posted on

Trigger a Python Script Using Slack

Introduction

Chances are that you are already using slack in your personal or workplace communications. Let's learn how we can make your slack channels even more powerful. In this tutorial, let's take a look at how we can execute python code whenever a message is sent to a specified channel in slack.

Prerequisites

No prerequisites but some content you might find helpful:

Activating a Script with Slack

In WayScript, we activate our scripts using triggers. We have a variety of different triggers available, but in this tutorial, let's use a slack trigger.

This slack trigger allows us to activate the workflow depending on the event type. In this example, let's say we want to activate whenever a message is posted to a certain, specified channel.

Then, if we want to create personalized response depending on the message text, we can create a variable using the outputs. We do this by selecting the output "Slack Message Text."

Passing the Slack Message to Python

Since we imported the variable of slack message text into our workflow, we can access it anywhere downstream of the trigger. Let's use it in a python module to send back personalized results.

Here, we have limitless options on what we can do with the user's input. We could send requests to different APIs, process the posted data, lookup the data against our databases, and so much more. An example personalized response may be something like sending a request to the website the user has posted in their slack message.

# reading in the variable we created in slack into our python script 
python_variabe_name = variables['Slack_Message_Text'] 
# import default modules 
# If a module isn't already imported, you can install your own modules using the requirements.txt import requests 
# Custom get request depending on slack message contents 
r = requests.get(python_variable_name) 
website_status = r.status_code 
# "Exporting" the variable from python back into the wayscript editor 
variables[ 'wayscript_variable_status' ] =website_status

Sending a Slack Response

We have created the variable we want to send back to the user whenever they post into slack with python, so now we just need a final slack module to finish this operation.

This time, instead of pulling data, we'll be writing data to the same channel the user posted into.

This will write the custom response back to the user whenever they post in that channel.

Questions, Concerns?

If there's any questions feel free to message us on discord. We're happy to help! If you want to see this full script template, you can find it here. If you have any questions of concerns, please feel free to reach out to us on our discord channel.

Top comments (0)