def __init__(self, authorize: AsyncAuthorize):
        """Multi-workspace authorization.

        :param authorize: The function to authorize incoming requests from Slack.
        """
        self.authorize = authorize
        self.logger = get_bolt_logger(AsyncMultiTeamsAuthorization)
    def __init__(self, *, auth_test_result: Optional[SlackResponse] = None):
        """Single-workspace authorization.

        :param auth_test_result: The initial `auth.test` API call result.
        """
        self.auth_test_result = auth_test_result
        self.logger = get_bolt_logger(SingleTeamAuthorization)
Пример #3
0
    def __init__(self, signing_secret: str):
        """Verifies an incoming request by checking the validity of
        x-slack-signature, x-slack-request-timestamp, and its body data.

        :param signing_secret: The signing secret.
        """
        self.verifier = SignatureVerifier(signing_secret=signing_secret)
        self.logger = get_bolt_logger(RequestVerification)
 def __init__(
     self,
     installation_store: AsyncInstallationStore,
     verification_enabled: bool = True,
 ):
     self.installation_store = installation_store
     self.verification_enabled = verification_enabled
     self.logger = get_bolt_logger(AsyncMultiTeamsAuthorization)
Пример #5
0
    def __init__(self, verification_token: str = None):
        """Handles ssl_check requests.

        Refer to https://api.slack.com/interactivity/slash-commands for details.
        :param verification_token: The verification token to check
            (optional as it's already deprecated - https://api.slack.com/authentication/verifying-requests-from-slack#verification_token_deprecation)
        """
        self.verification_token = verification_token
        self.logger = get_bolt_logger(SslCheck)
Пример #6
0
    def __init__(self, signing_secret: str):
        """Verifies an incoming request by checking the validity of
        `x-slack-signature`, `x-slack-request-timestamp`, and its body data.

        Refer to https://api.slack.com/authentication/verifying-requests-from-slack for details.

        Args:
            signing_secret: The signing secret
        """
        self.verifier = SignatureVerifier(signing_secret=signing_secret)
        self.logger = get_bolt_logger(RequestVerification)
Пример #7
0
 def __init__(self, verification_token: str = None):
     self.verification_token = verification_token
     self.logger = get_bolt_logger(SslCheck)
Пример #8
0
    def __init__(
        self,
        *,
        # Used in logger
        name: Optional[str] = None,
        # Set True when you run this app on a FaaS platform
        process_before_response: bool = False,
        # Basic Information > Credentials > Signing Secret
        signing_secret: Optional[str] = None,
        # for single-workspace apps
        token: Optional[str] = None,
        client: Optional[AsyncWebClient] = None,
        # for multi-workspace apps
        installation_store: Optional[AsyncInstallationStore] = None,
        oauth_state_store: Optional[AsyncOAuthStateStore] = None,
        oauth_state_cookie_name: str = OAuthStateUtils.default_cookie_name,
        oauth_state_expiration_seconds: int = OAuthStateUtils.
        default_expiration_seconds,
        # for the OAuth flow
        oauth_flow: Optional[AsyncOAuthFlow] = None,
        client_id: Optional[str] = None,
        client_secret: Optional[str] = None,
        scopes: Optional[List[str]] = None,
        user_scopes: Optional[List[str]] = None,
        redirect_uri: Optional[str] = None,
        oauth_install_path: Optional[str] = None,
        oauth_redirect_uri_path: Optional[str] = None,
        oauth_success_url: Optional[str] = None,
        oauth_failure_url: Optional[str] = None,
        # No need to set (the value is used only in response to ssl_check requests)
        verification_token: Optional[str] = None,
    ):
        signing_secret = signing_secret or os.environ.get(
            "SLACK_SIGNING_SECRET", None)
        token = token or os.environ.get("SLACK_BOT_TOKEN", None)

        if signing_secret is None or signing_secret == "":
            raise BoltError(
                "Signing secret not found, so could not initialize the Bolt app."
            )

        self._name: str = name or inspect.stack()[1].filename.split(
            os.path.sep)[-1]
        self._signing_secret: str = signing_secret

        client_id = client_id or os.environ.get("SLACK_CLIENT_ID", None)
        client_secret = client_secret or os.environ.get(
            "SLACK_CLIENT_SECRET", None)
        scopes = scopes or os.environ.get("SLACK_SCOPES", "").split(",")
        user_scopes = user_scopes or os.environ.get("SLACK_USER_SCOPES",
                                                    "").split(",")
        redirect_uri = redirect_uri or os.environ.get("SLACK_REDIRECT_URI",
                                                      None)
        oauth_install_path = oauth_install_path or os.environ.get(
            "SLACK_INSTALL_PATH", "/slack/install")
        oauth_redirect_uri_path = oauth_redirect_uri_path or os.environ.get(
            "SLACK_REDIRECT_URI_PATH", "/slack/oauth_redirect")

        self._verification_token: Optional[
            str] = verification_token or os.environ.get(
                "SLACK_VERIFICATION_TOKEN", None)
        self._framework_logger = get_bolt_logger(AsyncApp)

        self._token: Optional[str] = token

        if client is not None:
            self._async_client = client
            self._token = client.token
            if token is not None:
                self._framework_logger.warning(
                    "As you gave client as well, the bot token will be unused."
                )
        else:
            # NOTE: the token here can be None
            self._async_client = create_async_web_client(token)

        self._async_installation_store: Optional[
            AsyncInstallationStore] = installation_store
        self._async_oauth_state_store: Optional[
            AsyncOAuthStateStore] = oauth_state_store

        self._oauth_state_cookie_name = oauth_state_cookie_name
        self._oauth_state_expiration_seconds = oauth_state_expiration_seconds

        self._async_oauth_flow: Optional[AsyncOAuthFlow] = None
        if oauth_flow:
            self._async_oauth_flow = oauth_flow
            if self._async_installation_store is None:
                self._async_installation_store = (
                    self._async_oauth_flow.installation_store)
            if self._async_oauth_state_store is None:
                self._async_oauth_state_store = self._async_oauth_flow.oauth_state_store
            if self._async_oauth_flow._async_client is None:
                self._async_oauth_flow._async_client = self._async_client
        else:
            if client_id is not None and client_secret is not None:
                # The OAuth flow support is enabled
                if (self._async_installation_store is None
                        and self._async_oauth_state_store is None):
                    # use the default ones
                    self._async_installation_store = FileInstallationStore(
                        client_id=client_id, )
                    self._async_oauth_state_store = FileOAuthStateStore(
                        expiration_seconds=self.
                        _oauth_state_expiration_seconds,
                        client_id=client_id,
                    )

                if (self._async_installation_store is not None
                        and self._async_oauth_state_store is None):
                    raise ValueError(
                        f"Configure an appropriate OAuthStateStore for {self._async_installation_store}"
                    )

                self._async_oauth_flow = AsyncOAuthFlow(
                    client=create_async_web_client(),
                    logger=self._framework_logger,
                    # required storage implementations
                    installation_store=self._async_installation_store,
                    oauth_state_store=self._async_oauth_state_store,
                    oauth_state_cookie_name=self._oauth_state_cookie_name,
                    oauth_state_expiration_seconds=self.
                    _oauth_state_expiration_seconds,
                    # used for oauth.v2.access calls
                    client_id=client_id,
                    client_secret=client_secret,
                    # installation url parameters
                    scopes=scopes,
                    user_scopes=user_scopes,
                    redirect_uri=redirect_uri,
                    # path in this app
                    install_path=oauth_install_path,
                    redirect_uri_path=oauth_redirect_uri_path,
                    # urls after callback
                    success_url=oauth_success_url,
                    failure_url=oauth_failure_url,
                )

        if self._async_installation_store is not None and self._token is not None:
            self._token = None
            self._framework_logger.warning(
                "As you gave installation_store as well, the bot token will be unused."
            )

        self._async_middleware_list: List[Union[Callable,
                                                AsyncMiddleware]] = []
        self._async_listeners: List[AsyncListener] = []
        self._process_before_response = process_before_response

        self._init_middleware_list_done = False
        self._init_async_middleware_list()
 def __init__(self):
     """Ignores the events generated by this bot user itself."""
     self.logger = get_bolt_logger(IgnoringSelfEvents)
Пример #10
0
 def __init__(self, *, func: Callable[..., Union[bool, Awaitable[bool]]]):
     self.func = func
     self.arg_names = inspect.getfullargspec(func).args
     self.logger = get_bolt_logger(self.func)
Пример #11
0
    def __init__(self):
        """Handles url_verification requests.

        Refer to https://api.slack.com/events/url_verification for details.
        """
        self.logger = get_bolt_logger(UrlVerification)
Пример #12
0
    def __init__(
        self,
        *,
        logger: Optional[logging.Logger] = None,
        # Used in logger
        name: Optional[str] = None,
        # Set True when you run this app on a FaaS platform
        process_before_response: bool = False,
        # Basic Information > Credentials > Signing Secret
        signing_secret: Optional[str] = None,
        # for single-workspace apps
        token: Optional[str] = None,
        token_verification_enabled: bool = True,
        client: Optional[WebClient] = None,
        # for multi-workspace apps
        authorize: Optional[Callable[..., AuthorizeResult]] = None,
        installation_store: Optional[InstallationStore] = None,
        # for v1.0.x compatibility
        installation_store_bot_only: Optional[bool] = None,
        # for the OAuth flow
        oauth_settings: Optional[OAuthSettings] = None,
        oauth_flow: Optional[OAuthFlow] = None,
        # No need to set (the value is used only in response to ssl_check requests)
        verification_token: Optional[str] = None,
    ):
        """Bolt App that provides functionalities to register middleware/listeners

        :param name: The application name that will be used in logging.
            If absent, the source file name will be used instead.
        :param process_before_response: True if this app runs on Function as a Service. (Default: False)
        :param signing_secret: The Signing Secret value used for verifying requests from Slack.
        :param token: The bot access token required only for single-workspace app.
        :param token_verification_enabled: Verifies the validity of the given token if True.
        :param client: The singleton slack_sdk.WebClient instance for this app.
        :param authorize: The function to authorize an incoming request from Slack
            by checking if there is a team/user in the installation data.
        :param installation_store: The module offering save/find operations of installation data
        :param installation_store_bot_only: Use InstallationStore#find_bot if True (Default: False)
        :param oauth_settings: The settings related to Slack app installation flow (OAuth flow)
        :param oauth_flow: Manually instantiated slack_bolt.oauth.OAuthFlow.
            This is always prioritized over oauth_settings.
        :param verification_token: Deprecated verification mechanism.
            This can used only for ssl_check requests.
        """
        signing_secret = signing_secret or os.environ.get(
            "SLACK_SIGNING_SECRET")
        token = token or os.environ.get("SLACK_BOT_TOKEN")

        self._name: str = name or inspect.stack()[1].filename.split(
            os.path.sep)[-1]
        self._signing_secret: str = signing_secret

        self._verification_token: Optional[
            str] = verification_token or os.environ.get(
                "SLACK_VERIFICATION_TOKEN", None)
        self._framework_logger = logger or get_bolt_logger(App)

        self._token: Optional[str] = token

        if client is not None:
            if not isinstance(client, WebClient):
                raise BoltError(error_client_invalid_type())
            self._client = client
            self._token = client.token
            if token is not None:
                self._framework_logger.warning(
                    warning_client_prioritized_and_token_skipped())
        else:
            self._client = create_web_client(
                token)  # NOTE: the token here can be None

        # --------------------------------------
        # Authorize & OAuthFlow initialization
        # --------------------------------------

        self._authorize: Optional[Authorize] = None
        if authorize is not None:
            if oauth_settings is not None or oauth_flow is not None:
                raise BoltError(error_authorize_conflicts())
            self._authorize = CallableAuthorize(logger=self._framework_logger,
                                                func=authorize)

        self._installation_store: Optional[
            InstallationStore] = installation_store
        if self._installation_store is not None and self._authorize is None:
            self._authorize = InstallationStoreAuthorize(
                installation_store=self._installation_store,
                logger=self._framework_logger,
                bot_only=installation_store_bot_only,
            )

        self._oauth_flow: Optional[OAuthFlow] = None

        if (oauth_settings is None
                and os.environ.get("SLACK_CLIENT_ID") is not None
                and os.environ.get("SLACK_CLIENT_SECRET") is not None):
            # initialize with the default settings
            oauth_settings = OAuthSettings()

        if oauth_flow:
            self._oauth_flow = oauth_flow
            installation_store = select_consistent_installation_store(
                client_id=self._oauth_flow.client_id,
                app_store=self._installation_store,
                oauth_flow_store=self._oauth_flow.settings.installation_store,
                logger=self._framework_logger,
            )
            self._installation_store = installation_store
            self._oauth_flow.settings.installation_store = installation_store

            if self._oauth_flow._client is None:
                self._oauth_flow._client = self._client
            if self._authorize is None:
                self._authorize = self._oauth_flow.settings.authorize
        elif oauth_settings is not None:
            installation_store = select_consistent_installation_store(
                client_id=oauth_settings.client_id,
                app_store=self._installation_store,
                oauth_flow_store=oauth_settings.installation_store,
                logger=self._framework_logger,
            )
            self._installation_store = installation_store
            oauth_settings.installation_store = installation_store
            self._oauth_flow = OAuthFlow(client=self.client,
                                         logger=self.logger,
                                         settings=oauth_settings)
            if self._authorize is None:
                self._authorize = self._oauth_flow.settings.authorize

        if (self._installation_store is not None
                or self._authorize is not None) and self._token is not None:
            self._token = None
            self._framework_logger.warning(warning_token_skipped())

        # after setting bot_only here, __init__ cannot replace authorize function
        if installation_store_bot_only is not None and self._oauth_flow is not None:
            app_bot_only = installation_store_bot_only or False
            oauth_flow_bot_only = self._oauth_flow.settings.installation_store_bot_only
            if app_bot_only != oauth_flow_bot_only:
                self.logger.warning(warning_bot_only_conflicts())
                self._oauth_flow.settings.installation_store_bot_only = app_bot_only
                self._authorize.bot_only = app_bot_only

        # --------------------------------------
        # Middleware Initialization
        # --------------------------------------

        self._middleware_list: List[Union[Callable, Middleware]] = []
        self._listeners: List[Listener] = []

        listener_executor = ThreadPoolExecutor(max_workers=5)
        self._listener_runner = ThreadListenerRunner(
            logger=self._framework_logger,
            process_before_response=process_before_response,
            listener_error_handler=DefaultListenerErrorHandler(
                logger=self._framework_logger),
            listener_executor=listener_executor,
            lazy_listener_runner=ThreadLazyListenerRunner(
                logger=self._framework_logger,
                executor=listener_executor,
            ),
        )

        self._init_middleware_list_done = False
        self._init_middleware_list(
            token_verification_enabled=token_verification_enabled)
Пример #13
0
 def __init__(self, signing_secret: str):
     self.verifier = SignatureVerifier(signing_secret=signing_secret)
     self.logger = get_bolt_logger(RequestVerification)
Пример #14
0
 def __init__(self):
     self.logger = get_bolt_logger(UrlVerification)
Пример #15
0
 def __init__(self):
     self.logger = get_bolt_logger(AsyncSingleTeamAuthorization)
Пример #16
0
 def __init__(self):
     self.logger = get_bolt_logger(IgnoringSelfEvents)
Пример #17
0
    def __init__(
        self,
        *,
        logger: Optional[logging.Logger] = None,
        # Used in logger
        name: Optional[str] = None,
        # Set True when you run this app on a FaaS platform
        process_before_response: bool = False,
        # Basic Information > Credentials > Signing Secret
        signing_secret: Optional[str] = None,
        # for single-workspace apps
        token: Optional[str] = None,
        client: Optional[AsyncWebClient] = None,
        # for multi-workspace apps
        installation_store: Optional[AsyncInstallationStore] = None,
        authorize: Optional[Callable[..., Awaitable[AuthorizeResult]]] = None,
        # for the OAuth flow
        oauth_settings: Optional[AsyncOAuthSettings] = None,
        oauth_flow: Optional[AsyncOAuthFlow] = None,
        # No need to set (the value is used only in response to ssl_check requests)
        verification_token: Optional[str] = None,
    ):
        """Bolt App that provides functionalities to register middleware/listeners

        :param name: The application name that will be used in logging.
            If absent, the source file name will be used instead.
        :param process_before_response: True if this app runs on Function as a Service. (Default: False)
        :param signing_secret: The Signing Secret value used for verifying requests from Slack.
        :param token: The bot access token required only for single-workspace app.
        :param client: The singleton slack_sdk.web.async_client.AsyncWebClient instance for this app.
        :param installation_store: The module offering save/find operations of installation data
        :param authorize: The function to authorize an incoming request from Slack
            by checking if there is a team/user in the installation data.
        :param oauth_settings: The settings related to Slack app installation flow (OAuth flow)
        :param oauth_flow: Manually instantiated slack_bolt.oauth.async_oauth_flow.AsyncOAuthFlow.
            This is always prioritized over oauth_settings.
        :param verification_token: Deprecated verification mechanism.
            This can used only for ssl_check requests.
        """
        signing_secret = signing_secret or os.environ.get(
            "SLACK_SIGNING_SECRET")
        token = token or os.environ.get("SLACK_BOT_TOKEN")

        self._name: str = name or inspect.stack()[1].filename.split(
            os.path.sep)[-1]
        self._signing_secret: str = signing_secret
        self._verification_token: Optional[
            str] = verification_token or os.environ.get(
                "SLACK_VERIFICATION_TOKEN", None)
        self._framework_logger = logger or get_bolt_logger(AsyncApp)

        self._token: Optional[str] = token

        if client is not None:
            if not isinstance(client, AsyncWebClient):
                raise BoltError(error_client_invalid_type_async())
            self._async_client = client
            self._token = client.token
            if token is not None:
                self._framework_logger.warning(
                    warning_client_prioritized_and_token_skipped())
        else:
            # NOTE: the token here can be None
            self._async_client = create_async_web_client(token)

        self._async_authorize: Optional[AsyncAuthorize] = None
        if authorize is not None:
            if oauth_settings is not None or oauth_flow is not None:
                raise BoltError(error_authorize_conflicts())

            self._async_authorize = AsyncCallableAuthorize(
                logger=self._framework_logger, func=authorize)

        self._async_installation_store: Optional[
            AsyncInstallationStore] = installation_store
        if self._async_installation_store is not None and self._async_authorize is None:
            self._async_authorize = AsyncInstallationStoreAuthorize(
                installation_store=self._async_installation_store,
                logger=self._framework_logger,
            )

        self._async_oauth_flow: Optional[AsyncOAuthFlow] = None

        if (oauth_settings is None
                and os.environ.get("SLACK_CLIENT_ID") is not None
                and os.environ.get("SLACK_CLIENT_SECRET") is not None):
            # initialize with the default settings
            oauth_settings = AsyncOAuthSettings()

        if oauth_flow:
            if not isinstance(oauth_flow, AsyncOAuthFlow):
                raise BoltError(error_oauth_flow_invalid_type_async())

            self._async_oauth_flow = oauth_flow
            installation_store = select_consistent_installation_store(
                client_id=self._async_oauth_flow.client_id,
                app_store=self._async_installation_store,
                oauth_flow_store=self._async_oauth_flow.settings.
                installation_store,
                logger=self._framework_logger,
            )
            self._async_installation_store = installation_store
            self._async_oauth_flow.settings.installation_store = installation_store

            if self._async_oauth_flow._async_client is None:
                self._async_oauth_flow._async_client = self._async_client
            if self._async_authorize is None:
                self._async_authorize = self._async_oauth_flow.settings.authorize
        elif oauth_settings is not None:
            if not isinstance(oauth_settings, AsyncOAuthSettings):
                raise BoltError(error_oauth_settings_invalid_type_async())

            installation_store = select_consistent_installation_store(
                client_id=oauth_settings.client_id,
                app_store=self._async_installation_store,
                oauth_flow_store=oauth_settings.installation_store,
                logger=self._framework_logger,
            )
            self._async_installation_store = installation_store
            oauth_settings.installation_store = installation_store

            self._async_oauth_flow = AsyncOAuthFlow(client=self._async_client,
                                                    logger=self.logger,
                                                    settings=oauth_settings)
            if self._async_authorize is None:
                self._async_authorize = self._async_oauth_flow.settings.authorize

        if (self._async_installation_store is not None or self._async_authorize
                is not None) and self._token is not None:
            self._token = None
            self._framework_logger.warning(warning_token_skipped())

        self._async_middleware_list: List[Union[Callable,
                                                AsyncMiddleware]] = []
        self._async_listeners: List[AsyncListener] = []

        self._async_listener_runner = AsyncioListenerRunner(
            logger=self._framework_logger,
            process_before_response=process_before_response,
            listener_error_handler=AsyncDefaultListenerErrorHandler(
                logger=self._framework_logger),
            lazy_listener_runner=AsyncioLazyListenerRunner(
                logger=self._framework_logger, ),
        )

        self._init_middleware_list_done = False
        self._init_async_middleware_list()

        self._server: Optional[AsyncSlackAppServer] = None
Пример #18
0
 def __init__(self):
     """Single-workspace authorization."""
     self.auth_test_result: Optional[AsyncSlackResponse] = None
     self.logger = get_bolt_logger(AsyncSingleTeamAuthorization)