Repository navigation
Expand file tree
/
Copy pathasync_handler.py
More file actions
74 lines (64 loc) · 2.64 KB
/
Copy pathasync_handler.py
File metadata and controls
74 lines (64 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from typing import Dict, Any, Optional
from starlette.requests import Request
from starlette.responses import Response
from slack_bolt import BoltResponse
from slack_bolt.async_app import AsyncApp, AsyncBoltRequest
from slack_bolt.oauth.async_oauth_flow import AsyncOAuthFlow
def to_async_bolt_request(
req: Request,
body: bytes,
addition_context_properties: Optional[Dict[str, Any]] = None,
) -> AsyncBoltRequest:
request = AsyncBoltRequest(
body=body.decode("utf-8"),
query=req.query_params, # type: ignore[arg-type]
headers=req.headers, # type: ignore[arg-type]
)
if addition_context_properties is not None:
for k, v in addition_context_properties.items():
request.context[k] = v
return request
def to_starlette_response(bolt_resp: BoltResponse) -> Response:
resp = Response(
status_code=bolt_resp.status,
content=bolt_resp.body,
headers=bolt_resp.first_headers_without_set_cookie(),
)
for cookie in bolt_resp.cookies():
for name, c in cookie.items():
resp.set_cookie(
key=name,
value=c.value,
max_age=c.get("max-age"),
expires=c.get("expires"),
path=c.get("path"),
domain=c.get("domain"),
secure=True,
httponly=True,
)
return resp
class AsyncSlackRequestHandler:
def __init__(self, app: AsyncApp):
self.app = app
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: AsyncOAuthFlow = self.app.oauth_flow
if req.url.path == oauth_flow.install_path:
bolt_resp = await oauth_flow.handle_installation(
to_async_bolt_request(req, body, addition_context_properties)
)
return to_starlette_response(bolt_resp)
elif req.url.path == oauth_flow.redirect_uri_path:
bolt_resp = await oauth_flow.handle_callback(
to_async_bolt_request(req, body, addition_context_properties)
)
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))
return to_starlette_response(bolt_resp)
return Response(
status_code=404,
content="Not found",
)