Search code examples
slack-apiphpwebsocket

Issues using ratchetphp/Pawl websocket client


My question is specific to using slack rtm on ratchetphp/Pawl. I have below code which connects fine but dies eventually.

            <?php

            require_once "response.php";

            //first make authenticated call to rtm.start    
            use \Curl\Curl;
            $curl = new Curl();

            $rtmStartUrl = "https://slack.com/api/rtm.start?token=xx-xx-xx-xx-xx&pretty=1";
            $curl->get($rtmStartUrl);

            $wsUrl = $curl->response->url;

            $loop = React\EventLoop\Factory::create();
            $connector = new Ratchet\Client\Connector($loop);

            $connector($wsUrl)
            ->then(function(Ratchet\Client\WebSocket $conn) {
            $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
            echo "Received: {$msg}\n";
            // $conn->close();
            });

            $conn->on('close', function($code = null, $reason = null) {
            echo "Connection closed ({$code} - {$reason})\n";
            });

            $conn->send('Hello World!');
            }, function(\Exception $e) use ($loop) {
            echo "Could not connect: {$e->getMessage()}\n";
            $loop->stop();
            });

            $loop->run();

Upon running, the output is:

            root@ip-172-31-45-75:/var/www/html/slack# php pawl.php 
            Received: {"type":"hello"}
            Received: {"type":"reconnect_url","url":"wss://mpmulti-qpau.slack-msgs.com/websocket/jDkgDysXfZspRj10zqdcrshHK6PhPLItYx2HEkdXy47RPCAJwKgI_NLq0bhS4uMjIT7iRtOoCDUJffcxcr7YdiqMbITUZYqnTmT39Et5a8JeuPLFfCUUzan4MCz34p0jcfAKaQW9G9HpIWrYH4CTqyICZuhgWHnzo8K7dO2zXFc="}
            Received: {}
            Connection closed (1006 - Underlying connection closed)
            root@ip-172-31-45-75:/var/www/html/slack# 

The websocket is part of slack rtm api (https://api.slack.com/rtm). It seems like when reading on empty websocket, the connection is closed. I think it might be like we listen to slack events (https://api.slack.com/events) sent over websocket for working to avoid disconnect.

Currently, this does not work because of disconnection error.


Solution

  • Hello World! is not a valid message for this API, so Slack is closing the connection when it receives that message. Try sending something valid (or nothing at all).