diff --git a/docs/content/concepts/commands.md b/docs/content/concepts/commands.md index 010ef32d2..7ece460ca 100644 --- a/docs/content/concepts/commands.md +++ b/docs/content/concepts/commands.md @@ -1,5 +1,5 @@ --- -title: Listening and responding to commands +title: Listening & responding to commands lang: en slug: /concepts/commands --- diff --git a/docs/content/concepts/custom-steps.md b/docs/content/concepts/custom-steps.md index f91fac33c..10d03e4c4 100644 --- a/docs/content/concepts/custom-steps.md +++ b/docs/content/concepts/custom-steps.md @@ -1,6 +1,6 @@ --- title: Listening and responding to custom steps -sidebar_label: Custom steps +sidebar_label: Custom Steps lang: en slug: /concepts/custom-steps --- diff --git a/docs/content/concepts/shortcuts.md b/docs/content/concepts/shortcuts.md index d9f02c2a1..58889b1f8 100644 --- a/docs/content/concepts/shortcuts.md +++ b/docs/content/concepts/shortcuts.md @@ -1,5 +1,5 @@ --- -title: Listening and responding to shortcuts +title: Listening & responding to shortcuts lang: en slug: /concepts/shortcuts --- diff --git a/docs/content/concepts/steps-from-apps.md b/docs/content/concepts/steps-from-apps.md index 84315143b..f1e1e7c70 100644 --- a/docs/content/concepts/steps-from-apps.md +++ b/docs/content/concepts/steps-from-apps.md @@ -6,9 +6,9 @@ slug: /legacy/steps-from-apps :::danger -Steps from apps are a deprecated feature. +Steps from Apps is a deprecated feature. -Steps from apps are different than, and not interchangeable with, Slack automation workflows. We encourage those who are currently publishing steps from apps to consider the new [Slack automation features](https://api.slack.com/automation), such as [custom steps for Bolt](https://api.slack.com/automation/functions/custom-bolt), +Steps from Apps are different than, and not interchangeable with, Slack automation workflows. We encourage those who are currently publishing steps from apps to consider the new [Slack automation features](https://api.slack.com/automation), such as [custom steps for Bolt](https://api.slack.com/automation/functions/custom-bolt). Please [read the Slack API changelog entry](https://api.slack.com/changelog/2023-08-workflow-steps-from-apps-step-back) for more information. @@ -171,7 +171,7 @@ ws = WorkflowStep( app.step(ws) ``` -## Executing steps from app +## Executing steps from apps When your step from app is executed by an end user, your app will receive a [`workflow_step_execute` event](https://api.slack.com/events/workflow_step_execute). The `execute` callback in your `WorkflowStep` configuration will be run when this event is received. diff --git a/docs/content/concepts/updating-pushing-views.md b/docs/content/concepts/updating-pushing-views.md index d7a9e3a3e..051c0c6ae 100644 --- a/docs/content/concepts/updating-pushing-views.md +++ b/docs/content/concepts/updating-pushing-views.md @@ -1,5 +1,5 @@ --- -title: Updating and pushing views +title: Updating & pushing views lang: en slug: /concepts/updating-pushing-views --- diff --git a/docs/content/concepts/view-submissions.md b/docs/content/concepts/view-submissions.md index a22911e71..729f9d87b 100644 --- a/docs/content/concepts/view-submissions.md +++ b/docs/content/concepts/view-submissions.md @@ -1,5 +1,5 @@ --- -title: Listening for view submissions +title: Listening to views lang: en slug: /concepts/view_submissions --- diff --git a/docs/content/getting-started.md b/docs/content/getting-started.md index 79ccfff61..5449a4ac2 100644 --- a/docs/content/getting-started.md +++ b/docs/content/getting-started.md @@ -1,5 +1,5 @@ --- -title: Getting started +title: Getting Started slug: getting-started lang: en --- @@ -8,14 +8,7 @@ lang: en 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. - -When you're finished, you'll have this ⚡️[Getting Started with Slack app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started) to run, modify, and make your own. The possibilities are endless! - -:::info - -For this guide, we are going to be using [Socket Mode](https://api.slack.com/apis/connections/socket), our recommended option for those just getting started and building something for their team. If you already know you're going to want to use HTTP as your app's communication protocol, head over to our parallel guide, [Getting Started over HTTP](/tutorial/getting-started-http). - -::: +When you're finished, you'll have this ⚡️[Getting Started with Slack app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started) to run, modify, and make your own. --- @@ -30,7 +23,7 @@ We recommend using a workspace where you won't disrupt real work getting done 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. -This page contains an overview of your app in addition to important credentials you'll want to reference later. +This page contains an overview of your app in addition to important credentials you'll need later. ![Basic Information page](/img/boltpy/basic-information-page.png "Basic Information page") @@ -62,7 +55,6 @@ We're going to use bot and app-level tokens for this guide. 6. Navigate to **Socket Mode** on the left side menu and toggle to enable. - :::tip Treat your tokens like passwords and [keep them safe](https://api.slack.com/docs/oauth-safety). Your app uses tokens to post and retrieve information from Slack workspaces. @@ -72,6 +64,7 @@ Treat your tokens like passwords and [keep them safe](https://api.slack.com/docs --- ### Setting up your project {#setting-up-your-project} + 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. If you don’t already have a project, let’s create a new one. Create an empty directory: @@ -109,7 +102,7 @@ export SLACK_APP_TOKEN= :::warning -Keep all tokens secure. At a minimum, you should avoid checking them into public version control, and access them via environment variables as we've done above. Checkout the API documentation for more on [best practices for app security](https://api.slack.com/authentication/best-practices). +Remember to keep your tokens secure. At a minimum, you should avoid checking them into public version control, and access them via environment variables as we've done above. Check out the API documentation for more on [best practices for app security](https://api.slack.com/authentication/best-practices). ::: @@ -149,16 +142,42 @@ Your app behaves similarly to people on your team — it can post messages, add 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). -:::info +For those just starting, we recommend using [Socket Mode](https://api.slack.com/apis/socket-mode). Socket Mode allows your app to use the Events API and interactive features without exposing a public HTTP Request URL. This can be helpful during development, or if you're receiving requests from behind a firewall. -Earlier in this tutorial we enabled Socket Mode. Socket Mode lets apps use the Events API and interactive components without exposing a public HTTP endpoint. This can be helpful during development, or if you're receiving requests from behind a firewall. HTTP is more useful for apps being deployed to hosting environments, or apps intended for distribution via the Slack App Directory. To follow this getting started guide with HTTP instead, head over [here](/tutorial/getting-started-http). +That being said, you're welcome to set up an app with a public HTTP Request URL. HTTP is more useful for apps being deployed to hosting environments to respond within a large corporate Slack workspaces/organization, or apps intended for distribution via the Slack Marketplace. -::: +We've provided instructions for both ways in this guide. -It's time to tell Slack what events we'd like to listen for. +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + + + +1. Head to your app's configuration page (click on the app [from your app settings page](https://api.slack.com/apps)). Navigate to **Socket Mode** on the left side menu and toggle to enable. + +2. Go to **Basic Information** and scroll down under the App-Level Tokens section and click **Generate Token and Scopes** to generate an app token. Add the `connections:write` scope to this token and save the generated `xapp` token, we'll use that in just a moment. + +3. Finally, it's time to tell Slack what events we'd like to listen for. Under **Event Subscriptions**, toggle the switch labeled **Enable Events**. 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. + + + +1. Go 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**. + +2. Add your Request URL. Slack will send HTTP POST requests corresponding to events to this [Request URL](https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls) endpoint. Bolt uses the `/slack/events` path to listen to all incoming requests (whether shortcuts, events, or interactivity payloads). When configuring your Request URL within your app configuration, you'll append `/slack/events`, e.g. `https:///slack/events`. 💡 As long as your Bolt app is still running, your URL should become verified. + +:::tip + +For local development, you can use a proxy service like ngrok to create a public URL and tunnel requests to your development environment. Refer to [ngrok's getting started guide](https://ngrok.com/docs#getting-started-expose) on how to create this tunnel. And when you get to hosting your app, 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). + +::: + + + + Navigate to **Event Subscriptions** on the left sidebar and toggle to enable. Under **Subscribe to Bot Events**, you can add events for your bot to respond to. There are four events related to messages: - [`message.channels`](https://api.slack.com/events/message.channels) listens for messages in public channels that your app is added to - [`message.groups`](https://api.slack.com/events/message.groups) listens for messages in 🔒 private channels that your app is added to @@ -174,6 +193,9 @@ Your app is now ready for some logic. Let's start by using the `message()` metho The following example listens and responds to all messages in channels/DMs where your app has been added that contain the word "hello": + + + ```python import os from slack_bolt import App @@ -195,6 +217,35 @@ if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() ``` + + + +```python +import os +from slack_bolt import App + +# Initializes your app with your bot token and signing secret +app = App( + token=os.environ.get("SLACK_BOT_TOKEN"), + signing_secret=os.environ.get("SLACK_SIGNING_SECRET") +) + +# Listens to incoming messages that contain "hello" +# To learn available listener arguments, +# visit https://tools.slack.dev/bolt-python/api-docs/slack_bolt/kwargs_injection/args.html +@app.message("hello") +def message_hello(message, say): + # say() sends a message to the channel where the event was triggered + say(f"Hey there <@{message['user']}>!") + +# Start your app +if __name__ == "__main__": + app.start(port=int(os.environ.get("PORT", 3000))) +``` + + + + 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. 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. @@ -205,12 +256,25 @@ This is a basic example, but it gives you a place to start customizing your app To use features like buttons, select menus, datepickers, modals, and shortcuts, you’ll need to enable interactivity. Head over to **Interactivity & Shortcuts** in your app configuration. -:::tip + + + +With Socket Mode on, basic interactivity is enabled by default, so no further action is needed. + + + + +Similar to events, you'll need to specify a URL for Slack to send the action (such as *user clicked a button*). Back on your app configuration page, click on **Interactivity & Shortcuts** on the left side. You'll see that there's another **Request URL** box. -You’ll notice that with Socket Mode on, basic interactivity is enabled for us by default, so no further action here is needed. If you’re using HTTP, you’ll need to supply a Request URL for Slack to send events to. +:::tip + +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 (for example, `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! ::: + + + When interactivity is enabled, interactions with shortcuts, modals, or interactive components (such as buttons, select menus, and datepickers) will be sent to your app as events. Now, let's go back to your app's code and add logic to handle those events: @@ -219,6 +283,9 @@ Now, let's go back to your app's code and add logic to handle those events: Below, the code from the last section is modified to send a message containing a button rather than just a string: + + + ```python import os from slack_bolt import App @@ -255,6 +322,46 @@ if __name__ == "__main__": ``` + + + +```python +import os +from slack_bolt import App + +# Initializes your app with your bot token and signing secret +app = App( + token=os.environ.get("SLACK_BOT_TOKEN"), + signing_secret=os.environ.get("SLACK_SIGNING_SECRET") +) + +# Listens to incoming messages that contain "hello" +@app.message("hello") +def message_hello(message, say): + # say() sends a message to the channel where the event was triggered + say( + blocks=[ + { + "type": "section", + "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Click Me"}, + "action_id": "button_click" + } + } + ], + text=f"Hey there <@{message['user']}>!" + ) + +# Start your app +if __name__ == "__main__": + app.start(port=int(os.environ.get("PORT", 3000))) +``` + + + + 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. 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. @@ -269,6 +376,9 @@ Now, if you restart your app and say "hello" in a channel your app is in, you'll Let's add a handler to send a followup message when someone clicks the button: + + + ```python import os from slack_bolt import App @@ -307,12 +417,58 @@ if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() ``` + + + +```python +import os +from slack_bolt import App + +# Initializes your app with your bot token and signing secret +app = App( + token=os.environ.get("SLACK_BOT_TOKEN"), + signing_secret=os.environ.get("SLACK_SIGNING_SECRET") +) + +# Listens to incoming messages that contain "hello" +@app.message("hello") +def message_hello(message, say): + # say() sends a message to the channel where the event was triggered + say( + blocks=[ + { + "type": "section", + "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Click Me"}, + "action_id": "button_click" + } + } + ], + text=f"Hey there <@{message['user']}>!" + ) + +@app.action("button_click") +def action_button_click(body, ack, say): + # Acknowledge the action + ack() + say(f"<@{body['user']['id']}> clicked the button") + +# Start your app +if __name__ == "__main__": + app.start(port=int(os.environ.get("PORT", 3000))) +``` + + + + 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. --- ### Next steps {#next-steps} -You just built your first [Bolt for Python app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started) with Socket Mode! 🎉 +You just built your first [Bolt for Python app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)! 🎉 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: @@ -322,4 +478,4 @@ Now that you have a basic app up and running, you can start exploring how to mak * Bolt allows you to [call Web API methods](/concepts/web-api) with the client attached to your app. There are [over 220 methods](https://api.slack.com/methods) on our API site. -* 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. For apps that do not use Socket Mode, typically only the bot (`xoxb`) token and Signing Secret are required. For example of this, see our parallel guide [Getting Started with HTTP](/tutorial/getting-started-http). \ No newline at end of file +* 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. diff --git a/docs/content/tutorial/getting-started-http.md b/docs/content/tutorial/getting-started-http.md deleted file mode 100644 index 6cd4a8ae6..000000000 --- a/docs/content/tutorial/getting-started-http.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -title: Getting started over HTTP -slug: getting-started-http -lang: en ---- - -# Getting started with Bolt for Python over HTTP - -This guide is meant to walk you through getting up and running with a Slack app using **Bolt for Python over HTTP**. 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. - - -When you're finished, you'll have this ⚡️[Getting Started with Slack app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started) to run, modify, and make your own. - ---- - -### Create an app {#create-an-app} -First thing's first: before you start developing with Bolt, you'll want to [create a Slack app](https://api.slack.com/apps/new). - -:::tip - -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). - -::: - -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. - -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. - -![Basic Information page](/img/boltpy/basic-information-page.png "Basic Information page") - -Look around, add an app icon and description, and then let's start configuring your app 🔩 - ---- - -### Tokens and installing apps {#tokens-and-installing-apps} -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. - -There are three main token types available to a Slack app: user (`xoxp`), bot (`xoxb`), and app-level (`xapp`) tokens. -- [User tokens](https://api.slack.com/authentication/token-types#user) 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](https://api.slack.com/authentication/token-types#bot) 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. -- [App-level tokens](https://api.slack.com/authentication/token-types#app) represent your app across organizations, including installations by all individual users on all workspaces in a given organization and are commonly used for creating websocket connections to your app. - -For brevity, we're going to use bot tokens for this guide. - -1. Navigate to the **OAuth & Permissions** on the left sidebar and scroll down to the **Bot Token Scopes** section. Click **Add an OAuth Scope**. - -2. 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. - -3. 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. - -4. Once you authorize the installation, you'll land on the **OAuth & Permissions** page and see a **Bot User OAuth Access Token**. We'll use that in just a moment. - -![OAuth Tokens](/img/boltpy/bot-token.png "Bot OAuth Token") - -:::info - -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. - -::: - ---- - -### Setting up your project {#setting-up-your-project} -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. - -If you don’t already have a project, let’s create a new one. Create an empty directory: - -```shell -mkdir first-bolt-app -cd first-bolt-app -``` - -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/): - -```shell -python3 -m venv .venv -source .venv/bin/activate -``` - -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)): - -```shell -which python3 -# Output: /path/to/first-bolt-app/.venv/bin/python3 -``` - -Before we install the Bolt for Python package to your new project, let's save the **bot token** and **signing secret** that were generated when you configured your app. - -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). -```shell -export SLACK_SIGNING_SECRET= -``` - -2. **Copy your bot (xoxb) token from the OAuth & Permissions page** and store it in another environment variable. -```shell -export SLACK_BOT_TOKEN=xoxb- -``` -> 🔒 Remember to keep your tokens and signing secret secure. At a minimum, you should avoid checking them into public version control, and access them via environment variables as we've done above. Checkout the API documentation for more on [best practices for app security](https://api.slack.com/authentication/best-practices). - -Now, let's create your app. Install the `slack_bolt` Python package to your virtual environment using the following command: - -```shell -pip install slack_bolt -``` - -Create a new file called `app.py` in this directory and add the following code: - -```python -import os -from slack_bolt import App - -# Initializes your app with your bot token and signing secret -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# Start your app -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -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: - -```script -python3 app.py -``` - -Your app should let you know that it's up and running. 🎉 - ---- - -### Setting up events over HTTP {#setting-up-events} -Your app behaves similarly to people on your team — it can post messages, add emoji reactions, and listen and respond to events. - -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). - -Let's enable events for your app: -1. Go 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**. - -2. Add your Request URL. Slack will send HTTP POST requests corresponding to events to this [Request URL](https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls) endpoint. Bolt uses the `/slack/events` path to listen to all incoming requests (whether shortcuts, events, or interactivity payloads). When configuring your Request URL within your app configuration, you'll append `/slack/events`, e.g. `https:///slack/events`. 💡 As long as your Bolt app is still running, your URL should become verified. - -:::tip - -For local development, you can use a proxy service like ngrok to create a public URL and tunnel requests to your development environment. Refer to [ngrok's getting started guide](https://ngrok.com/docs#getting-started-expose) on how to create this tunnel. And when you get to hosting your app, 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). - -::: - -Finally, it's time to tell Slack what events we'd like to listen for. - -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. - -Navigate to **Event Subscriptions** on the left sidebar and toggle to enable. Under **Subscribe to Bot Events**, you can add events for your bot to respond to. There are four events related to messages: -- [`message.channels`](https://api.slack.com/events/message.channels) listens for messages in public channels that your app is added to -- [`message.groups`](https://api.slack.com/events/message.groups) listens for messages in 🔒 private channels that your app is added to -- [`message.im`](https://api.slack.com/events/message.im) listens for messages in your app's DMs with users -- [`message.mpim`](https://api.slack.com/events/message.mpim) listens for messages in multi-person DMs that your app is added to - -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. - ---- - -### Listening and responding to a message {#listening-and-responding-to-a-message} -Your app is now ready for some logic. Let's start by using the `message()` method to attach a listener for messages. - -The following example listens and responds to all messages in channels/DMs where your app has been added that contain the word "hello": - -```python -import os -from slack_bolt import App - -# Initializes your app with your bot token and signing secret -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# Listens to incoming messages that contain "hello" -# To learn available listener arguments, -# visit https://tools.slack.dev/bolt-python/api-docs/slack_bolt/kwargs_injection/args.html -@app.message("hello") -def message_hello(message, say): - # say() sends a message to the channel where the event was triggered - say(f"Hey there <@{message['user']}>!") - -# Start your app -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -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. - -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. - ---- - -### Sending and responding to actions {#sending-and-responding-to-actions} - -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*). - -Back on your app configuration page, click on **Interactivity & Shortcuts** on the left side. You'll see that there's another **Request URL** box. - -:::tip - -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 (for example, `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! - -::: - -![Configuring a Request URL](/img/boltpy/request-url-config.png "Configuring a Request URL") - -When interactivity is enabled, interactions with shortcuts, modals, or interactive components (such as buttons, select menus, and datepickers) will be sent to your app as events. - -Now, let's go back to your app's code and add logic to handle those events: -- First, we'll send a message that contains an interactive component (in this case a button) -- Next, we'll listen for the action of a user clicking the button before responding - -Below, the code from the last section is modified to send a message containing a button rather than just a string: - -```python -import os -from slack_bolt import App - -# Initializes your app with your bot token and signing secret -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# Listens to incoming messages that contain "hello" -@app.message("hello") -def message_hello(message, say): - # say() sends a message to the channel where the event was triggered - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text": "Click Me"}, - "action_id": "button_click" - } - } - ], - text=f"Hey there <@{message['user']}>!" - ) - -# Start your app -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -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. - -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. - -:::tip - -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. - -::: - -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!*). - -Let's add a handler to send a followup message when someone clicks the button: - -```python -import os -from slack_bolt import App - -# Initializes your app with your bot token and signing secret -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# Listens to incoming messages that contain "hello" -@app.message("hello") -def message_hello(message, say): - # say() sends a message to the channel where the event was triggered - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text": "Click Me"}, - "action_id": "button_click" - } - } - ], - text=f"Hey there <@{message['user']}>!" - ) - -@app.action("button_click") -def action_button_click(body, ack, say): - # Acknowledge the action - ack() - say(f"<@{body['user']['id']}> clicked the button") - -# Start your app -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -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. - ---- - -### Next steps {#next-steps} -You just built your first [Bolt for Python app](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)! 🎉 - -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: - -* Read through the _Basic concepts_ to learn about the different methods and features your Bolt app has access to. - -* Explore the different events your bot can listen to with the [`app.event()` method](/concepts/event-listening). All of the events are listed [on the API site](https://api.slack.com/events). - -* Bolt allows you to [call Web API methods](/concepts/web-api) with the client attached to your app. There are [over 220 methods](https://api.slack.com/methods) on our API site. - -* 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. If you are using Socket Mode instead of HTTP, an additional (`xapp`) token with `connections:write` scopes is required. \ No newline at end of file diff --git a/docs/i18n/ja-jp/code.json b/docs/i18n/ja-jp/code.json index eb1a022fa..2b3c80254 100644 --- a/docs/i18n/ja-jp/code.json +++ b/docs/i18n/ja-jp/code.json @@ -285,5 +285,37 @@ "theme.unlistedContent.message": { "message": "このページは非公開です。 検索対象外となり、このページのリンクに直接アクセスできるユーザーのみに公開されます。", "description": "The unlisted content banner message" + }, + "theme.blog.author.pageTitle": { + "message": "{authorName} - {nPosts}", + "description": "The title of the page for a blog author" + }, + "theme.blog.authorsList.pageTitle": { + "message": "著者一覧", + "description": "The title of the authors page" + }, + "theme.blog.authorsList.viewAll": { + "message": "すべての著者を見る", + "description": "The label of the link targeting the blog authors page" + }, + "theme.blog.author.noPosts": { + "message": "この著者による投稿はまだありません。", + "description": "The text for authors with 0 blog post" + }, + "theme.contentVisibility.unlistedBanner.title": { + "message": "非公開のページ", + "description": "The unlisted content banner title" + }, + "theme.contentVisibility.unlistedBanner.message": { + "message": "このページは非公開です。 検索対象外となり、このページのリンクに直接アクセスできるユーザーのみに公開されます。", + "description": "The unlisted content banner message" + }, + "theme.contentVisibility.draftBanner.title": { + "message": "下書きのページ", + "description": "The draft content banner title" + }, + "theme.contentVisibility.draftBanner.message": { + "message": "このページは下書きです。開発環境でのみ表示され、本番環境のビルドには含まれません。", + "description": "The draft content banner message" } } diff --git a/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current.json b/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current.json index ecd4e1e22..eb3b5be26 100644 --- a/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current.json +++ b/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current.json @@ -26,5 +26,53 @@ "sidebar.sidebarBoltPy.link.Contributors Guide": { "message": "貢献", "description": "The label for link Contributors Guide in sidebar sidebarBoltPy, linking to https://github.com/SlackAPI/bolt-python/blob/main/.github/contributing.md" + }, + "sidebar.sidebarBoltPy.category.Guides": { + "message": "ガイド", + "description": "The label for category Guides in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.Slack API calls": { + "message": "Slack API コール", + "description": "The label for category Slack API calls in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.Events": { + "message": "イベント API", + "description": "The label for category Events in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.App UI & Interactivity": { + "message": "インタラクティビティ & ショートカット", + "description": "The label for category App UI & Interactivity in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.App Configuration": { + "message": "App の設定", + "description": "The label for category App Configuration in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.Middleware & Context": { + "message": "ミドルウェア & コンテキスト", + "description": "The label for category Middleware & Context in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.Adaptors": { + "message": "アダプター", + "description": "The label for category Adaptors in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.Authorization & Security": { + "message": "認可 & セキュリティ", + "description": "The label for category Authorization & Security in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.category.Legacy": { + "message": "レガシー(非推奨)", + "description": "The label for category Legacy in sidebar sidebarBoltPy" + }, + "sidebar.sidebarBoltPy.link.Reference": { + "message": "リファレンス", + "description": "The label for link Reference in sidebar sidebarBoltPy, linking to https://tools.slack.dev/bolt-python/api-docs/slack_bolt/" + }, + "sidebar.sidebarBoltPy.link.Release notes": { + "message": "リリースノート", + "description": "The label for link Release notes in sidebar sidebarBoltPy, linking to https://github.com/slackapi/bolt-python/releases" + }, + "sidebar.sidebarBoltPy.doc.Bolt for Python": { + "message": "Bolt for Python", + "description": "The label for the doc item Bolt for Python in sidebar sidebarBoltPy, linking to the doc index" } } diff --git a/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/getting-started.md b/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/getting-started.md index 41aecf6ef..7e50fbcf2 100644 --- a/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/getting-started.md +++ b/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/getting-started.md @@ -11,12 +11,6 @@ lang: ja-jp この手順を全て終わらせたら、あなたはきっと ⚡️[Slack アプリのはじめ方](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)のサンプルアプリを動作させたり、それに変更を加えたり、自分のアプリを作ったりすることができるようになるでしょう。 -:::tip - -このガイドでは[ソケットモード](https://api.slack.com/apis/connections/socket) を利用します。ソケットモードは、Slack アプリ開発をとりあえず始めてみるときやあなたのチームだけのためのアプリをつくるときにおすすめのやり方です。もしすでに HTTP をアプリのコミュニケーションプロトコルとするとわかっている場合は、HTTP の方式に対応した同様のドキュメントである [Bolt 入門ガイド(HTTP)](/tutorial/getting-started-http) を参照してください。 - -::: - --- ### アプリを作成する {#create-an-app} @@ -26,7 +20,7 @@ lang: ja-jp 通常の業務の妨げにならないよう、別の開発用のワークスペースを使用することをおすすめします。[新しいワークスペースは無料で作成できます](https://slack.com/get-started#create) -:::。 +::: アプリ名を入力し(_後で変更可能_)、インストール先のワークスペースを選択して「`Create App`」ボタンをクリックすると、アプリの **Basic Information** ページが表示されます。 @@ -105,9 +99,11 @@ export SLACK_BOT_TOKEN=xoxb-<ボットトークン> ```shell export SLACK_APP_TOKEN=<アプリレベルトークン> ``` +:::warning -> 🔒 全てのトークンは安全に保管してください。少なくともパブリックなバージョン管理にチェックインするようなことは避けるべきでしょう。また、上にあった例のように環境変数を介してアクセスするようにしてください。詳細な情報は [アプリのセキュリティのベストプラクティス](https://api.slack.com/authentication/best-practices)のドキュメントを参照してください。 +🔒 全てのトークンは安全に保管してください。少なくともパブリックなバージョン管理にチェックインするようなことは避けるべきでしょう。また、上にあった例のように環境変数を介してアクセスするようにしてください。詳細な情報は [アプリのセキュリティのベストプラクティス](https://api.slack.com/authentication/best-practices)のドキュメントを参照してください。 +::: 完了したら、いよいよアプリを作っていきましょう。以下のコマンドを使って、仮想環境に Python の `slack_bolt` パッケージをインストールします。 @@ -145,16 +141,40 @@ python3 app.py Slack ワークスペースで発生するイベント(メッセージが投稿されたときや、メッセージに対するリアクションがつけられたときなど)をリッスンするには、[Events API を使って特定の種類のイベントをサブスクライブします](https://api.slack.com/events-api)。 -:::tip +このチュートリアルの序盤でソケットモードを有効にしました。ソケットモードを使うことで、アプリが公開された HTTP エンドポイントを公開せずに Events API やインタラクティブコンポーネントを利用できるようになります。このことは、開発時やファイヤーウォールの裏からのリクエストを受ける際に便利です。HTTP での方式は、ホスティング環境にデプロイするアプリや Slack App Directory で配布されるアプリの開発・運用に適しています。 -このチュートリアルの序盤でソケットモードを有効にしました。ソケットモードを使うことで、アプリが公開された HTTP エンドポイントを公開せずに Events API やインタラクティブコンポーネントを利用できるようになります。このことは、開発時やファイヤーウォールの裏からのリクエストを受ける際に便利です。HTTP での方式は、ホスティング環境にデプロイするアプリや Slack App Directory で配布されるアプリの開発・運用に適しています。HTTP での情報については[こちらのドキュメント](/tutorial/getting-started-http)を参照してください。 +それでは、このアプリがどのイベントをリッスンしたいかを Slack に伝えましょう。 -::: +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; -それでは、このアプリがどのイベントをリッスンしたいかを Slack に伝えましょう。 + + + +1. アプリの構成ページに移動します ([アプリ設定ページから](https://api.slack.com/apps) アプリをクリックします)。左側のメニューで **ソケット モード** に移動し、有効に切り替えます。 + +2. [**基本情報**] に移動し、[アプリレベル トークン] セクションの下にスクロールして、[**トークンとスコープの生成**] をクリックしてアプリ トークンを生成します。このトークンに `connections:write` スコープを追加し、生成された `xapp` トークンを保存します。これはすぐに使用します。 + +3. 最後に、聞きたいイベントを Slack に伝えます。 **イベント サブスクリプション** で、**イベントを有効にする** というラベルのスイッチを切り替えます。 イベントが発生すると、そのイベントをトリガーしたユーザーやイベントが発生したチャンネルなど、イベントに関する情報が Slack からアプリに送信されます。アプリではこれらの情報を処理して、適切な応答を返します。 + + + +1. アプリ構成ページに戻ります ([アプリ管理ページから](https://api.slack.com/apps) アプリをクリックします)。左側のサイドバーで [**イベント サブスクリプション**] をクリックします。 **イベントを有効にする**というラベルの付いたスイッチを切り替えます。 + +2. リクエスト URL を追加します。 Slack は、イベントに対応する HTTP POST リクエストをこの [リクエスト URL](https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-) に送信します。 Bolt は、`/slack/events` パスを使用して、すべての受信リクエスト (ショートカット、イベント、対話性ペイロードなど) をリッスンします。アプリ構成内でリクエスト URL を構成する場合は、`/slack/events` を追加します。 「https://あなたのドメイン/slack/events」。 💡 Bolt アプリが実行されている限り、URL は検証されるはずです。 + +:::tip + +ローカル開発の場合、ngrok などのプロキシ サービスを使用してパブリック URL を作成し、リクエストを開発環境にトンネリングできます。このトンネルの作成方法については、[ngrok のスタート ガイド](https://ngrok.com/docs#getting-started-expose) を参照してください。アプリをホスティングする際には、Slack 開発者がアプリをホストするために使用する最も一般的なホスティング プロバイダーを [API サイト](https://api.slack.com/docs/hosting) に集めました。 + +::: + + + + 左側のサイドバーから **Event Subscriptions** にアクセスして、機能を有効にしてください。 **Subscribe to Bot Events** 配下で、ボットが受け取れるイベントを追加することができます。4つのメッセージに関するイベントがあります。 - [`message.channels`](https://api.slack.com/events/message.channels) アプリが参加しているパブリックチャンネルのメッセージをリッスン - [`message.groups`](https://api.slack.com/events/message.groups) アプリが参加しているプライベートチャンネルのメッセージをリッスン @@ -170,6 +190,9 @@ Slack ワークスペースで発生するイベント(メッセージが投 次の例では、アプリが参加するチャンネルとダイレクトメッセージに投稿されるすべてのメッセージをリッスンし、「こんにちは」というメッセージに応答を返します。 + + + ```python import os from slack_bolt import App @@ -191,6 +214,35 @@ if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() ``` + + + +```python +import os +from slack_bolt import App + +# ボットトークンと署名シークレットを使ってアプリを初期化します +app = App( + token=os.environ.get("SLACK_BOT_TOKEN"), + signing_secret=os.environ.get("SLACK_SIGNING_SECRET") +) + +# 'hello' を含むメッセージをリッスンします +# 指定可能なリスナーのメソッド引数の一覧は以下のモジュールドキュメントを参考にしてください: +# https://tools.slack.dev/bolt-python/api-docs/slack_bolt/kwargs_injection/args.html +@app.message("hello") +def message_hello(message, say): + # イベントがトリガーされたチャンネルへ say() でメッセージを送信します + say(f"Hey there <@{message['user']}>!") + +# アプリを起動します +if __name__ == "__main__": + app.start(port=int(os.environ.get("PORT", 3000))) +``` + + + + アプリを再起動して、ボットユーザーが参加しているチャンネル・ダイレクトメッセージに「こんにちは」というメッセージを投稿すると、アプリが返答を返すでしょう。 これはごく基本的なコード例ですが、最終的にやりたいことを実現するためにアプリをカスタマイズしていく土台として利用できます。次は、シンプルなテキストの返答を送信する代わりにメッセージ内にボタンを表示するという、もう少しインタラクティブな動作を試してみましょう。 @@ -201,12 +253,25 @@ if __name__ == "__main__": インタラクティブ機能を有効にすると、ボタン、選択メニュー、日付ピッカー、モーダル、ショートカットなどの機能が利用できるようになります。アプリ設定ページの「**Interactivity & Shortcuts**」にアクセスしてください。 + + + +ソケット モードをオンにすると、基本的な対話機能がデフォルトで有効になるため、それ以上の操作は必要ありません。 + + + + +イベントと同様に、Slack がアクション (*ユーザーがボタンをクリックした* など) を送信するには、URL を指定する必要があります。アプリ構成ページに戻り、左側にある **対話性とショートカット** をクリックします。別の **リクエスト URL** ボックスがあることがわかります。 + :::tip ソケットモードを有効にしているとき、デフォルトで基本的なインタラクティブ機能が有効になっていることに気づくでしょう。追加のアクションは不要です。もし HTTP を使っている場合、Slack からのイベント送信先である Request URL を設定する必要があります。 ::: + + + インタラクティビティが有効化されていれば、ショートカット、モーダル、インタラクティブコンポーネント (例:ボタン、選択メニュー、日付ピッカー) とのインタラクションはイベントとしてあなたのアプリに送信されます。 それでは、アプリのコードに戻り、これらのイベントを処理する為のロジックを追加しましょう。 @@ -215,6 +280,9 @@ if __name__ == "__main__": 以下のコードの後の部分を編集し、文字列だけのメッセージの代わりに、ボタンを含んだメッセージを送信するようにしてみます。 + + + ```python import os from slack_bolt import App @@ -247,6 +315,46 @@ if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() ``` + + + +```python +import os +from slack_bolt import App + +# ボットトークンと署名シークレットを使ってアプリを初期化します +app = App( + token=os.environ.get("SLACK_BOT_TOKEN"), + signing_secret=os.environ.get("SLACK_SIGNING_SECRET") +) + +# 'hello' を含むメッセージをリッスンします +@app.message("hello") +def message_hello(message, say): + # イベントがトリガーされたチャンネルへ say() でメッセージを送信します + say( + blocks=[ + { + "type": "section", + "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text":"Click Me"}, + "action_id": "button_click" + } + } + ], + text=f"Hey there <@{message['user']}>!" + ) + +# アプリを起動します +if __name__ == "__main__": + app.start(port=int(os.environ.get("PORT", 3000))) +``` + + + + `say()` の中の値を `blocks` という配列のオブジェクトに変えました。ブロックは Slack メッセージを構成するコンポーネントであり、テキストや画像、日付ピッカーなど、さまざまなタイプのブロックがあります。この例では `accessory` に `button` を持たせた「section」のブロックを、アプリからの応答に含めています。`blocks` を使用する場合、`text` は通知やアクセシビリティのためのフォールバックとなります。 ボタンを含む `accessory` オブジェクトでは、`action_id` を指定していることがわかります。これは、ボタンを一意に示す識別子として機能します。これを使って、アプリをどのアクションに応答させるかを指定できます。 @@ -261,6 +369,9 @@ if __name__ == "__main__": ハンドラーを追加して、ボタンがクリックされたときにフォローアップメッセージを送信するようにしてみましょう。 + + + ```python import os from slack_bolt import App @@ -300,16 +411,63 @@ if __name__ == "__main__": SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start() ``` + + + +```python +import os +from slack_bolt import App + +# ボットトークンと署名シークレットを使ってアプリを初期化します +app = App( + token=os.environ.get("SLACK_BOT_TOKEN"), + signing_secret=os.environ.get("SLACK_SIGNING_SECRET") +) + +# 'hello' を含むメッセージをリッスンします +@app.message("hello") +def message_hello(message, say): + # イベントがトリガーされたチャンネルへ say() でメッセージを送信します + say( + blocks=[ + { + "type": "section", + "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text":"Click Me"}, + "action_id": "button_click" + } + } + ], + text=f"Hey there <@{message['user']}>!" + ) + +@app.action("button_click") +def action_button_click(body, ack, say): + # アクションを確認したことを即時で応答します + ack() + # チャンネルにメッセージを投稿します + say(f"<@{body['user']['id']}> clicked the button") + +# アプリを起動します +if __name__ == "__main__": + app.start(port=int(os.environ.get("PORT", 3000))) +``` + + + + `app.action()` を使って、先ほど命名した `button_click` という `action_id` をリッスンしています。アプリを再起動し、ボタンをクリックすると、アプリからの「クリックしました!」というメッセージが新たに表示されるでしょう。 --- ### 次のステップ {#next-steps} -はじめての [Bolt for Python アプリ](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)をソケットモードを使って構築することができました。🎉 +はじめての [Bolt for Python アプリ](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)を構築することができました。🎉 ここまでで基本的なアプリをセットアップして実行することはできたので、次は自分だけの Bolt アプリを作る方法について調べてみてください。参考になりそうなリソースをいくつかご紹介します。 * 基本的な概念について読んでみてください。Bolt アプリがアクセスできるさまざまメソッドや機能について知ることができます。 * [`app.event()` メソッド](/concepts/event-listening)でボットがリッスンできるイベントをほかにも試してみましょう。すべてのイベントの一覧は [API サイト](https://api.slack.com/events)で確認できます。 * Bolt では、アプリにアタッチされたクライアントから [Web API メソッドを呼び出す](/concepts/web-api)ことができます。API サイトに [220 以上のメソッド](https://api.slack.com/methods)を一覧しています。 -* [API サイト](https://api.slack.com/docs/token-types)でほかのタイプのトークンを確認してみてください。アプリで実行したいアクションによって、異なるトークンが必要になる場合があります。ソケットモードを使わないアプリでは、通常はボットトークン (`xoxb`) と署名シークレットが必要です。ソケットモードを使わない場合の例については、 HTTP 方式のやり方としてこのチュートリアルと対になっている [Bolt 入門ガイド(HTTP)](/tutorial/getting-started-http)を参照してください。 \ No newline at end of file +* [API サイト](https://api.slack.com/docs/token-types)でほかのタイプのトークンを確認してみてください。アプリで実行したいアクションによって、異なるトークンが必要になる場合があります。 diff --git a/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/tutorial/getting-started-http.md b/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/tutorial/getting-started-http.md deleted file mode 100644 index b6c461de2..000000000 --- a/docs/i18n/ja-jp/docusaurus-plugin-content-docs/current/tutorial/getting-started-http.md +++ /dev/null @@ -1,322 +0,0 @@ ---- -title: Bolt 入門ガイド(HTTP) -slug: getting-started-http -lang: ja-jp ---- - -# Bolt 入門ガイド(HTTP) - -このガイドでは、**HTTP上で Bolt for Python** を使った Slack アプリの設定と起動する方法について説明します。ここで説明する手順は、新しい Slack アプリを作成し、ローカルの開発環境をセットアップし、Slack ワークスペースからのメッセージをリッスンして応答するアプリを開発するという流れになります。 - -この手順を全て終わらせたら、あなたはきっと ⚡️[Slack アプリのはじめ方](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)のサンプルアプリを動作させたり、それに変更を加えたり、自分のアプリを作ったりすることができるようになるでしょう。 - ---- - -### アプリを作成する {#create-an-app} -最初にやるべきこと : Bolt での開発を始める前に、[Slack アプリを作成](https://api.slack.com/apps/new)します。 - -:::tip - -いつもの仕事のさまたげにならないように、別の開発用のワークスペースを使用することをおすすめします。[新しいワークスペースは無料で作成できます](https://slack.com/get-started#create)。 - -::: - -アプリ名を入力し(_後で変更可能_)、インストール先のワークスペースを選択したら、「`Create App`」ボタンをクリックすると、アプリの **Basic Information** ページが表示されます。 - -このページでは、アプリの概要を確認できます。また、「**App Credentials**」ヘッダーの下では「`Signing Secret`」などの重要な認証情報も確認できます。これらの認証情報は後で必要になります。 - -![Basic Information ページ](/img/boltpy/basic-information-page.png "Basic Information ページ") - -ひと通り確認し、アプリのアイコンと説明を追加したら、アプリの構成 🔩 を始めましょう。 - ---- - -### トークンとアプリのインストール {#tokens-and-installing-apps} -Slack アプリでは、[Slack API へのアクセスの管理に OAuth を使用します](https://api.slack.com/docs/oauth)。アプリがインストールされると、トークンが発行されます。アプリはそのトークンを使って API メソッドを呼び出すことができます。 - -Slack アプリで使用できるトークンには、ユーザートークン(`xoxp`)とボットトークン(`xoxb`)、アプリレベルトークン(`xapp`)の 3 種類があります。 -- [ユーザートークン](https://api.slack.com/authentication/token-types#user) を使用すると、ユーザーがアプリをインストールまたは認証した後、アプリがそのユーザーを代理して API メソッドを呼び出すことができます。1 つのワークスペースに複数のユーザートークンが存在する可能性があります。 -- [ボットトークン](https://api.slack.com/authentication/token-types#bot) はボットユーザーに関連づけられ、1 つのワークスペースでは最初に誰かがそのアプリをインストールした際に一度だけ発行されます。どのユーザーがインストールを実行しても、アプリが使用するボットトークンは同じになります。_ほとんど_のアプリで使用されるのは、ボットトークンです。 -- [アプリレベルトークン](https://api.slack.com/authentication/token-types#app) は、組織に渡ってあなたのアプリを表すものです。所属する組織内の全てのワークスペースに、全ての個人ユーザによってインストールされたアプリについても同様です。アプリレベルトークンは WebSocket 通信を行うアプリを作る際に通常使われます。 - -説明を簡潔にするために、このガイドではボットトークンを使用します。 - -1. 左サイドバーの「**OAuth & Permissions**」をクリックし、「**Bot Token Scopes**」セクションまで下にスクロールします。「**Add an OAuth Scope**」をクリックします。 - -2. ここでは [`chat:write`](https://api.slack.com/scopes/chat:write) というスコープのみを追加します。このスコープは、アプリが参加しているチャンネルにメッセージを投稿することを許可します。 - -3. OAuth & Permissions ページの一番上までスクロールし、「**Install App to Workspace**」をクリックします。Slack の OAuth 確認画面 が表示されます。この画面で開発用ワークスペースへのアプリのインストールを承認します。 - -4. インストールを承認すると **OAuth & Permissions** ページが表示され、**Bot User OAuth Access Token** を確認できるでしょう。このトークンはこのあと利用します。 - -![OAuth トークン](/img/boltpy/bot-token.png "ボット用 OAuth トークン") - -:::tip - -トークンはパスワードと同様に取り扱い、[安全な方法で保管してください](https://api.slack.com/docs/oauth-safety)。アプリはこのトークンを使って Slack ワークスペースで投稿をしたり、情報の取得をしたりします。 - -::: - ---- - -### プロジェクトをセットアップする {#setting-up-your-project} -初期設定が終わったら、新しい Bolt プロジェクトのセットアップを行いましょう。このプロジェクトが、あなたのアプリのロジックを処理するコードを配置する場所となります。 - -プロジェクトをまだ作成していない場合は、新しく作成しましょう。空のディレクトリを作成します。 - -```shell -mkdir first-bolt-app -cd first-bolt-app -``` - -次に、プロジェクトの依存関係を管理する方法として、[Python 仮想環境](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#creating-a-virtual-environment)を使ったおすすめの方法を紹介します。これはシステム Python に存在するパッケージとのコンフリクトを防ぐために推奨されている優れた方法です。[Python 3.6 以降](https://www.python.org/downloads/)の仮想環境を作成し、アクティブにしてみましょう。 - -```shell -python3 -m venv .venv -source .venv/bin/activate -``` - -`python3` へのパスがプロジェクトの中を指していることを確かめることで、仮想環境がアクティブになっていることを確認できます([Windows でもこれに似たコマンドが利用できます](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/#activating-a-virtual-environment))。 - -```shell -which python3 -# 出力結果 : /path/to/first-bolt-app/.venv/bin/python3 -``` - -Bolt for Python のパッケージを新しいプロジェクトにインストールする前に、アプリの設定時に作成された **ボットトークン** と **署名シークレット** を保存しましょう。 - -1. **Basic Information ページの署名シークレットをコピー**して、新しい環境変数に保存します。以下のコマンド例は Linux と macOS で利用できます。[Windows でもこれに似たコマンドが利用できます](https://superuser.com/questions/212150/how-to-set-env-variable-in-windows-cmd-line/212153#212153)。 -```shell -export SLACK_SIGNING_SECRET= -``` - -2. **OAuth & Permissions ページのボットトークン (xoxb) をコピー**して、新しい環境変数に保存します。以下のコマンド例は Linux と macOS で利用できます。[Windows でもこれに似たコマンドが利用できます](https://superuser.com/questions/212150/how-to-set-env-variable-in-windows-cmd-line/212153#212153)。 -```shell -export SLACK_BOT_TOKEN=xoxb- -``` - -> 🔒 全てのトークンは安全に保管してください。最低限、パブリックなバージョンコントロールにチェックインすることは避けてください。また、上記の例のように環境変数を介してアクセスするようにしてください。詳細な情報は [best practices for app security](https://api.slack.com/authentication/best-practices).のドキュメントを参照してください。 - - -完了したら、アプリを作ってみましょう。以下のコマンドを使って、仮想環境に Python の `slack_bolt` パッケージをインストールします。 - -```shell -pip install slack_bolt -``` - -このディレクトリに「`app.py`」という名前の新しいファイルを作成し、以下のコードを追加します。 - -```python -import os -from slack_bolt import App -from slack_bolt.adapter.socket_mode import SocketModeHandler - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -このようにトークンがあれば、最初の Bolt アプリが作成できます。「`app.py`」ファイルを保存して、コマンドラインで以下を実行します。 - -```script -python3 app.py -``` - -アプリが起動し、実行中であることが表示されます。🎉 - ---- - -### HTTP を利用したイベントを設定する {#setting-up-events} -アプリはワークスペース内の他のメンバーと同じように振る舞い、メッセージを投稿したり、絵文字リアクションを追加したり、イベントをリッスンして返答したりできます。 - -Slack ワークスペースで発生するイベント(メッセージが投稿されたときや、メッセージに対するリアクションがつけられたときなど)をリッスンするには、[Events API を使って特定の種類のイベントをサブスクライブします](https://api.slack.com/events-api)。 - -それでは、アプリのイベント設定を有効化してみましょう。 - -1. [アプリ管理ページ](https://api.slack.com/apps)でアプリをクリックします。次に、左サイドバーの「**Event Subscriptions**」をクリックします。「**Enable Events**」というラベルのスイッチをオンに切り替えます。 -2. リクエストURLを追加します。Slackはイベントに対応するHTTP POSTリクエストをこの [Request URL](https://api.slack.com/apis/connections/events-api#the-events-api__subscribing-to-event-types__events-api-request-urls) のエンドポイントに送信します。Bolt は `/slack/events` のエンドポイントで、全ての受信リクエストをリッスンします。これらのリクエストにはショートカット、イベント、インタラクションペイロードが含まれます。アプリの設定でエンドポイントを指定するときは、すべての Request URL の末尾に「/slack/events」を追加してください。例えば、 `https:///slack/events` のようになります。Bolt アプリが起動した状態のままなら、URL の検証が成功するはずです。 - -:::tip - -ローカル開発では、[ngrok](https://ngrok.com/)のようなプロキシサービスを使って公開 URL を作成し、リクエストを開発環境にトンネリングすることができます。このトンネリングの方法については、[ngrok のガイド](https://ngrok.com/docs#getting-started-expose)を参照してください。また、アプリのホスティングが必要になった場合には、[API サイトに](https://api.slack.com/docs/hosting) Slack開発者達がアプリのホスティングよく利用するホスティングプロバイダーを集めています。 - -::: - -それでは、Slackにどのイベントをリッスンするかを教えてあげましょう。 - -イベントが発生すると、そのイベントをトリガーしたユーザーやイベントが発生したチャンネルなど、イベントに関する情報が Slack からアプリに送信されます。アプリではこれらの情報を処理して、適切な応答を返します。 - -左側のサイドバーから **Event Subscriptions** にアクセスして、機能を有効にしてください。 **Subscribe to Bot Events** 配下で、ボットが受け取れる イベントを追加することができます。4つのメッセージに関するイベントがあります。 -- [`message.channels`](https://api.slack.com/events/message.channels) アプリが参加しているパブリックチャンネルのメッセージをリッスン -- [`message.groups`](https://api.slack.com/events/message.groups) アプリが参加しているプライベートチャンネルのメッセージをリッスン -- [`message.im`](https://api.slack.com/events/message.im) あなたのアプリとユーザーのダイレクトメッセージをリッスン -- [`message.mpim`](https://api.slack.com/events/message.mpim) あなたのアプリが追加されているグループ DM をリッスン - -ボットが参加するすべての場所のメッセージをリッスンさせるには、これら 4 つのメッセージイベントをすべて選択します。ボットにリッスンさせるメッセージイベントの種類を選択したら、「**Save Changes**」ボタンをクリックします。 - ---- - -### メッセージをリッスンして応答する {#listening-and-responding-to-a-message} -アプリにロジックを組み込む準備が整いました。まずは `message()` メソッドを使用して、メッセージのリスナーをアタッチしましょう。 - -次の例では、アプリが参加するチャンネルとダイレクトメッセージに投稿されるすべてのメッセージをリッスンし、「hello」というメッセージに応答を返します。 - -```python -import os -from slack_bolt import App - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# 'hello' を含むメッセージをリッスンします -# 指定可能なリスナーのメソッド引数の一覧は以下のモジュールドキュメントを参考にしてください: -# https://tools.slack.dev/bolt-python/api-docs/slack_bolt/kwargs_injection/args.html -@app.message("hello") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say(f"Hey there <@{message['user']}>!") - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -アプリを再起動し、ボットユーザーが参加しているチャンネルまたはダイレクトメッセージに「hello」というメッセージを投稿すれば、アプリが応答するでしょう。 - -これはごく基本的なコード例ですが、最終的にやりたいことを実現するためにアプリをカスタマイズするための起点として利用できます。プレーンテキストを送信する代わりにボタンを表示するという、もう少しインタラクティブな動作を試してみましょう。 - ---- - -### アクションを送信して応答する {#sending-and-responding-to-actions} - -インタラクティブ機能を有効にすると、ボタン、選択メニュー、日付ピッカー、モーダル、ショートカットなどの機能が利用できるようになります。イベントと同様に、Slack からのアクション(*ユーザーがボタンをクリックした*など)の送信先となる URL を設定する必要があります。 - -アプリ設定ページに戻り、左サイドメニューの「**Interactivity & Shortcuts**」をクリックします。別の **Request URL** ボックスを見つけます。 - -:::tip - -デフォルトでは、Bolt はイベントに使用しているのと同じエンドポイントをインタラクティブコンポーネントにも使用するように設定されているため、上記と同じリクエスト URL(この例では「`https://8e8ec2d7.ngrok.io/slack/events`」)を使用します。このままの状態で、右下隅にある「**Save Changes**」ボタンを押してください。これでインタラクティブ機能がアプリで利用できるようになりました。 - -::: - -![Request URL の設定](/img/boltpy/request-url-config.png "Request URL の設定") - -インタラクティブ機能が有効化されている時、ショートカット、モーダル、インタラクティブコンポーネント (ボタンや、選択メニュー、日付ピッカー) とのインタラクションはイベントとしてアプリに対して送信されます。 - -それでは、アプリのコードに戻り、これらのイベントを処理する為のロジックを追加しましょう。 -- まず、インタラクティブコンポーネントを含んだメッセージをアプリから送信します(このケースではボタン)。 -- 次に、ユーザーから返されるボタンクリックのアクションをリッスンし、それに応答します。 - -以下のコードの後の部分を編集し、文字列だけのメッセージの代わりに、ボタンを含んだメッセージを送信するようにしてみます。 - -```python -import os -from slack_bolt import App - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# 'hello' を含むメッセージをリッスンします -@app.message("hello") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text":"Click Me"}, - "action_id": "button_click" - } - } - ], - text=f"Hey there <@{message['user']}>!" - ) - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -`say()` の中の値を `blocks` という配列のオブジェクトに変えました。ブロックは Slack メッセージを構成するコンポーネントであり、テキストや画像、日付ピッカーなど、さまざまなタイプのブロックがあります。この例では `accessory` に `button` を持たせた「section」のブロックを、アプリからの応答に含めています。`blocks` を使用する場合、`text` は通知やアクセシビリティのためのフォールバックとなります。 - -ボタンを含む `accessory` オブジェクトでは、`action_id` を指定していることがわかります。これは、ボタンを一意に示す識別子として機能します。これを使って、アプリをどのアクションに応答させるかを指定できます。 - -:::tip - -[Block Kit Builder](https://app.slack.com/block-kit-builder) を使用すると、インタラクティブなメッセージのプロトタイプを簡単に作成できます。自分自身やチームメンバーがメッセージのモックアップを作成し、生成される JSON をアプリに直接貼りつけることができます。 - -::: - -アプリを再起動し、アプリが参加しているチャンネルで「hello」と入力すると、ボタン付きのメッセージが表示されるようになりました。ただし、ボタンをクリックしても、*まだ*何も起こりません。 - -ハンドラーを追加して、ボタンがクリックされたときにフォローアップメッセージを送信するようにしてみましょう。 - -```python -import os -from slack_bolt import App - -# ボットトークンと署名シークレットを使ってアプリを初期化します -app = App( - token=os.environ.get("SLACK_BOT_TOKEN"), - signing_secret=os.environ.get("SLACK_SIGNING_SECRET") -) - -# 'hello' を含むメッセージをリッスンします -@app.message("hello") -def message_hello(message, say): - # イベントがトリガーされたチャンネルへ say() でメッセージを送信します - say( - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": f"Hey there <@{message['user']}>!"}, - "accessory": { - "type": "button", - "text": {"type": "plain_text", "text":"Click Me"}, - "action_id": "button_click" - } - } - ], - text=f"Hey there <@{message['user']}>!" - ) - -@app.action("button_click") -def action_button_click(body, ack, say): - # アクションを確認したことを即時で応答します - ack() - # チャンネルにメッセージを投稿します - say(f"<@{body['user']['id']}> clicked the button") - -# アプリを起動します -if __name__ == "__main__": - app.start(port=int(os.environ.get("PORT", 3000))) -``` - -`app.action()` を使って、先ほど命名した `button_click` という `action_id` をリッスンしています。アプリを再起動し、ボタンをクリックすると、アプリからの「clicked the button」というメッセージが新たに表示されるでしょう。 - ---- - -### 次のステップ {#next-steps} -はじめての [Bolt for Python アプリ](https://github.com/slackapi/bolt-python/tree/main/examples/getting_started)を構築することができました。🎉 - -ここまでで基本的なアプリをセットアップして実行することはできたので、次は自分だけの Bolt アプリを作る方法を調べてみましょう。参考になりそうな記事をいくつかご紹介します。 - -* 基本的な概念について読む。Bolt アプリがアクセスできるさまざまメソッドや機能について知ることができます。 -* [`app.event()` メソッド](/concepts/event-listening)でボットがリッスンできるイベントをほかにも試してみる。すべてのイベントの一覧は [API サイト](https://api.slack.com/events)で確認できます。 -* Bolt では、アプリにアタッチされたクライアントから [Web API メソッドを呼び出す](/concepts/web-api)ことができます。API サイトに [220 以上のメソッド](https://api.slack.com/methods)を一覧しています。 -* [API サイト](https://api.slack.com/docs/token-types)でほかのタイプのトークンを確認する。アプリで実行したいアクションによって、異なるトークンが必要になる場合があります。HTTPの代わりにソケットモードを利用したい場合には、`connections:write` のスコープを追加した、追加のトークン (`xapp`) が必要です。 \ No newline at end of file diff --git a/docs/i18n/ja-jp/docusaurus-theme-classic/navbar.json b/docs/i18n/ja-jp/docusaurus-theme-classic/navbar.json index 014f5f0c4..3eee009ee 100644 --- a/docs/i18n/ja-jp/docusaurus-theme-classic/navbar.json +++ b/docs/i18n/ja-jp/docusaurus-theme-classic/navbar.json @@ -54,5 +54,9 @@ "item.label.Slack Community": { "message": "Slack Community", "description": "Navbar item with label Slack Community" + }, + "item.label.Slack CLI": { + "message": "Slack CLI", + "description": "Navbar item with label Slack CLI" } -} \ No newline at end of file +} diff --git a/docs/sidebars.js b/docs/sidebars.js index 7b1db75c2..7c36af2cd 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -2,15 +2,17 @@ const sidebars = { sidebarBoltPy: [ { - type: "category", - label: "Guides", + type: 'doc', + id: 'index', + label: 'Bolt for Python', + className: 'sidebar-title', + }, + { type: 'html', value: '
' }, + { + type: 'category', + label: 'Guides', + collapsed: false, items: [ - { - type: "doc", - id: "index", - label: "Bolt for Python", - className: "sidebar-title", - }, "getting-started", { type: "category", @@ -19,7 +21,7 @@ const sidebars = { }, { type: "category", - label: "Events API", + label: "Events", items: ["concepts/message-listening", "concepts/event-listening"], }, { @@ -84,7 +86,7 @@ const sidebars = { { type: "category", label: "Tutorials", - items: ["tutorial/ai-chatbot", "tutorial/getting-started-http"], + items: ["tutorial/ai-chatbot", "tutorial/custom-steps-for-jira"], }, { type: "html", value: "
" }, {