X Tutup
Skip to content

Commit 3eff6a1

Browse files
mwbrooksseratchshaydewael
committed
[slackapi#70 slackapi#71] Add Getting started guide and sample app
* [slackapi#70] Add 'Create an app' section * [slackapi#70] Add 'Tokens and installing apps' section * [slackapi#70] Add 'Setting up your local project' section * [slackapi#70] Add 'Setting up events' section * [slackapi#70] Add 'Listening and responding to a message' section * [slackapi#70] Add 'Sending and responding to actions' section * [slackapi#70] Add 'Next steps' section * [slackapi#70] Stub a details section for setting up a Python virtual environment * [slackapi#70] Update MacOS to macOS to reflect the modern naming convention. - Based on feedback from @seratch - See https://github.com/slackapi/bolt-python/pull/71/files#r485996903 * [slackapi#70] Update Python code samples to use 4 spaces. - Thanks @seratch slackapi#71 (comment) * [slackapi#70] Update wording of a Python package - Thanks @seratch slackapi#71 (comment) * [slackapi#70] Update 'python' command usage to 'python3' to help all audiences - Thanks @seratch slackapi#71 (comment) * [slackapi#70] Update responds with "Hey there @user!" for consistency. - Thanks @seratch slackapi#71 (comment) * Update 130 to 220 Web API methods - Thanks @seratch slackapi#71 (comment) Co-authored-by: Kazuhiro Sera <seratch@gmail.com> * [slackapi#70] Remove completed TODO comments. * [slackapi#70] Fix number list to display correctly. * [slackapi#70] Adjust "Listening and Responding to a Message" section for clarity - Bring in changes from https://github.com/slackapi/bolt-js/pull/600/files * [slackapi#70] Refactor 'reply_to_hello' to 'message_hello' for consistency * [slackapi#70] Remove details section for setting up a Python virtual environment * [slackapi#70] Update the virtual environment directory name. The official Python 3 tutorial recommends using .venv as the directory name of a virtual environment because it's hidden by many systems/editors and doesn't conflict with some system conventions of .env https://docs.python.org/3/tutorial/venv.html#creating-virtual-environments * [slackapi#70] Emphasize that python3 will be inside your virtual environment project * [slackapi#70] Add getting started app to samples * [slackapi#70] Remove completed TODO comments. * [slackapi#70] Update event scopes to be a list * [slackapi#70] Remove completed TODOs * [slackapi#70] Mention that Python 3.6 or later is required for 'slack_bolt' * [slackapi#70] Remove TODO for argument order best practice. - We decided to match the bolt-js docs as a first step - See slackapi#71 (comment) - Thanks, @misscoded! * [slackapi#70] .gitignore env*/ in the getting_started sample app See slackapi#71 (comment) * [slackapi#70] Update message.im scope description - See slackapi#71 (comment) * [slackapi#70] Update wording of 'dialogs' to 'modals' - See slackapi#71 (comment) Co-authored-by: Shay DeWael <swdewael@gmail.com> * [slackapi#70] Update wording of interactivity setup - See slackapi#71 (comment) Co-authored-by: Shay DeWael <swdewael@gmail.com> * [slackapi#70] Update wording for modifying the code base - See slackapi#71 (comment) Co-authored-by: Shay DeWael <swdewael@gmail.com> * [slackapi#70] Update explaination of say() to align with bolt-js and clarify text role - See slackapi#71 (comment) - See slackapi#71 (comment) * [slackapi#70] Link to Getting Started app at beginning and end of guide. - See slackapi#71 (comment) * [slackapi#70] Update link to Block Kit Builder - See slackapi#71 (comment) * [slackapi#70] Update action_id explaination to be clearer. - See slackapi#71 (comment) Co-authored-by: Kazuhiro Sera <seratch@gmail.com> Co-authored-by: Shay DeWael <swdewael@gmail.com>
1 parent 7db2f7c commit 3eff6a1

File tree

5 files changed

+412
-1
lines changed

5 files changed

+412
-1
lines changed

docs/_tutorials/getting_started.md

Lines changed: 318 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,321 @@ redirect_from:
1212

1313
<div class="section-content">
1414
This guide is meant to walk you through getting up and running with a Slack app using Bolt for Python. Along the way, we’ll create a new Slack app, set up your local environment, and develop an app that listens and responds to messages from a Slack workspace.
15-
</div>
15+
</div>
16+
17+
When you're finished, you'll have this ⚡️[Getting Started with Slack app](https://github.com/slackapi/bolt-python/tree/main/samples/getting_started) to run, modify, and make your own.
18+
19+
---
20+
21+
### Create an app
22+
First thing's first: before you start developing with Bolt, you'll want to [create a Slack app](https://api.slack.com/apps/new).
23+
24+
> 💡 We recommend using a workspace where you won't disrupt real work getting done — [you can create a new one for free](https://slack.com/get-started#create).
25+
26+
After you fill out an app name (_you can change it later_) and pick a workspace to install it to, hit the `Create App` button and you'll land on your app's **Basic Information** page.
27+
28+
This page contains an overview of your app in addition to important credentials you'll need later, like the `Signing Secret` under the **App Credentials** header.
29+
30+
![Basic Information page](../assets/basic-information-page.png "Basic Information page")
31+
32+
Look around, add an app icon and description, and then let's start configuring your app 🔩
33+
34+
---
35+
36+
### Tokens and installing apps
37+
Slack apps use [OAuth to manage access to Slack's APIs](https://api.slack.com/docs/oauth). When an app is installed, you'll receive a token that the app can use to call API methods.
38+
39+
There are two token types available to a Slack app: user (`xoxp`) and bot (`xoxb`) tokens. User tokens allow you to call API methods on behalf of users after they install or authenticate the app. There may be several user tokens for a single workspace. Bot tokens are associated with bot users, and are only granted once in a workspace where someone installs the app. The bot token your app uses will be the same no matter which user performed the installation. Bot tokens are the token type that _most_ apps use.
40+
41+
For brevity, we're going to use bot tokens for this guide.
42+
43+
Navigate to the **OAuth & Permissions** on the left sidebar and scroll down to the **Bot Token Scopes** section. Click **Add an OAuth Scope**.
44+
45+
For now, we'll just add one scope: [`chat:write`](https://api.slack.com/scopes/chat:write). This grants your app the permission to post messages in channels it's a member of.
46+
47+
Scroll up to the top of the OAuth & Permissions page and click **Install App to Workspace**. You'll be led through Slack's OAuth UI, where you should allow your app to be installed to your development workspace.
48+
49+
Once you authorize the installation, you'll land on the **OAuth & Permissions** page and see a **Bot User OAuth Access Token**.
50+
51+
![OAuth Tokens](../assets/bot-token.png "Bot OAuth Token")
52+
53+
> 💡 Treat your token like a password and [keep it safe](https://api.slack.com/docs/oauth-safety). Your app uses it to post and retrieve information from Slack workspaces.
54+
55+
---
56+
57+
### Setting up your local project
58+
With the initial configuration handled, it's time to set up a new Bolt project. This is where you'll write the code that handles the logic for your app.
59+
60+
If you don’t already have a project, let’s create a new one. Create an empty directory:
61+
62+
```shell
63+
mkdir first-bolt-app
64+
cd first-bolt-app
65+
```
66+
67+
Next, we recommend using a [Python virtual environment](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment) to manage your project's dependencies. This is a great way to prevent conflicts with your system's Python packages. Let's create and activate a new virtual environment with [Python 3.6 or later](https://www.python.org/downloads/):
68+
69+
```shell
70+
python3 -m venv .venv
71+
source .venv/bin/activate
72+
```
73+
74+
We can confirm that the virtual environment is active by checking that the path to `python3` is _inside_ your project ([a similar command is available on Windows](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#activating-a-virtual-environment)):
75+
76+
```shell
77+
which python3
78+
# Output: /path/to/first-bolt-app/.venv/bin/python3
79+
```
80+
81+
Before we install the Bolt for Python package to your new project, let's save the bot token and signing secret that was generated when you configured your app. These should be stored as environment variables and should *not* be saved in version control.
82+
83+
1. **Copy your Signing Secret from the Basic Information page** and then store it in a new environment variable. The following example works on Linux and macOS; but [similar commands are available on Windows](https://superuser.com/questions/212150/how-to-set-env-variable-in-windows-cmd-line/212153#212153).
84+
```shell
85+
export SLACK_SIGNING_SECRET=<your-signing-secret>
86+
```
87+
88+
2. **Copy your bot (xoxb) token from the OAuth & Permissions page** and store it in another environment variable.
89+
```shell
90+
export SLACK_BOT_TOKEN=xoxb-<your-bot-token>
91+
```
92+
93+
Now, lets create your app. Install the `slack_bolt` Python package to your virtual environment using the following command:
94+
95+
```shell
96+
pip install slack_bolt
97+
```
98+
99+
Create a new file called `app.py` in this directory and add the following code:
100+
101+
```python
102+
import os
103+
from slack_bolt import App
104+
105+
# Initializes your app with your bot token and signing secret
106+
app = App(
107+
token=os.environ.get("SLACK_BOT_TOKEN"),
108+
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
109+
)
110+
111+
# Start your app
112+
if __name__ == "__main__":
113+
app.start(port=int(os.environ.get("PORT", 3000)))
114+
```
115+
116+
Your token and signing secret are enough to create your first Bolt app. Save your `app.py` file then on the command line run the following:
117+
118+
```script
119+
python3 app.py
120+
```
121+
122+
Your app should let you know that it's up and running.
123+
124+
---
125+
126+
### Setting up events
127+
Your app behaves similarly to people on your team — it can post messages, add emoji reactions, and more. To listen for events happening in a Slack workspace (like when a message is posted or when a reaction is posted to a message) you'll use the [Events API to subscribe to event types](https://api.slack.com/events-api).
128+
129+
To enable events for your app, start by going back to your app configuration page (click on the app [from your app management page](https://api.slack.com/apps)). Click **Event Subscriptions** on the left sidebar. Toggle the switch labeled **Enable Events**.
130+
131+
You'll see a text input labeled **Request URL**. The Request URL is a public URL where Slack will send HTTP POST requests corresponding to events you specify.
132+
133+
> ⚙️We've collected some of the most common hosting providers Slack developers use to host their apps [on our API site](https://api.slack.com/docs/hosting)
134+
135+
When an event occurs, Slack will send your app some information about the event, like the user that triggered it and the channel it occurred in. Your app will process the details and can respond accordingly.
136+
137+
<details>
138+
<summary markdown="0">
139+
<h4>Using a local Request URL for development</h4>
140+
</summary>
141+
142+
If you’re just getting started with your app's development, you probably don’t have a publicly accessible URL yet. Eventually, you’ll want to set one up, but for now a development proxy like [ngrok](https://ngrok.com/) will create a public URL and tunnel requests to your own development environment. We've written a separate tutorial about [using ngrok with Slack for local development](https://api.slack.com/tutorials/tunneling-with-ngrok) that should help you get everything set up.
143+
144+
Once you’ve installed a development proxy, run it to begin forwarding requests to a specific port (we’re using port `3000` for this example, but if you customized the port used to initialize your app use that port instead):
145+
146+
```shell
147+
ngrok http 3000
148+
```
149+
150+
![Running ngrok](../assets/ngrok.gif "Running ngrok")
151+
152+
The output should show a generated URL that you can use (we recommend the one that starts with `https://`). This URL will be the base of your request URL, in this case `https://8e8ec2d7.ngrok.io`.
153+
154+
---
155+
</details>
156+
157+
Now you have a public-facing URL for your app that tunnels to your local machine. The Request URL that you use in your app configuration is composed of your public-facing URL combined with the URL your app is listening on. By default, Bolt apps listen at `/slack/events` so our full request URL would be `https://8e8ec2d7.ngrok.io/slack/events`.
158+
159+
> ⚙️Bolt uses the `/slack/events` endpoint to listen to all incoming requests (whether shortcuts, events, or interactivity payloads). When configuring endpoints within your app configuration, you'll append `/slack/events` to all request URLs.
160+
161+
Under the **Enable Events** switch in the **Request URL** box, go ahead and paste in your URL. As long as your Bolt app is still running, your URL should become verified.
162+
163+
After your request URL is verified, scroll down to **Subscribe to Bot Events**. There are four events related to messages:
164+
- `message.channels` listens for messages in public channels that your app is added to
165+
- `message.groups` listens for messages in private channels that your app is added to
166+
- `message.im` listens for messages in your app's DMs with users
167+
- `message.mpim` listens for messages in multi-person DMs that your app is added to
168+
169+
If you want your bot to listen to messages from everywhere it is added to, choose all four message events. After you’ve selected the events you want your bot to listen to, click the green **Save Changes** button.
170+
171+
---
172+
173+
### Listening and responding to a message
174+
Your app is now ready for some logic. Let's start by using the `message()` method to attach a listener for messages.
175+
176+
The following example listens and responds to all messages in channels/DMs where your app has been added that contain the word "hello":
177+
178+
```python
179+
import os
180+
from slack_bolt import App
181+
182+
# Initializes your app with your bot token and signing secret
183+
app = App(
184+
token=os.environ.get("SLACK_BOT_TOKEN"),
185+
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
186+
)
187+
188+
# Listens to incoming messages that contain "hello"
189+
@app.message("hello")
190+
def message_hello(message, say):
191+
# say() sends a message to the channel where the event was triggered
192+
say(f"Hey there <@{message['user']}>!")
193+
194+
# Start your app
195+
if __name__ == "__main__":
196+
app.start(port=int(os.environ.get("PORT", 3000)))
197+
```
198+
199+
If you restart your app, so long as your bot user has been added to the channel/DM, when you send any message that contains "hello", it will respond.
200+
201+
This is a basic example, but it gives you a place to start customizing your app based on your own goals. Let's try something a little more interactive by sending a button rather than plain text.
202+
203+
---
204+
205+
### Sending and responding to actions
206+
207+
To use features like buttons, select menus, datepickers, modals, and shortcuts, you’ll need to enable interactivity. Similar to events, you'll need to specify a URL for Slack to send the action (such as *user clicked a button*).
208+
209+
Back on your app configuration page, click on **Interactivity & Shortcuts** on the left side. You'll see that there's another **Request URL** box.
210+
211+
By default, Bolt is configured to use the same endpoint for interactive components that it uses for events, so use the same request URL as above (in the example, it was `https://8e8ec2d7.ngrok.io/slack/events`). Press the **Save Changes** button in the lower right hand corner, and that's it. Your app is set up to handle interactivity!
212+
213+
![Configuring a Request URL](../assets/request-url-config.png "Configuring a Request URL")
214+
215+
Now, let's go back to your app's code and add interactivity. This will consist of two steps:
216+
- First, your app will send a message that contains a button.
217+
- Next, your app will listen to the action of a user clicking the button and respond
218+
219+
Below, the code from the last section is modified to send a message containing a button rather than just a string:
220+
221+
```python
222+
import os
223+
from slack_bolt import App
224+
225+
# Initializes your app with your bot token and signing secret
226+
app = App(
227+
token=os.environ.get("SLACK_BOT_TOKEN"),
228+
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
229+
)
230+
231+
# Listens to incoming messages that contain "hello"
232+
@app.message("hello")
233+
def message_hello(message, say):
234+
# say() sends a message to the channel where the event was triggered
235+
say(
236+
blocks=[
237+
{
238+
"type": "section",
239+
"text": {
240+
"type": "mrkdwn",
241+
"text": f"Hey there <@{message['user']}>!"
242+
},
243+
"accessory": {
244+
"type": "button",
245+
"text": {
246+
"type": "plain_text",
247+
"text": "Click Me"
248+
},
249+
"action_id": "button_click"
250+
}
251+
}
252+
],
253+
text=f"Hey there <@{message['user']}>!"
254+
)
255+
256+
# Start your app
257+
if __name__ == "__main__":
258+
app.start(port=int(os.environ.get("PORT", 3000)))
259+
```
260+
261+
The value inside of `say()` is now an object that contains an array of `blocks`. Blocks are the building components of a Slack message and can range from text to images to datepickers. In this case, your app will respond with a section block that includes a button as an accessory. Since we're using `blocks`, the `text` is a fallback for notifications and accessibility.
262+
263+
You'll notice in the button `accessory` object, there is an `action_id`. This will act as a unique identifier for the button so your app can specify what action it wants to respond to.
264+
265+
> 💡 The [Block Kit Builder](https://app.slack.com/block-kit-builder) is an simple way to prototype your interactive messages. The builder lets you (or anyone on your team) mockup messages and generates the corresponding JSON that you can paste directly in your app.
266+
267+
Now, if you restart your app and say "hello" in a channel your app is in, you'll see a message with a button. But if you click the button, nothing happens (*yet!*).
268+
269+
Let's add a handler to send a followup message when someone clicks the button:
270+
271+
```python
272+
import os
273+
from slack_bolt import App
274+
275+
# Initializes your app with your bot token and signing secret
276+
app = App(
277+
token=os.environ.get("SLACK_BOT_TOKEN"),
278+
signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
279+
)
280+
281+
# Listens to incoming messages that contain "hello"
282+
@app.message("hello")
283+
def message_hello(message, say):
284+
# say() sends a message to the channel where the event was triggered
285+
say(
286+
blocks=[
287+
{
288+
"type": "section",
289+
"text": {
290+
"type": "mrkdwn",
291+
"text": f"Hey there <@{message['user']}>!"
292+
},
293+
"accessory": {
294+
"type": "button",
295+
"text": {
296+
"type": "plain_text",
297+
"text": "Click Me"
298+
},
299+
"action_id": "button_click"
300+
}
301+
}
302+
],
303+
text=f"Hey there <@{message['user']}>!"
304+
)
305+
306+
@app.action("button_click")
307+
def action_button_click(body, ack, say):
308+
# Acknowledge the action
309+
ack()
310+
say(f"<@{body['user']['id']}> clicked the button")
311+
312+
# Start your app
313+
if __name__ == "__main__":
314+
app.start(port=int(os.environ.get("PORT", 3000)))
315+
```
316+
317+
You can see that we used `app.action()` to listen for the `action_id` that we named `button_click`. If you restart your app and click the button, you'll see a new message from your app that says you clicked the button.
318+
319+
---
320+
321+
### Next steps
322+
You just built your first [Bolt for Python app](https://github.com/slackapi/bolt-python/tree/main/samples/getting_started)! 🎉
323+
324+
Now that you have a basic app up and running, you can start exploring how to make your Bolt app stand out. Here are some ideas about what to explore next:
325+
326+
* Read through the [Basic concepts](/bolt-python/concepts#basic) to learn about the different methods and features your Bolt app has access to.
327+
328+
* Explore the different events your bot can listen to with the [`events()` method](/bolt-python/concepts#event-listening). All of the events are listed [on the API site](https://api.slack.com/events).
329+
330+
* Bolt allows you to [call Web API methods](/bolt-python/concepts#web-api) with the client attached to your app. There are [over 220 methods](https://api.slack.com/methods) on our API site.
331+
332+
* Learn more about the different token types [on our API site](https://api.slack.com/docs/token-types). Your app may need different tokens depending on the actions you want it to perform.

samples/getting_started/.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Python
2+
.venv/
3+
env*/

samples/getting_started/README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Getting Started with ⚡️ Bolt for Python
2+
> Slack app example from 📚 [Getting started with Bolt for Python][1]
3+
4+
## Overview
5+
6+
This is a Slack app built with the [Bolt for Python framework][2] that showcases
7+
responding to events and interactive buttons.
8+
9+
## Running locally
10+
11+
### 1. Setup environment variables
12+
13+
```zsh
14+
# Replace with your signing secret and token
15+
export SLACK_BOT_TOKEN=<your-bot-token>
16+
export SLACK_SIGNING_SECRET=<your-signing-secret>
17+
```
18+
19+
### 2. Setup your local project
20+
21+
```zsh
22+
# Clone this project onto your machine
23+
git clone https://github.com/slackapi/bolt-python.git
24+
25+
# Change into this project
26+
cd bolt-python/samples/getting_started/
27+
28+
# Setup virtual environment
29+
python3 -m venv .venv
30+
source .venv/bin/activate
31+
32+
# Install the dependencies
33+
pip install -r requirements.txt
34+
```
35+
36+
### 3. Start servers
37+
38+
[Setup ngrok][3] to create a local requests URL for development.
39+
40+
```zsh
41+
npm run ngrok
42+
npm run start
43+
```
44+
45+
[1]: https://slack.dev/bolt-python/tutorial/getting-started
46+
[2]: https://slack.dev/bolt-python/
47+
[3]: https://slack.dev/bolt-python/tutorial/getting-started#setting-up-events

0 commit comments

Comments
 (0)
X Tutup