11import base64
22import logging
3- from typing import List
3+ from typing import List , Dict , Optional
44
55from slack_bolt .app import App
66from slack_bolt .logger import get_bolt_app_logger
77from slack_bolt .oauth import OAuthFlow
88from slack_bolt .request import BoltRequest
99from slack_bolt .response import BoltResponse
1010
11- # https://stackoverflow.com/questions/37703609/using-python-logging-with-aws-lambda
12- root = logging .getLogger ()
13- if root .handlers :
14- for handler in root .handlers :
15- root .removeHandler (handler )
16-
1711
1812class SlackRequestHandler ():
1913 def __init__ (self , app : App ):
2014 self .app = app
2115 self .logger = get_bolt_app_logger (app .name , SlackRequestHandler )
2216
17+ @classmethod
18+ def clear_all_log_handlers (cls ):
19+ # https://stackoverflow.com/questions/37703609/using-python-logging-with-aws-lambda
20+ root = logging .getLogger ()
21+ if root .handlers :
22+ for handler in root .handlers :
23+ root .removeHandler (handler )
24+
2325 def handle (self , event , context ):
2426 self .logger .debug (f"Incoming event: { event } , context: { context } " )
2527
@@ -29,11 +31,13 @@ def handle(self, event, context):
2931 if method == "GET" :
3032 if self .app .oauth_flow is not None :
3133 oauth_flow : OAuthFlow = self .app .oauth_flow
32- bolt_req = to_bolt_request (event )
34+ bolt_req : BoltRequest = to_bolt_request (event )
3335 query = bolt_req .query
34- is_callback = (query .get ("code" , None ) is not None \
35- and query .get ("state" , None ) is not None ) \
36- or query .get ("error" , None ) is not None
36+ is_callback = query is not None and (
37+ (_first_value (query , "code" ) is not None and _first_value (query , "state" ) is not None )
38+ or
39+ _first_value (query , "error" ) is not None
40+ )
3741 if is_callback :
3842 bolt_resp = oauth_flow .handle_callback (bolt_req )
3943 return to_aws_response (bolt_resp )
@@ -49,7 +53,15 @@ def handle(self, event, context):
4953 return not_found ()
5054
5155
52- def to_bolt_request (event ):
56+ def _first_value (query : Dict [str , List [str ]], name : str ) -> Optional [str ]:
57+ if query :
58+ values = query .get (name , [])
59+ if values and len (values ) > 0 :
60+ return values [0 ]
61+ return None
62+
63+
64+ def to_bolt_request (event ) -> BoltRequest :
5365 body = event .get ("body" , "" )
5466 if event ["isBase64Encoded" ]:
5567 body = base64 .b64decode (body ).decode ("utf-8" )
@@ -63,15 +75,15 @@ def to_bolt_request(event):
6375 )
6476
6577
66- def to_aws_response (resp : BoltResponse ):
78+ def to_aws_response (resp : BoltResponse ) -> Dict [ str , any ] :
6779 return {
6880 "statusCode" : resp .status ,
6981 "body" : resp .body ,
7082 "headers" : resp .first_headers (),
7183 }
7284
7385
74- def not_found ():
86+ def not_found () -> Dict [ str , any ] :
7587 return {
7688 "statusCode" : 404 ,
7789 "body" : "Not Found" ,
0 commit comments