Skip to content

Commit

Permalink
Update the Django example (#348)
Browse files Browse the repository at this point in the history
  • Loading branch information
seratch authored May 24, 2021
1 parent 51daa12 commit 51edf84
Show file tree
Hide file tree
Showing 24 changed files with 441 additions and 241 deletions.
83 changes: 78 additions & 5 deletions examples/django/README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,85 @@
Follow the instructions [here](https://slack.dev/bolt-python/concepts#authenticating-oauth) for configuring OAuth flow supported Slack apps. This example works with the default env variables such as `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET`, `SLACK_SCOPES`, `SLACK_SIGNING_SECRET`, and so forth.
## Bolt for Python - Django integration example

This example demonstrates how you can use Bolt for Python in your Django application. The project consists of two apps.

### `simple_app` - Single-workspace App Example

If you want to run a simple app like the one you've tried in the [Getting Started Guide](https://slack.dev/bolt-python/tutorial/getting-started), this is the right one for you. By default, this Django project runs this application. If you want to switch to OAuth flow supported one, modify `myslackapp/urls.py`.

To run this app, all you need to do are:

* Create a new Slack app configuration at https://api.slack.com/apps?new_app=1
* Go to "OAuth & Permissions"
* Add `app_mentions:read`, `chat:write` in Scopes > Bot Token Scopes
* Go to "Install App"
* Click "Install to Workspace"
* Complete the installation flow
* Copy the "Bot User OAuth Token" value, which starts with `xoxb-`

You can start your Django application this way:

```bash
python -m venv .venv
source .venv/bin/activate
pip install -U pip
pip install -r requirements.txt

export SLACK_SIGNING_SECRET=(You can find this value at Settings > Basic Information > App Credentials > Signing Secret)
export SLACK_BOT_TOKEN=(You can find this value at Settings > Install App > Bot User OAuth Token)

python manage.py migrate
python manage.py runserver 0.0.0.0:3000
```

As you did at [Getting Started Guide](https://slack.dev/bolt-python/tutorial/getting-started), configure ngrok or something similar to serve a public endpoint. Lastly,

* Go back to the Slack app configuration page
* Go to "Event Subscriptions"
* Turn the feature on
* Set the "Request URL" to `https://{your public domain}/slack/events`
* Go to the Slack workspace you've installed this app
* Invite the app's bot user to a channel
* Mention the bot user in the channel
* You'll see a reply from your app's bot user!

### `oauth_app` - Multiple-workspace App Example (OAuth flow supported)

By default, this Django project runs this application. If you want to switch to OAuth flow supported one, modify `myslackapp/urls.py`.

This example uses SQLite. If you are looking for an example using MySQL, check the `mysql-docker-compose.yml` and the comment in `myslackapp/settings.py`.


To run this app, all you need to do are:

* Create a new Slack app configuration at https://api.slack.com/apps?new_app=1
* Go to "OAuth & Permissions"
* Add `app_mentions:read`, `chat:write` in Scopes > Bot Token Scopes
* Follow the instructions [here](https://slack.dev/bolt-python/concepts#authenticating-oauth) for configuring OAuth flow supported Slack apps

You can start your Django application this way:

```bash
python -m venv .venv
source .venv/bin/activate
pip install -U pip
pip install -r requirements.txt
export SLACK_CLIENT_ID=
export SLACK_CLIENT_SECRET=
export SLACK_SCOPES=commands,chat:write
export SLACK_SIGNING_SECRET=

export SLACK_SIGNING_SECRET=(You can find this value at Settings > Basic Information > App Credentials > Signing Secret)
export SLACK_CLIENT_ID=(You can find this value at Settings > Basic Information > App Credentials > Client ID)
export SLACK_CLIENT_SECRET=(You can find this value at Settings > Basic Information > App Credentials > Client Secret)
export SLACK_SCOPES=app_mentions:read,chat:write

python manage.py migrate
python manage.py runserver 0.0.0.0:3000
```

As you did at [Getting Started Guide](https://slack.dev/bolt-python/tutorial/getting-started), configure ngrok or something similar to serve a public endpoint. Lastly,

* Go back to the Slack app configuration page
* Go to "Event Subscriptions"
* Turn the feature on
* Set the "Request URL" to `https://{your public domain}/slack/events`
* Visit `https://{your public domain}/slack/install` and complete the installation flow
* Invite the app's bot user to a channel
* Mention the bot user in the channel
* You'll see a reply from your app's bot user!
3 changes: 2 additions & 1 deletion examples/django/manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@


def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "slackapp.settings")
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myslackapp.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
Expand Down
File renamed without changes.
16 changes: 16 additions & 0 deletions examples/django/myslackapp/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for myslackapp project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myslackapp.settings")

application = get_asgi_application()
Original file line number Diff line number Diff line change
@@ -1,64 +1,35 @@
"""
Django settings for slackapp project.
Django settings for myslackapp project.
Generated by 'django-admin startproject' using Django 3.0.8.
Generated by 'django-admin startproject' using Django 3.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

import os
from pathlib import Path

LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"root": {
"handlers": ["console"],
"level": "DEBUG",
},
"loggers": {
"django": {
"handlers": ["console"],
"level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
"propagate": False,
},
"django.db": {
"level": "DEBUG",
},
"slack_bolt": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
},
},
}
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# TODO: CHANGE THIS IF YOU REUSE THIS APP
SECRET_KEY = (
"This is just a example. You should not expose your secret key in real apps"
)
SECRET_KEY = "This is just a example. You should not expose your secret key in real apps"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True


# ALLOWED_HOSTS = []
ALLOWED_HOSTS = ["*"]


# Application definition

INSTALLED_APPS = [
Expand All @@ -68,7 +39,8 @@
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"slackapp.apps.SlackAppConfig",
"simple_app.apps.SimpleAppConfig",
"oauth_app.apps.OauthAppConfig",
]

MIDDLEWARE = [
Expand All @@ -81,7 +53,7 @@
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "slackapp.urls"
ROOT_URLCONF = "myslackapp.urls"

TEMPLATES = [
{
Expand All @@ -99,35 +71,44 @@
},
]

WSGI_APPLICATION = "slackapp.wsgi.application"
WSGI_APPLICATION = "myslackapp.wsgi.application"


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
# python manage.py migrate
# python manage.py runserver 0.0.0.0:3000
# You can initialize your local database by the following steps:
#
# python manage.py migrate
# python manage.py runserver 0.0.0.0:3000
#
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
# If you want to use MySQL quickly, the following steps work for you
#
# docker-compose -f mysql-docker-compose.yml up --build
# pip install mysqlclient
# python manage.py migrate
# python manage.py runserver 0.0.0.0:3000
#
# And then, enable the following setting instead:
#
# "default": {
# "ENGINE": "django.db.backends.sqlite3",
# "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
# "ENGINE": "django.db.backends.mysql",
# "NAME": "slackapp",
# "USER": "app",
# "PASSWORD": "password",
# "HOST": "127.0.0.1",
# "PORT": 33306,
# },

# docker-compose -f mysql-docker-compose.yml up --build
# pip install mysqlclient
# python manage.py migrate
# python manage.py runserver 0.0.0.0:3000
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "slackapp",
"USER": "app",
"PASSWORD": "password",
"HOST": "127.0.0.1",
"PORT": 33306,
},
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
Expand All @@ -144,8 +125,9 @@
},
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = "en-us"

Expand All @@ -157,7 +139,43 @@

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = "/static/"

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"


LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"console": {
"class": "logging.StreamHandler",
},
},
"root": {
"handlers": ["console"],
"level": "DEBUG",
},
"loggers": {
"django": {
"handlers": ["console"],
"level": os.getenv("DJANGO_LOG_LEVEL", "INFO"),
"propagate": False,
},
"django.db": {
"level": "DEBUG",
},
"slack_bolt": {
"handlers": ["console"],
"level": "DEBUG",
"propagate": False,
},
},
}
42 changes: 42 additions & 0 deletions examples/django/myslackapp/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""myslackapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

is_simple_app = True

if is_simple_app:
# A simple app that works only for a single Slack workspace
# (prerequisites)
# export SLACK_BOT_TOKEN=
# export SLACK_SIGNING_SECRET=
from simple_app.urls import slack_events_handler

urlpatterns = [path("slack/events", slack_events_handler)]
else:
# OAuth flow supported app
# (prerequisites)
# export SLACK_CLIENT_ID=
# export SLACK_CLIENT_SECRET=
# export SLACK_SIGNING_SECRET=
# export SLACK_SCOPES=app_mentions:read
from oauth_app.urls import slack_events_handler, slack_oauth_handler

urlpatterns = [
path("slack/events", slack_events_handler, name="handle"),
path("slack/install", slack_oauth_handler, name="install"),
path("slack/oauth_redirect", slack_oauth_handler, name="oauth_redirect"),
]
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"""
WSGI config for slackapp project.
WSGI config for myslackapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "slackapp.settings")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myslackapp.settings")

application = get_wsgi_application()
File renamed without changes.
Loading

0 comments on commit 51edf84

Please sign in to comment.