When creating a slack app, if you want to install it in only one workspace, you can manually install it from the app's ** settings page **. However, if you want to install the app personally or finally ** publish it in the Slack directory, you need to install it with OAuth authentication.
I think that the mechanism of OAuth authentication of slack is the same as the general one.
import os
import slack
from flask import Flask, request, make_response
client_id = os.environ["SLACK_CLIENT_ID"]
client_secret = os.environ["SLACK_CLIENT_SECRET"]
#Add the scope required by the app here.
oauth_scope = ",".join([
"channels:history",
"groups:history",
"im:history",
"mpim:history",
"chat:write"
]) #os.environ["SLACK_BOT_SCOPE"]
uuids = []
app = Flask(__name__)
@app.route("/begin_auth", methods=["GET"])
def pre_install():
"""Create a link to jump to the OAuth authentication page of slack and display it."""
from uuid import uuid4
state_string = str(uuid4())
uuids.append(state_string)
return f'<a href="https://slack.com/oauth/v2/authorize?scope={ oauth_scope }&client_id={ client_id }&state={ state_string}">Add to Slack</a>'
@app.route("/finish_auth", methods=["GET", "POST"])
def post_install():
"""It is the processing of redirected access after authentication is completed."""
auth_code = request.args['code']
state_code = request.args['state']
#state_401 if the codes do not match
if not state_code in uuids:
return make_response("", 401)
else:
uuids.remove(state_code)
#To authenticate, create a client with a blank token.
client = slack.WebClient(token="")
#Request an authentication token.
response = client.oauth_v2_access(
client_id=client_id,
client_secret=client_secret,
code=auth_code
)
#Save the slack bot token in DB etc.
SLACK_BOT_TOKEN = response['access_token']
#Don't forget to tell your users success!
return make_response("Authentication successful!!", 200)
app.run()
ʻApp> Basic Information> OAuth & Permissions> Register http: // localhost: 5000 / finish_auth
in Redirect URLs`.
Save with Save URLs
Now you are ready
Start flask and go to http: // localhost: 5000 / begin_auth
.
Clicking on the link will ask you to authenticate with slack.
Press Allow to move to the next screen and generate a token at that time. If the UUID4 for verification matches, remove it from the list and use the slackClient to get an access token.
I didn't write it in this code, but let's save the obtained access token for the next use.
slack API Japanese document Installing with OAuth
Recommended Posts