|
| 1 | +# Slack PHP – Socket Mode |
| 2 | + |
| 3 | +This package provides a slack-php `AppServer` implementation that allows an application written for the |
| 4 | +[Slack App Framework for PHP][1] to be run in [Socket Mode][2]. Socket Mode uses the websocket protocol to communicate |
| 5 | +with Slack, and allows you to run an app (even locally) without having to expose it via a public HTTP endpoint. This can |
| 6 | +be very useful for testing Slack apps in a way that does not violate most work-related firewall restrictions. |
| 7 | + |
| 8 | +**This package should be used for testing only, and is not designed for production use.** |
| 9 | + |
| 10 | +> This Socket Mode implementation uses the [`amphp/websocket-client`][3] package from [Amp][4], an awesome collection of |
| 11 | +PHP packages that make async and event loop style programming in PHP possible. Check it out sometime. |
| 12 | + |
| 13 | +## Installation |
| 14 | + |
| 15 | +- Requires PHP 7.4+ |
| 16 | +- Use Composer to install: `composer require slack-php/slack-socket-mode` |
| 17 | + |
| 18 | +## Usage |
| 19 | + |
| 20 | +When using Socket Mode, there is no web server serving your app. When you run an app configured for Socket Mode, it |
| 21 | +establishes a connection to Slack as a websocket client. It maintains that connection to listen for Slack events until |
| 22 | +it is explicitly terminated (e.g., via `CTRL+C`), Socket Mode is disabled in your app configuration, or an unrecoverable |
| 23 | +error occurs. This is a different way of running PHP than many are used to, so please pay close attention. |
| 24 | + |
| 25 | +When running an app in Slack Mode, you need an "App Token" instead of the typical "Signing Secret". The App Token is |
| 26 | +specially purposed for making the web socket connection. You can read more about [Socket Mode][2] in the Slack |
| 27 | +documentation to learn how to get an App Token. |
| 28 | + |
| 29 | +### Example |
| 30 | + |
| 31 | +This small app responds to the `/cool` slash command. |
| 32 | + |
| 33 | +> Assumptions: |
| 34 | +> |
| 35 | +> - You have required the Composer autoloader to enable autoloading of the framework files. |
| 36 | +> - You have set `SLACK_APP_TOKEN` in the environment (e.g., `putenv("SLACK_APP_TOKEN=foo");`) |
| 37 | +
|
| 38 | +```php |
| 39 | +<?php |
| 40 | + |
| 41 | +use SlackPhp\Framework\App; |
| 42 | +use SlackPhp\Framework\Context; |
| 43 | +use SlackPhp\SocketMode\SocketServer; |
| 44 | + |
| 45 | +App::new() |
| 46 | + ->command('cool', function (Context $ctx) { |
| 47 | + $ctx->ack(':thumbsup: That is so cool!'); |
| 48 | + }) |
| 49 | + ->run(new SocketServer()); |
| 50 | +``` |
| 51 | + |
| 52 | +[1]: https://github.com/slack-php/slack-php-app-framework |
| 53 | +[2]: https://api.slack.com/apis/connections/socket |
| 54 | +[3]: https://amphp.org/websocket-client/ |
| 55 | +[4]: https://amphp.org/ |
0 commit comments