Make a simple Slackbot with interactive button in python

I tried to create an interactive slackbot with buttons in python using SW. If it is written by other people, it is usually quite complicated with node.js and I am not good at javascript, so I want to avoid it as much as possible and do it with python! So I tried to make it as simple as possible using flask + heroku + slack client. Slack bots with buttons have a reputation for being bothersome and popular, so I'm wondering if this article can be used as a reference to make it relatively quick.

The code is available here [https://github.com/sh-tatsuno/slackbot_python_server).

Premise

--Installing pyenv, pyenv-virtualenv --Register on heroku --A suitable slack account

Please prepare these in advance.

Preparation on slack

This is quite a hassle, but let's do our best.

--Creating a slack app Log in to here and create a new slack app. スクリーンショット 2017-09-17 23.22.29.png The App Name can be anything, but for Workspace, specify the team you want to use the bot with.

Then go to basic information. At this time, please save the following Verification Token.

スクリーンショット 2017-09-17 23.14.08.png

Next, we will make settings for the bot. Set the following Interactive Messages and Permissions. スクリーンショット 2017-09-17 23.12.32.png

--Interactive Messages settings Specify the URL to redirect to when you press the button. This time we will redirect to'slack / json_html' on heroku. スクリーンショット 2017-09-17 23.12.51.png

--Permissions setting Let's set the required permissions from the Scope near the center of the page. Is it Send messages system for the time being? Next, let's issue an OAuth Token from Tokens for Your Workspace at the top of the page. Please keep this as well.

スクリーンショット 2017-09-17 23.38.11.png

Creating a project

Now, let's make the server side from here.

--Creating a python environment

Create a project and install a virtualenv environment. The necessary libraries will also be installed at this time.

$ mkdir slackbot_python_server
$ cd slackbot_python_server
$ pyenv virtualenv 3.6.2 heroku_python_3.6.2
$ pyenv local heroku_python_3.6.2
$ pip install Flask gunicorn slackclient
$ echo .python-version >> .gitignore
$ pip freeze > requirements.txt

--Create a Procfile

$ echo web: gunicorn main:app --log-file=- > Procfile

--Create main.py

First, define the slack client and the flask server. SLACK_BOT_TOKEN and SLACK_VERIFICATION_TOKEN will be set later in heroku as environment variables.

main.py


from flask import Flask, request, make_response, Response
import os
import json

from slackclient import SlackClient


# Your app's Slack bot user token
SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN")
SLACK_VERIFICATION_TOKEN = os.environ.get("SLACK_VERIFICATION_TOKEN")

# Slack client for Web API requests
slack_client = SlackClient(SLACK_BOT_TOKEN)

# Flask webserver for incoming traffic from Slack
app = Flask(__name__)

Next, define the attachments for the button post. At this time, set each element of the button in the action part. It seems that you can enter any id you like for call_back_id.

main.py


# your attachment
attachments_json = [
    {
        "fallback": "Upgrade your Slack client to use messages like these.",
        "color": "#258ab5",
        "attachment_type": "default",
        "callback_id": "the_greatest_war",
        "actions": [
            {
                "name": "choco1",
                "text": "mushroom",
                "value": "kinoko",
                "type": "button"
            },
            {
                "name": "choco2",
                "text": "bambooshoot",
                "value": "takenoko",
                "type": "button"
            }
        ]
    }
]

Set the root part. When a request comes in with GET, slack_client.api_call is called and a post with a button is posted on the general channel. The element set earlier is entered in attachments_json.

main.py


#route
#when you access such as curl command, slackbot post interactive message
@app.route("/", methods=["GET"])
def index():
    slack_client.api_call(
        "chat.postMessage",
        channel="#general",
        text="Which school are you?",
        attachments=attachments_json
    )
    return make_response("", 200)

Finally, create the redirect part when the button is pressed. Since form_json ["actions"] [0] ["value"] contains the value selected by the previous button, it branches based on this value and returns the statement.

main.py


#redirect from button
@app.route("/slack/json_html", methods=["POST"])
def json_html():

    # Parse the request payload
    form_json = json.loads(request.form["payload"])

    val = form_json["actions"][0]["value"]
    if val == "kinoko":
        response_text = "All right, then it's a war"
    else:
        response_text = "All right, then ally"
    response = slack_client.api_call(
        "chat.postMessage",
        channel="#general",
        text=response_text,
        attachments=[]
    )

    return make_response("", 200)

This completes main.py.

--git heroku settings

Set up git.

$ git init 
$ git add .
$ git commit -m "first commit"

Create and configure heroku. In addition to creating a heroku project, set the environment variables of the Token obtained earlier in Slack.

$ heroku login
$ heroku create <app-name>
$ heroku config:set SLACK_BOT_TOKEN = "<The OAuth Token you just got>" SLACK_VERIFICATION_TOKEN = "<Verification Token acquired earlier>"  --app "<app-name>"

Deployment and operation check

Push the project to heroku with the following command.

$ git push heroku master

Now, send a request to the app given to heroku with the following command and check the operation.

$ curl https://<heroku apps>.herokuapp.com/

At this time, if the button is posted to general and it works, it is successful. スクリーンショット 2017-09-18 0.29.03.png

Afterword

At first, I did it with python's slackbot and got stuck in a jar. I had a hard time with slackclient because there weren't many articles in Japanese, but when I looked it up, it seems that it can be selected by a list and various options can be made, so it seems to be quite convenient (probably the same as js). ). Please give it a try.

References

-Deploy Flask app on heroku -Create a Slack bot with Python's slackbot library -I tried using buttons and interactive messages in Slack's Botkit

Recommended Posts

Make a simple Slackbot with interactive button in python
[Python] Make a simple maze game with Pyxel
Make a bookmarklet in Python
Make a fortune with Python
Let's make a simple game with Python 3 and iPhone
What is God? Make a simple chatbot with python
Let's make a GUI with python.
Make a recommender system with python
[Python] Generate a password with Slackbot
Implementing a simple algorithm in Python 2
Let's make a graph with python! !!
Run a simple algorithm in Python
I made a simple typing game with tkinter in Python
[Python] Make a simple maze game with Pyxel-Make enemies appear-
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Creating a simple PowerPoint file with Python
Let's make a shiritori game with Python
A simple HTTP client implemented in Python
Rubyist tried to make a simple API with Python + bottle + MySQL
Try drawing a simple animation in Python
Create a simple GUI app in Python
Make a simple OMR (mark sheet reader) with Python and OpenCV
Let's make a voice slowly with Python
Let's make a simple language with PLY 1
Write a simple greedy algorithm in Python
Write a simple Vim Plugin in Python 3
Let's make a web framework with Python! (1)
Let's make a combination calculation in Python
Make a desktop app with Python with Electron
Let's make a Twitter Bot with Python!
Let's make a web framework with Python! (2)
I made a simple blackjack with Python
Set up a simple HTTPS server in Python 3
[Python] Get the files in a folder with Python
Make a Twitter trend bot with heroku + Python
Make a simple pixel art generator with Flask
Create a virtual environment with conda in Python
Start a simple Python web server with Docker
Make a copy of the list in Python
Try to make a "cryptanalysis" cipher with Python
Make a rock-paper-scissors game in one line (python)
A simple Pub / Sub program note in Python
Create a simple momentum investment model in Python
Let's replace UWSC with Python (5) Let's make a Robot
Work in a virtual environment with Python virtualenv.
Make a joyplot-like plot of R in python
Create a new page in confluence with Python
Try to make a dihedral group with Python
Set up a simple SMTP server in Python
A simple to-do list created with Python + Django
Simple gRPC in Python
Make a Nyan button
Slackbot development in Python
Put Docker in Windows Home and run a simple web server with Python
I tried to make a simple mail sending application with tkinter of Python
Make one repeating string with a Python regular expression.
How to convert / restore a string with [] in python
Try to make a Python module in C language
Write a super simple molecular dynamics program in python
I want to transition with a button in flask
Try to make a command standby tool with python