Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# change black settings
0e4cd56b69e8f83166cd262f762802b7f18c3d21
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# black project prefers pyproject.toml
# that's why we have this file in addition to other setting files
[tool.black]
line-length = 125

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the key change in this PR. With having this file, running black command always respects this configuration

1 change: 0 additions & 1 deletion scripts/build_pypi_package.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ cd ${script_dir}/..
rm -rf ./slack_bolt.egg-info

pip install -U pip && \
python setup.py test && \
pip install twine wheel && \
rm -rf dist/ build/ slack_bolt.egg-info/ && \
python setup.py sdist bdist_wheel && \
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
universal = 1

[aliases]
test=pytest
test=pytest
9 changes: 2 additions & 7 deletions slack_bolt/adapter/aws_lambda/chalice_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@ class ChaliceSlackRequestHandler:
def __init__(self, app: App, chalice: Chalice, lambda_client: Optional[BaseClient] = None): # type: ignore
self.app = app
self.chalice = chalice
self.logger = get_bolt_app_logger(
app.name, ChaliceSlackRequestHandler, app.logger
)
self.logger = get_bolt_app_logger(app.name, ChaliceSlackRequestHandler, app.logger)

if getenv("AWS_CHALICE_CLI_MODE") == "true" and lambda_client is None:
try:
Expand Down Expand Up @@ -64,10 +62,7 @@ def handle(self, request: Request):
bolt_req: BoltRequest = to_bolt_request(request, body)
query = bolt_req.query
is_callback = query is not None and (
(
_first_value(query, "code") is not None
and _first_value(query, "state") is not None
)
(_first_value(query, "code") is not None and _first_value(query, "state") is not None)
or _first_value(query, "error") is not None
)
if is_callback:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ def start(self, function: Callable[..., None], request: BoltRequest) -> None:

chalice_request: dict = request.context["chalice_request"]
request.headers["x-slack-bolt-lazy-only"] = ["1"]
request.headers["x-slack-bolt-lazy-function-name"] = [
request.lazy_function_name
]
request.headers["x-slack-bolt-lazy-function-name"] = [request.lazy_function_name]
payload = {
"method": "NONE",
"headers": {k: v[0] for k, v in request.headers.items()},
Expand Down
9 changes: 2 additions & 7 deletions slack_bolt/adapter/aws_lambda/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ class SlackRequestHandler:
def __init__(self, app: App): # type: ignore
self.app = app
self.logger = get_bolt_app_logger(app.name, SlackRequestHandler, app.logger)
self.app.listener_runner.lazy_listener_runner = LambdaLazyListenerRunner(
self.logger
)
self.app.listener_runner.lazy_listener_runner = LambdaLazyListenerRunner(self.logger)
if self.app.oauth_flow is not None:
self.app.oauth_flow.settings.redirect_uri_page_renderer.install_path = "?"

Expand All @@ -44,10 +42,7 @@ def handle(self, event, context):
bolt_req: BoltRequest = to_bolt_request(event)
query = bolt_req.query
is_callback = query is not None and (
(
_first_value(query, "code") is not None
and _first_value(query, "state") is not None
)
(_first_value(query, "code") is not None and _first_value(query, "state") is not None)
or _first_value(query, "error") is not None
)
if is_callback:
Expand Down
16 changes: 4 additions & 12 deletions slack_bolt/adapter/aws_lambda/lambda_s3_oauth_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,18 @@ def __init__(
client_id=os.environ["SLACK_CLIENT_ID"],
client_secret=os.environ["SLACK_CLIENT_SECRET"],
)
oauth_state_bucket_name = (
oauth_state_bucket_name or os.environ["SLACK_STATE_S3_BUCKET_NAME"]
)
installation_bucket_name = (
installation_bucket_name or os.environ["SLACK_INSTALLATION_S3_BUCKET_NAME"]
)
oauth_state_bucket_name = oauth_state_bucket_name or os.environ["SLACK_STATE_S3_BUCKET_NAME"]
installation_bucket_name = installation_bucket_name or os.environ["SLACK_INSTALLATION_S3_BUCKET_NAME"]
self.s3_client = boto3.client("s3")
if settings.state_store is None or not isinstance(
settings.state_store, AmazonS3OAuthStateStore
):
if settings.state_store is None or not isinstance(settings.state_store, AmazonS3OAuthStateStore):
settings.state_store = AmazonS3OAuthStateStore(
logger=logger,
s3_client=self.s3_client,
bucket_name=oauth_state_bucket_name,
expiration_seconds=settings.state_expiration_seconds,
)

if settings.installation_store is None or not isinstance(
settings.installation_store, AmazonS3InstallationStore
):
if settings.installation_store is None or not isinstance(settings.installation_store, AmazonS3InstallationStore):
settings.installation_store = AmazonS3InstallationStore(
logger=logger,
s3_client=self.s3_client,
Expand Down
4 changes: 1 addition & 3 deletions slack_bolt/adapter/aws_lambda/lazy_listener_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ def start(self, function: Callable[..., None], request: BoltRequest) -> None:
event: dict = request.context["lambda_request"]
headers = event["headers"]
headers["x-slack-bolt-lazy-only"] = "1" # not an array
headers[
"x-slack-bolt-lazy-function-name"
] = request.lazy_function_name # not an array
headers["x-slack-bolt-lazy-function-name"] = request.lazy_function_name # not an array
event["method"] = "NONE"
invocation = self.lambda_client.invoke(
FunctionName=request.context["aws_lambda_function_name"],
Expand Down
4 changes: 1 addition & 3 deletions slack_bolt/adapter/aws_lambda/local_lambda_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ def invoke(
Payload: str = "{}",
) -> InvokeResponse:
scoped = self._config.scope(self._config.chalice_stage, FunctionName)
lambda_context = LambdaContext(
FunctionName, memory_size=scoped.lambda_memory_size
)
lambda_context = LambdaContext(FunctionName, memory_size=scoped.lambda_memory_size)

with self._patched_env_vars(scoped.environment_variables):
response = self._app(json.loads(Payload), lambda_context)
Expand Down
24 changes: 6 additions & 18 deletions slack_bolt/adapter/django/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,11 @@ def start(self, function: Callable[..., None], request: BoltRequest) -> None:
)

def wrapped_func():
release_thread_local_connections(
request.context.logger, "before-lazy-listener"
)
release_thread_local_connections(request.context.logger, "before-lazy-listener")
try:
func()
finally:
release_thread_local_connections(
request.context.logger, "lazy-listener-completion"
)
release_thread_local_connections(request.context.logger, "lazy-listener-completion")

self.executor.submit(wrapped_func)

Expand All @@ -124,9 +120,7 @@ def __init__(self, app: App): # type: ignore
)

if not isinstance(listener_runner, ThreadListenerRunner):
raise BoltError(
"Custom listener_runners are not compatible with this Django adapter."
)
raise BoltError("Custom listener_runners are not compatible with this Django adapter.")

if app.process_before_response is True:
# As long as the app access Django models in the same thread,
Expand All @@ -135,9 +129,7 @@ def __init__(self, app: App): # type: ignore
return

current_start_handler = listener_runner.listener_start_handler
if current_start_handler is not None and not isinstance(
current_start_handler, DefaultListenerStartHandler
):
if current_start_handler is not None and not isinstance(current_start_handler, DefaultListenerStartHandler):
# As we run release_thread_local_connections() before listener executions,
# it's okay to skip calling the same connection clean-up method at the listener completion.
message = """As you've already set app.listener_runner.listener_start_handler to your own one,
Expand All @@ -152,9 +144,7 @@ def __init__(self, app: App): # type: ignore
self.app.logger.info(message)
else:
# for proper management of thread-local Django DB connections
self.app.listener_runner.listener_start_handler = (
DjangoListenerStartHandler()
)
self.app.listener_runner.listener_start_handler = DjangoListenerStartHandler()
self.app.logger.debug("DjangoListenerStartHandler has been enabled")

current_completion_handler = listener_runner.listener_completion_handler
Expand All @@ -169,9 +159,7 @@ def __init__(self, app: App): # type: ignore
self.app.logger.info(message)
return
# for proper management of thread-local Django DB connections
self.app.listener_runner.listener_completion_handler = (
DjangoListenerCompletionHandler()
)
self.app.listener_runner.listener_completion_handler = DjangoListenerCompletionHandler()
self.app.logger.debug("DjangoListenerCompletionHandler has been enabled")

def handle(self, req: HttpRequest) -> HttpResponse:
Expand Down
18 changes: 4 additions & 14 deletions slack_bolt/adapter/falcon/async_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,19 @@ class AsyncSlackAppResource:

def __init__(self, app: AsyncApp): # type: ignore
if falcon_version.__version__.startswith("2."):
raise BoltError(
"This ASGI compatible adapter requires Falcon version >= 3.0"
)
raise BoltError("This ASGI compatible adapter requires Falcon version >= 3.0")

self.app = app

async def on_get(self, req: Request, resp: Response):
if self.app.oauth_flow is not None:
oauth_flow: AsyncOAuthFlow = self.app.oauth_flow
if req.path == oauth_flow.install_path:
bolt_resp = await oauth_flow.handle_installation(
await self._to_bolt_request(req)
)
bolt_resp = await oauth_flow.handle_installation(await self._to_bolt_request(req))
await self._write_response(bolt_resp, resp)
return
elif req.path == oauth_flow.redirect_uri_path:
bolt_resp = await oauth_flow.handle_callback(
await self._to_bolt_request(req)
)
bolt_resp = await oauth_flow.handle_callback(await self._to_bolt_request(req))
await self._write_response(bolt_resp, resp)
return

Expand All @@ -69,11 +63,7 @@ async def _write_response(self, bolt_resp: BoltResponse, resp: Response):
for cookie in bolt_resp.cookies():
for name, c in cookie.items():
expire_value = c.get("expires")
expire = (
datetime.strptime(expire_value, "%a, %d %b %Y %H:%M:%S %Z")
if expire_value
else None
)
expire = datetime.strptime(expire_value, "%a, %d %b %Y %H:%M:%S %Z") if expire_value else None
resp.set_cookie(
name=name,
value=c.value,
Expand Down
6 changes: 1 addition & 5 deletions slack_bolt/adapter/falcon/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,7 @@ def _write_response(self, bolt_resp: BoltResponse, resp: Response):
for cookie in bolt_resp.cookies():
for name, c in cookie.items():
expire_value = c.get("expires")
expire = (
datetime.strptime(expire_value, "%a, %d %b %Y %H:%M:%S %Z")
if expire_value
else None
)
expire = datetime.strptime(expire_value, "%a, %d %b %Y %H:%M:%S %Z") if expire_value else None
resp.set_cookie(
name=name,
value=c.value,
Expand Down
8 changes: 2 additions & 6 deletions slack_bolt/adapter/sanic/async_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,10 @@ async def handle(self, req: Request) -> HTTPResponse:
if self.app.oauth_flow is not None:
oauth_flow: AsyncOAuthFlow = self.app.oauth_flow
if req.path == oauth_flow.install_path:
bolt_resp = await oauth_flow.handle_installation(
to_async_bolt_request(req)
)
bolt_resp = await oauth_flow.handle_installation(to_async_bolt_request(req))
return to_sanic_response(bolt_resp)
elif req.path == oauth_flow.redirect_uri_path:
bolt_resp = await oauth_flow.handle_callback(
to_async_bolt_request(req)
)
bolt_resp = await oauth_flow.handle_callback(to_async_bolt_request(req))
return to_sanic_response(bolt_resp)

elif req.method == "POST":
Expand Down
4 changes: 1 addition & 3 deletions slack_bolt/adapter/socket_mode/async_base_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@ class AsyncBaseSocketModeHandler:
app: Union[App, AsyncApp] # type: ignore
client: AsyncBaseSocketModeClient

async def handle(
self, client: AsyncBaseSocketModeClient, req: SocketModeRequest
) -> None:
async def handle(self, client: AsyncBaseSocketModeClient, req: SocketModeRequest) -> None:
"""Handles Socket Mode envelope requests through a WebSocket connection.

Args:
Expand Down
12 changes: 3 additions & 9 deletions slack_bolt/adapter/socket_mode/async_internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,10 @@ async def send_async_response(
if bolt_resp.status == 200:
content_type = bolt_resp.headers.get("content-type", [""])[0]
if bolt_resp.body is None or len(bolt_resp.body) == 0:
await client.send_socket_mode_response(
SocketModeResponse(envelope_id=req.envelope_id)
)
await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id))
elif content_type.startswith("application/json"):
dict_body = json.loads(bolt_resp.body)
await client.send_socket_mode_response(
SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body)
)
await client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body))
else:
await client.send_socket_mode_response(
SocketModeResponse(
Expand All @@ -46,6 +42,4 @@ async def send_async_response(
spent_time = int((time() - start_time) * 1000)
client.logger.debug(f"Response time: {spent_time} milliseconds")
else:
client.logger.info(
f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})"
)
client.logger.info(f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})")
16 changes: 4 additions & 12 deletions slack_bolt/adapter/socket_mode/internals.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,17 @@ def send_response(
if bolt_resp.status == 200:
content_type = bolt_resp.headers.get("content-type", [""])[0]
if bolt_resp.body is None or len(bolt_resp.body) == 0:
client.send_socket_mode_response(
SocketModeResponse(envelope_id=req.envelope_id)
)
client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id))
elif content_type.startswith("application/json"):
dict_body = json.loads(bolt_resp.body)
client.send_socket_mode_response(
SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body)
)
client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id, payload=dict_body))
else:
client.send_socket_mode_response(
SocketModeResponse(
envelope_id=req.envelope_id, payload={"text": bolt_resp.body}
)
SocketModeResponse(envelope_id=req.envelope_id, payload={"text": bolt_resp.body})
)

if client.logger.level <= logging.DEBUG:
spent_time = int((time() - start_time) * 1000)
client.logger.debug(f"Response time: {spent_time} milliseconds")
else:
client.logger.info(
f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})"
)
client.logger.info(f"Unsuccessful Bolt execution result (status: {bolt_resp.status}, body: {bolt_resp.body})")
8 changes: 2 additions & 6 deletions slack_bolt/adapter/starlette/async_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ class AsyncSlackRequestHandler:
def __init__(self, app: AsyncApp): # type: ignore
self.app = app

async def handle(
self, req: Request, addition_context_properties: Optional[Dict[str, Any]] = None
) -> Response:
async def handle(self, req: Request, addition_context_properties: Optional[Dict[str, Any]] = None) -> Response:
body = await req.body()
if req.method == "GET":
if self.app.oauth_flow is not None:
Expand All @@ -67,9 +65,7 @@ async def handle(
)
return to_starlette_response(bolt_resp)
elif req.method == "POST":
bolt_resp = await self.app.async_dispatch(
to_async_bolt_request(req, body, addition_context_properties)
)
bolt_resp = await self.app.async_dispatch(to_async_bolt_request(req, body, addition_context_properties))
return to_starlette_response(bolt_resp)

return Response(
Expand Down
16 changes: 4 additions & 12 deletions slack_bolt/adapter/starlette/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,27 +48,19 @@ class SlackRequestHandler:
def __init__(self, app: App): # type: ignore
self.app = app

async def handle(
self, req: Request, addition_context_properties: Optional[Dict[str, Any]] = None
) -> Response:
async def handle(self, req: Request, addition_context_properties: Optional[Dict[str, Any]] = None) -> Response:
body = await req.body()
if req.method == "GET":
if self.app.oauth_flow is not None:
oauth_flow: OAuthFlow = self.app.oauth_flow
if req.url.path == oauth_flow.install_path:
bolt_resp = oauth_flow.handle_installation(
to_bolt_request(req, body, addition_context_properties)
)
bolt_resp = oauth_flow.handle_installation(to_bolt_request(req, body, addition_context_properties))
return to_starlette_response(bolt_resp)
elif req.url.path == oauth_flow.redirect_uri_path:
bolt_resp = oauth_flow.handle_callback(
to_bolt_request(req, body, addition_context_properties)
)
bolt_resp = oauth_flow.handle_callback(to_bolt_request(req, body, addition_context_properties))
return to_starlette_response(bolt_resp)
elif req.method == "POST":
bolt_resp = self.app.dispatch(
to_bolt_request(req, body, addition_context_properties)
)
bolt_resp = self.app.dispatch(to_bolt_request(req, body, addition_context_properties))
return to_starlette_response(bolt_resp)

return Response(
Expand Down
Loading