Skip to content

Instantly share code, notes, and snippets.

@sagebind
Last active November 22, 2016 05:30
Show Gist options
  • Save sagebind/00f50d7ad28f5f9ff56b to your computer and use it in GitHub Desktop.
Save sagebind/00f50d7ad28f5f9ff56b to your computer and use it in GitHub Desktop.
Example program using slack-client
<?php
require __DIR__ . "/vendor/autoload.php";
use React\EventLoop;
use Slack\ChannelInterface;
use Slack\RealTimeClient;
$loop = EventLoop\Factory::create();
$client = new RealTimeClient($loop);
$client->setToken("some token");
// Wait for a user to type a message.
$client->on("message", function ($data) use ($client) {
// Look for certain text. The array contains keys corresponding to the event
// data documented in the Slack events API: https://api.slack.com/events
if (strpos($data["text"], "bot respond") !== false) {
// Asynchronously get whatever kind of channel the message was sent in.
$client->getChannelGroupOrDMByID($data["channel"])->then(function (ChannelInterface $channel) use ($client) {
// After the channel object was fetched, we can continue.
// Send a message to the same channel the original message was posted in.
return $client->send("Hello!", $channel)->then(null, function (\Exception $exception) { // <-- First callback isn't
// necessary, since send() doesn't resolve with a
// return value and we don't need to do anything else afterwards.
echo "Sending message failed!\n" . $exception . "\n";
});
}, function (\Exception $exception) {
// Pass in a second callback to then() to catch exceptions.
echo "Getting channel failed!\n" . $exception . "\n";
});
}
});
// Connect to the Slack server.
$client->connect()->then(function () {
echo "Connected!\n";
});
// Run the event loop.
$loop->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment