def test_init_close(self):
     client = SocketModeClient(app_token="xapp-A111-222-xyz")
     try:
         self.assertIsNotNone(client)
         self.assertFalse(client.is_connected())
     finally:
         client.close()
 def process(client: SocketModeClient, req: SocketModeRequest):
     if req.type == "events_api":
         response = SocketModeResponse(envelope_id=req.envelope_id)
         client.send_socket_mode_response(response)
         client.web_client.reactions_add(
             name="eyes",
             channel=req.payload["event"]["channel"],
             timestamp=req.payload["event"]["ts"],
         )
Ejemplo n.º 3
0
 def __init__(  # type: ignore
     self,
     app: App,  # type: ignore
     app_token: Optional[str] = None,
     logger: Optional[Logger] = None,
     web_client: Optional[WebClient] = None,
     ping_interval: float = 10,
     concurrency: int = 10,
     http_proxy_host: Optional[str] = None,
     http_proxy_port: Optional[int] = None,
     http_proxy_auth: Optional[Tuple[str, str]] = None,
     proxy_type: Optional[str] = None,
     trace_enabled: bool = False,
 ):
     self.app = app
     self.app_token = app_token or os.environ["SLACK_APP_TOKEN"]
     self.client = SocketModeClient(
         app_token=self.app_token,
         logger=logger if logger is not None else app.logger,
         web_client=web_client if web_client is not None else app.client,
         ping_interval=ping_interval,
         concurrency=concurrency,
         http_proxy_host=http_proxy_host,
         http_proxy_port=http_proxy_port,
         http_proxy_auth=http_proxy_auth,
         proxy_type=proxy_type,
         trace_enabled=trace_enabled,
     )
     self.client.socket_mode_request_listeners.append(self.handle)
 def __init__(  # type: ignore
     self,
     app: App,  # type: ignore
     app_token: Optional[str] = None,
 ):
     self.app = app
     self.app_token = app_token or os.environ["SLACK_APP_TOKEN"]
     self.client = SocketModeClient(app_token=self.app_token)
     self.client.socket_mode_request_listeners.append(self.handle)
Ejemplo n.º 5
0
    def __init__(  # type: ignore
        self,
        app: App,  # type: ignore
        app_token: Optional[str] = None,
        logger: Optional[Logger] = None,
        web_client: Optional[WebClient] = None,
        ping_interval: float = 10,
        concurrency: int = 10,
        http_proxy_host: Optional[str] = None,
        http_proxy_port: Optional[int] = None,
        http_proxy_auth: Optional[Tuple[str, str]] = None,
        proxy_type: Optional[str] = None,
        trace_enabled: bool = False,
    ):
        """Socket Mode adapter for Bolt apps

        Args:
            app: The Bolt app
            app_token: App-level token starting with `xapp-`
            logger: Custom logger
            web_client: custom `slack_sdk.web.WebClient` instance
            ping_interval: The ping-pong internal (seconds)
            concurrency: The size of the underlying thread pool
            http_proxy_host: HTTP proxy host
            http_proxy_port: HTTP proxy port
            http_proxy_auth: HTTP proxy authentication (username, password)
            proxy_type: Proxy type
            trace_enabled: True if trace-level logging is enabled
        """
        self.app = app
        self.app_token = app_token or os.environ["SLACK_APP_TOKEN"]
        self.client = SocketModeClient(
            app_token=self.app_token,
            logger=logger if logger is not None else app.logger,
            web_client=web_client if web_client is not None else app.client,
            ping_interval=ping_interval,
            concurrency=concurrency,
            http_proxy_host=http_proxy_host,
            http_proxy_port=http_proxy_port,
            http_proxy_auth=http_proxy_auth,
            proxy_type=proxy_type,
            trace_enabled=trace_enabled,
        )
        self.client.socket_mode_request_listeners.append(self.handle)
    def test_interactions(self):
        t = Thread(target=start_socket_mode_server(self, 3012))
        t.daemon = True
        t.start()

        received_messages = []
        received_socket_mode_requests = []

        def message_handler(ws_app, message):
            self.logger.info(f"Raw Message: {message}")
            time.sleep(randint(50, 200) / 1000)
            received_messages.append(message)

        def socket_mode_request_handler(client: BaseSocketModeClient,
                                        request: SocketModeRequest):
            self.logger.info(f"Socket Mode Request: {request}")
            time.sleep(randint(50, 200) / 1000)
            received_socket_mode_requests.append(request)

        client = SocketModeClient(
            app_token="xapp-A111-222-xyz",
            web_client=self.web_client,
            on_message_listeners=[message_handler],
            auto_reconnect_enabled=False,
            trace_enabled=True,
        )
        client.socket_mode_request_listeners.append(
            socket_mode_request_handler)

        try:
            time.sleep(1)  # wait for the server
            client.wss_uri = "ws://0.0.0.0:3012/link"
            client.connect()
            self.assertTrue(client.is_connected())
            time.sleep(1)  # wait for the message receiver

            for _ in range(10):
                client.send_message("foo")
                client.send_message("bar")
                client.send_message("baz")
            self.assertTrue(client.is_connected())

            expected = (socket_mode_envelopes + [socket_mode_hello_message] +
                        ["foo", "bar", "baz"] * 10)
            expected.sort()

            count = 0
            while count < 10 and len(received_messages) < len(expected):
                time.sleep(0.2)
                count += 0.2

            received_messages.sort()
            self.assertEqual(received_messages, expected)

            self.assertEqual(len(socket_mode_envelopes),
                             len(received_socket_mode_requests))
        finally:
            client.close()
            self.server.stop()
            self.server.close()
import os
from threading import Event
from slack_sdk.web import WebClient
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.websocket_client import SocketModeClient

client = SocketModeClient(
    app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"),
    web_client=WebClient(
        token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN"),
        # pip3 install proxy.py
        # proxy --port 9000 --log-level d
        proxy="http://localhost:9000",
    ),
    trace_enabled=True,
    # pip3 install proxy.py
    # proxy --port 9000 --log-level d
    http_proxy_host="localhost",
    http_proxy_port=9000,
    http_proxy_auth=("user", "pass"),
)

if __name__ == "__main__":

    def process(client: SocketModeClient, req: SocketModeRequest):
        if req.type == "events_api":
            response = SocketModeResponse(envelope_id=req.envelope_id)
            client.send_socket_mode_response(response)
            client.web_client.reactions_add(
Ejemplo n.º 8
0
    def test_send_message_while_disconnection(self):
        if is_ci_unstable_test_skip_enabled():
            return
        t = Thread(target=start_socket_mode_server(self, 3012))
        t.daemon = True
        t.start()
        time.sleep(2)  # wait for the server

        try:
            self.reset_sever_state()
            client = SocketModeClient(
                app_token="xapp-A111-222-xyz",
                web_client=self.web_client,
                auto_reconnect_enabled=False,
                trace_enabled=True,
            )
            client.wss_uri = "ws://0.0.0.0:3012/link"
            client.connect()
            time.sleep(1)  # wait for the connection
            client.send_message("foo")

            client.disconnect()
            time.sleep(1)  # wait for the connection
            try:
                client.send_message("foo")
                # TODO: The client may not raise an exception here
                # self.fail("WebSocketException is expected here")
            except WebSocketException as _:
                pass

            client.connect()
            time.sleep(1)  # wait for the connection
            client.send_message("foo")
        finally:
            client.close()
            self.server.stop()
            self.server.close()
import logging

logging.basicConfig(level=logging.DEBUG)

import os
from threading import Event
from slack_sdk.web import WebClient
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.websocket_client import SocketModeClient

client = SocketModeClient(
    app_token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_APP_TOKEN"),
    web_client=WebClient(token=os.environ.get("SLACK_SDK_TEST_SOCKET_MODE_BOT_TOKEN")),
    trace_enabled=True,
)

if __name__ == "__main__":

    def process(client: SocketModeClient, req: SocketModeRequest):
        if req.type == "events_api":
            response = SocketModeResponse(envelope_id=req.envelope_id)
            client.send_socket_mode_response(response)
            client.web_client.reactions_add(
                name="eyes",
                channel=req.payload["event"]["channel"],
                timestamp=req.payload["event"]["ts"],
            )

    client.socket_mode_request_listeners.append(process)
    client.connect()