Skip to content

Commit

Permalink
Implement Lazy Listener Functions slackapi#34 (slackapi#35)
Browse files Browse the repository at this point in the history
* Implement Lazy Listener Functions slackapi#34

* Add unit tests

* Remove test.pypi.org from instructions

* Fix errors in Python 3.6

* Apply formtter to samples

* Fix type hints
  • Loading branch information
seratch authored Aug 26, 2020
1 parent dd855e1 commit 5a702cd
Show file tree
Hide file tree
Showing 34 changed files with 1,216 additions and 242 deletions.
5 changes: 1 addition & 4 deletions samples/aws_chalice/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
from slack_bolt.adapter.aws_lambda.chalice_handler import ChaliceSlackRequestHandler

# process_before_response must be True when running on FaaS
bolt_app = App(
process_before_response=True,
authorization_test_enabled=False,
)
bolt_app = App(process_before_response=True, authorization_test_enabled=False,)


@bolt_app.event("app_mention")
Expand Down
5 changes: 1 addition & 4 deletions samples/aws_chalice/simple_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,7 @@
from slack_bolt.adapter.aws_lambda.chalice_handler import ChaliceSlackRequestHandler

# process_before_response must be True when running on FaaS
bolt_app = App(
process_before_response=True,
authorization_test_enabled=False,
)
bolt_app = App(process_before_response=True, authorization_test_enabled=False,)


@bolt_app.event("app_mention")
Expand Down
3 changes: 2 additions & 1 deletion samples/aws_lambda/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
vendor/
vendor/
.env
6 changes: 6 additions & 0 deletions samples/aws_lambda/deploy_lazy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/bash
rm -rf vendor && mkdir -p vendor/slack_bolt && cp -pr ../../slack_bolt/* vendor/slack_bolt/
pip install python-lambda -U
lambda deploy \
--config-file lazy_aws_lambda_config.yaml \
--requirements requirements.txt
57 changes: 57 additions & 0 deletions samples/aws_lambda/lazy_aws_lambda.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# ------------------------------------------------
# instead of slack_bolt in requirements.txt
import sys
import time

sys.path.insert(1, "vendor")
# ------------------------------------------------

import logging

from slack_bolt import App
from slack_bolt.adapter.aws_lambda import SlackRequestHandler

# process_before_response must be True when running on FaaS
app = App(process_before_response=True)


@app.middleware # or app.use(log_request)
def log_request(logger, payload, next):
logger.debug(payload)
return next()


command = "/hello-bolt-python-lambda"


def respond_to_slack_within_3_seconds(payload, ack):
if payload.get("text", None) is None:
ack(f":x: Usage: {command} (description here)")
else:
title = payload["text"]
ack(f"Accepted! (task: {title})")


def process_request(respond, payload):
time.sleep(5)
title = payload["text"]
respond(f"Completed! (task: {title})")


app.command(command)(ack=respond_to_slack_within_3_seconds, lazy=[process_request])

SlackRequestHandler.clear_all_log_handlers()
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.DEBUG)


def handler(event, context):
slack_handler = SlackRequestHandler(app=app)
return slack_handler.handle(event, context)


# export SLACK_SIGNING_SECRET=***
# export SLACK_BOT_TOKEN=xoxb-***

# rm -rf vendor && cp -pr ../../src/* vendor/
# pip install python-lambda
# lambda deploy --config-file aws_lambda_config.yaml --requirements requirements.txt
40 changes: 40 additions & 0 deletions samples/aws_lambda/lazy_aws_lambda_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
region: us-east-1

function_name: bolt_py_function
handler: lazy_aws_lambda.handler
description: My first lambda function
runtime: python3.8
# role: lambda_basic_execution
role: bolt_python_lambda_invocation # AWSLambdaFullAccess

# S3 upload requires appropriate role with s3:PutObject permission
# (ex. basic_s3_upload), a destination bucket, and the key prefix
# bucket_name: 'example-bucket'
# s3_key_prefix: 'path/to/file/'

# if access key and secret are left blank, boto will use the credentials
# defined in the [default] section of ~/.aws/credentials.
aws_access_key_id:
aws_secret_access_key:

# dist_directory: dist
# timeout: 15
# memory_size: 512
# concurrency: 500
#

# Experimental Environment variables
environment_variables:
SLACK_BOT_TOKEN: ${SLACK_BOT_TOKEN}
SLACK_SIGNING_SECRET: ${SLACK_SIGNING_SECRET}

# If `tags` is uncommented then tags will be set at creation or update
# time. During an update all other tags will be removed except the tags
# listed here.
#tags:
# tag_1: foo
# tag_2: bar

# Build options
build:
source_directories: vendor # a comma delimited list of directories in your project root that contains source to package.
4 changes: 3 additions & 1 deletion samples/django/slackapp/slackapp/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@

# 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
Expand Down
36 changes: 24 additions & 12 deletions samples/async_modals_app.py → samples/lazy_async_modals_app.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
# ------------------------------------------------
# instead of slack_bolt in requirements.txt
import asyncio
import sys

sys.path.insert(1, "..")
# ------------------------------------------------

import asyncio
import logging
from slack_bolt.async_app import AsyncApp

logging.basicConfig(level=logging.DEBUG)

from slack_bolt.async_app import AsyncApp

app = AsyncApp()


Expand All @@ -21,11 +20,12 @@ async def log_request(logger, payload, next):
return await next()


@app.command("/hello-bolt-python")
async def handle_command(payload, ack, respond, client, logger):
async def ack_command(payload, ack, logger):
logger.info(payload)
await ack("Accepted!")
await ack("Thanks!")


async def post_button_message(respond):
await respond(
blocks=[
{
Expand All @@ -45,6 +45,8 @@ async def handle_command(payload, ack, respond, client, logger):
]
)


async def open_modal(payload, client, logger):
res = await client.views_open(
trigger_id=payload["trigger_id"],
view={
Expand All @@ -66,6 +68,7 @@ async def handle_command(payload, ack, respond, client, logger):
"type": "external_select",
"action_id": "es_a",
"placeholder": {"type": "plain_text", "text": "Select an item"},
"min_query_length": 0,
},
"label": {"type": "plain_text", "text": "Search"},
},
Expand All @@ -76,6 +79,7 @@ async def handle_command(payload, ack, respond, client, logger):
"type": "multi_external_select",
"action_id": "mes_a",
"placeholder": {"type": "plain_text", "text": "Select an item"},
"min_query_length": 0,
},
"label": {"type": "plain_text", "text": "Search (multi)"},
},
Expand All @@ -85,6 +89,11 @@ async def handle_command(payload, ack, respond, client, logger):
logger.info(res)


app.command("/hello-bolt-python")(
ack=ack_command, lazy=[post_button_message, open_modal],
)


@app.options("es_a")
async def show_options(ack):
await ack(
Expand Down Expand Up @@ -125,19 +134,22 @@ async def show_multi_options(ack):


@app.view("view-id")
async def view_submission(ack, payload, logger):
async def handle_view_submission(ack, payload, logger):
await ack()
logger.info(payload["view"]["state"]["values"])


@app.action("a")
async def button_click(ack, respond):
async def ack_button_click(ack, respond):
await ack()
await respond("Loading ...")


async def respond_5_seconds_later(respond):
await asyncio.sleep(5)
await respond(
{"response_type": "in_channel", "text": "Clicked!",}
)
await respond("Completed!")


app.action("a")(ack=ack_button_click, lazy=[respond_5_seconds_later])

if __name__ == "__main__":
app.start(3000)
Expand Down
Loading

0 comments on commit 5a702cd

Please sign in to comment.