How to build a web app that connect with Slack Bolt + Setup webhook
By phuongkt, at: 2024年4月1日9:42
How to build a web app that connect with Slack Bolt + Setup webhook
In this blog post, we'll walk through a journey to build a web app that not only connects with Slack Bolt but also sets up a webhook to interact with Slack events. From setting up your development environment to deploying your first Slack app feature, we'll cover all the steps needed to bring your app from concept to reality. Whether you're a seasoned developer or just starting out, our goal is to equip you with the knowledge and confidence to create a Slack app that can transform the way your team communicates and collaborates.
Let's dive in and unleash the potential of Slack Bolt and webhooks to create engaging, efficient, and impactful Slack apps.
Setting Up the Development Environment
Fisrt these are the requirements and initial setups we need to take care of.
- A Slack account and permissions to create apps within your workspace. If you haven't got one, you can register a new slack account here Slack Create New Account!
- Python 3.6 or later installed on your machine. You can download it from Python.org.
- pip and virtualenv for managing Python packages and environments. These tools usually come with Python, but you can find installation instructions here if needed.
Then create a new slack app
- Navigate to the Slack API: Visit the Slack API website and login if necessary
- Create a New App: Click on the "Create New App" button. Choose "From scratch" and give your app a name. Select the Slack workspace you want to install your app to.
- Basic App Configuration: After creating your app, you'll be redirected to the app's configuration page. Take note of the "Signing Secret" under the "App Credentials" section; you'll need it later.
Finally, we come to Environment Setup
- Create a Project Directory: From your terminal
mkdir slack_app && cd slack app
- Create a Virtual Environment:
python3 -m venv env
- On macOS/Linux
source env/bin/activate
- On Windows
.\env\Scripts\activate
- On macOS/Linux
- Install Slack Bolt for Python:
pip install slack_bolt
After all the initial set up steps, we're all set to start designing our slack app, let's first run a basic Bolt App
- Create a New Python File: In your project directory, create a file named app.py.
- Add the Following Code to app.py:
from slack_bolt import App
# Initializes your app with your bot token and signing secret
app = App(token="your-bot-token", signing_secret="your-signing-secret")
# Add functionality here
if __name__ == "__main__":
app.start(port=3000)
Replace "your-bot-token" and "your-signing-secret" with the credentials from your Slack app's settings.
- Run Your App:
python app.py
Connecting Your App with Slack
Having laid the foundation by setting up the development environment and gaining an understanding of Slack Bolt for Python, it's time to dive into how to connect your app with Slack more deeply. This part will cover configuring your Slack app in the API dashboard, authenticating your app with Slack using OAuth 2.0, and listening to more sophisticated events and interactions.
Configuring Your App in Slack API Dashboard
To ensure smooth communication between your app and Slack, you need to configure your Slack app with the necessary OAuth scopes, event subscriptions, and interactive components if you haven't done so already.
- OAuth & Permissions:
- Navigate to the "OAuth & Permissions" page in your app's settings on the Slack API dashboard.
- Under "Scopes", add the necessary bot token scopes for the functionalities you plan to implement. For example, chat:write to send
messages, commands to use slash commands, and app_mentions:read to respond to app mentions.
- Save your changes.
- Navigate to the "OAuth & Permissions" page in your app's settings on the Slack API dashboard.
- Event Subscriptions:
- If not already set up in previous step, go to "Event Subscriptions" and enable events.
- Input your Request URL, which Slack will use to send event notifications. This URL should point to your server where Slack Bolt is running. If you're testing locally, this will be your ngrok URL followed by /slack/events.
- Subscribe to workspace or bot events as required by your app's functionality.
- If not already set up in previous step, go to "Event Subscriptions" and enable events.
- Interactivity & Shortcuts:
- Visit the "Interactivity & Shortcuts" section and toggle the Interactivity switch to "On".
- Set the Request URL, similar to the Event Subscriptions section. This URL is where Slack will send data from interactive components like buttons, modals, and menus.
- Visit the "Interactivity & Shortcuts" section and toggle the Interactivity switch to "On".
Moving on we need to Authenticating Your App with Slack (OAuth 2.0)
OAuth 2.0 is a protocol that allows your app to request authorization to access specific information or perform actions on behalf of a user. Slack uses OAuth 2.0 for app authentication, enabling users to securely install and interact with your app.
- Implementing OAuth Flow:
from slack_bolt import App
from slack_bolt.oauth.oauth_settings import OAuthSettings
app = App(
signing_secret="your-signing-secret",
oauth_settings=OAuthSettings(
client_id="your-client-id",
client_secret="your-client-secret",
scopes=["chat:write", "commands", "app_mentions:read"]
)
)
- Initiating OAuth Flow:
- Direct users to install your app by providing an "Add to Slack" button on your app or website. This button should link to the Slack authorization URL with your app's client ID.
- Once the user initiates the installation process, Slack will redirect them to your OAuth redirect URI with a code parameter.
- Your app will exchange this code for an access token using Slack's OAuth API.
- Direct users to install your app by providing an "Add to Slack" button on your app or website. This button should link to the Slack authorization URL with your app's client ID.
With OAuth set up, your app can now interact more deeply with Slack, responding to specific user interactions, commands, and events.
Setting Up Webhooks
Webhooks are HTTP callbacks that send data to a specified URL in response to an event. In the context of Slack, webhooks allow your app to receive JSON payloads containing data about events happening in Slack, such as new messages in a channel or reactions added to a message.
We've already set up Event Subscriptions in previous sections for events like messages and mentions. Now, let's focus on securing those webhook endpoints. Securing your webhook endpoints is crucial to prevent unauthorized access and ensure that the data being sent to your app is from Slack.
Setting Up a Secure Webhook Endpoint in Python
from flask import Flask, request, abort
import hmac
import hashlib
app = Flask(__name__)
@app.route("/slack/events", methods=["POST"])
def slack_events():
timestamp = request.headers.get('X-Slack-Request-Timestamp')
slack_signature = request.headers.get('X-Slack-Signature')
request_body = request.get_data().decode('utf-8')
basestring = f"v0:{timestamp}:{request_body}".encode('utf-8')
my_signature = 'v0=' + hmac.new(b"your-signing-secret", basestring, hashlib.sha256).hexdigest()
if not hmac.compare_digest(my_signature, slack_signature):
abort(400)
# Process the event here
return "OK", 200
if __name__ == "__main__":
app.start(port=3000)
Developing Your Desired Features
Now you can let your imagination guide you to design complex slack app that suits yours, or your company's needs.
Conclusion
Building a web app that connects with Slack using the Slack Bolt framework and setting up webhooks can transform how teams interact within Slack, streamlining workflows and enhancing productivity. Throughout this blog post, we’ve journeyed from setting up your development environment and understanding the Slack Bolt framework, to connecting your app with Slack and securing webhooks. Each step is designed to equip you with the knowledge to create a Slack app that not only responds to user interactions in real-time but also remains secure and scalable. Best Luck!