All Projects → mcrumm → Phlack

mcrumm / Phlack

Licence: mit
Slack Integrations for PHP

Projects that are alternatives of or similar to Phlack

Slackkit
Build Slack apps, in Swift
Stars: ✭ 977 (+1743.4%)
Mutual labels:  slack
Slack Memo Vim
Simple memo manager with Vim using Slack.
Stars: ✭ 40 (-24.53%)
Mutual labels:  slack
Craft Brief
Quick, easy, and customizable user-group notifications for Craft CMS.
Stars: ✭ 47 (-11.32%)
Mutual labels:  slack
Slack Thel
The Genious L, now in slack to answer all your Queries! 😎
Stars: ✭ 36 (-32.08%)
Mutual labels:  slack
Old Slack Emojis
Bring back old emojis to new Slack!
Stars: ✭ 39 (-26.42%)
Mutual labels:  slack
Terminal Slack
Terminal client for slack
Stars: ✭ 1,030 (+1843.4%)
Mutual labels:  slack
Vuejs Slack Clone Realtime
Slack clone using VueJS and firebase
Stars: ✭ 33 (-37.74%)
Mutual labels:  slack
Octoslack
OctoPrint plugin for Slack, Mattermost, Pushbullet, Pushover, Rocket.Chat, Discord, Riot/Matrix, & Microsoft Teams
Stars: ✭ 50 (-5.66%)
Mutual labels:  slack
Slackword
Dictionary in your slack....additionally, you can get random words.
Stars: ✭ 39 (-26.42%)
Mutual labels:  slack
Node Chat One To One
Node.js socket-io based one to one chat engine
Stars: ✭ 47 (-11.32%)
Mutual labels:  slack
Bolt Starter
A Bolt ⚡️ app template with useful settings for easier development
Stars: ✭ 37 (-30.19%)
Mutual labels:  slack
Slack Tui
TUI-based client for Slack
Stars: ✭ 38 (-28.3%)
Mutual labels:  slack
Mantisbt Slack
Slack integration for Mantis bug tracker
Stars: ✭ 45 (-15.09%)
Mutual labels:  slack
Koffeemate
Fresh coffee announcements on Slack. Brewing accidents and statistics too. For Android, written 100% in Kotlin.
Stars: ✭ 35 (-33.96%)
Mutual labels:  slack
Slack Twitter
Read your timeline, fave tweets, and post to Twitter from Slack.
Stars: ✭ 47 (-11.32%)
Mutual labels:  slack
Slack Api
A super simple PHP wrapper for Slack API
Stars: ✭ 34 (-35.85%)
Mutual labels:  slack
Webpack Deploy
Collection of useful utilities for deploying (not only) Webpack apps
Stars: ✭ 44 (-16.98%)
Mutual labels:  slack
Marvin
The paranoid bot (framework)
Stars: ✭ 51 (-3.77%)
Mutual labels:  slack
Slack Poster
Simple gem to post messages on Slack using web hooks.
Stars: ✭ 49 (-7.55%)
Mutual labels:  slack
Synology Notifications
Synology notifications service
Stars: ✭ 47 (-11.32%)
Mutual labels:  slack

Phlack

Build Status Scrutinizer Quality Score Code Coverage Total Downloads Latest Stable Version Latest Unstable Version License

Phlack eases the creation of Slack Integrations in PHP.

Installation

via composer:

composer require mcrumm/phlack

Basic Usage

Send a Message

<?php
$phlack = new Crummy\Phlack\Phlack('https://my.webhook.url');

$response = $phlack->send('Hello, from Phlack!');

if (200 === $response['status']) {
    echo 'Success!';
}

Advanced Usage

Legacy WebHook URLs

Early versions of Incoming Webhooks used a generic webhook path for all teams. If your webhook URL starts with something like myteam.slack.com, give Phlack your team name and Incoming Webhook token, and it will do the rest:

<?php
$phlack  = new Crummy\Phlack\Phlack([
    'username' => 'myteam',
    'token'    => 'my_webhook_token'
]);

Factory Method

If you prefer, you can instantiate Phlack via its static factory() method:

<?php
$phlack = Crummy\Phlack\Phlack::factory($config);

New Instance

Besides a webhook url or an array configuration, Phlack will also accept a PhlackClient instance as a constructor argument:

<?php
$client = new Crummy\Phlack\Bridge\Guzzle\PhlackClient('https://my.webhook.url');
$phlack = new Crummy\Phlack\Phlack($client);

Note: The constructor and factory method both accept the same types of arguments: a string representing the webhook url, an array of client config options, or a PhlackClient object.

❤️ for Guzzle

The PhlackClient is simply a web service client implemented with Guzzle. Examine its service description for more details.

Messages

Messages represent the payload for Slack's Incoming WebHook integration.

Creating Messages

Messages can be created using the provided builders, or they can be instantiated directly.

Message Builder

The MessageBuilder allows for programmatic creation of a Message object.

<?php
// ...
$messageBuilder = $phlack->getMessageBuilder();
$messageBuilder
  ->setText('I was created in the MessageBuilder')
  ->setChannel('testing')
  ->setIconEmoji('ghost');
$message = $messageBuilder->create();

You can also use the MessageBuilder directly to create the Message object and add Attachments. The MessageBuilder supports method chaining to allow for adding multiple Attachment objects to a single message.

$messageBuilder = $phlack->getMessageBuilder(); // Get the MessageBuilder

$messageBuilder
    ->setText('This message contains multiple attachments.') // Message text.
    ->createAttachment()  // Returns the AttachmentBuilder.
        ->setTitle($title)
        ->setTitleLink($link)
        ->setPretext($pretext)
        ->setText($body)
        ->setColor($color)
        ->setFallback($title . ' ' . $pretext)
    ->end() // Creates the first attachment and returns the MessageBuilder
    ->setUsername($username) // Sets username on the Message object.
    ->createAttachment() // Returns the AttachmentBuilder.
        ->setTitle('Attachment #2')
        ->setFallback('Attachment #2 for example purposes')
        ->setText('Add multiple attachments to a Phlack Message via method chaining.')
    ->end() // Creates the second attachment and returns the MessageBuilder.
;

$message = $messageBuilder->create();

Note: When adding Attachments this way, you must call end() once for each attachment so that the MessageBuilder knows to create the Attachment object and return itself for further modification.

Attachment Builder

If you prefer, you may use the AttachmentBuilder in a standalone fashion:

<?php
// ...

// Get the AttachmentBuilder
$attachmentBuilder = $phlack->getAttachmentBuilder();

// Create the Attachment
$attachment =
    $attachmentBuilder
        ->setTitle('My Attachment Title')
        ->setTitleLink('http://www.example.com')
        ->setPretext('Some optional pretext')
        ->setText('This is the body of my attachment')
        ->setColor($color)
        ->addField('Field 1', 'Some Value', true)
        ->setFallback($title . ' ' . $pretext)
    ->create()
;

// Create a Message to contain the Attachment
$message = new \Crummy\Phlack\Message\Message('This message contains an attachment.');

// Add the Attachment to the Message
$message->addAttachment($attachment);

Message Object

A Message can be instantiated with just a text value:

<?php
//...
use Crummy\Phlack\Message\Message;
$message = new Message('Hello, from phlack!');
echo 'The message payload: ' . PHP_EOL:
echo $message; // Output: {"text": "Hello, from phlack!"}

But you can set optional parameters when constructing the message, too:

<?php
//...
use Crummy\Phlack\Message\Message;
$message = new Message('Hello, from phlack!', '#random');
echo 'The message payload: ' . PHP_EOL:
echo $message; // Output: {"text": "Hello, from phlack!", "channel": "#random"}

Sending Messages

Use Phlack's send() command to fire off the message:

<?php
// ...
$response = $phlack->send($message);

if (200 != $response['status']) {
  die('FAIL! - ' . $response['text']);
}

echo 'The message was sent: ' . $message;

Custom Messages

Custom messages can be sent by using an array of valid parameters:

<?php
$phlack->send([
    'channel'      => '#random',
    'icon_emoji'   => '🌮',
    'username'     => 'Phlack',
    'unfurl_links' => true,
    'text'         => 'I ❤️ the <http://api.slack.com|Slack API>!',
]);

Note: No input validation is performed on custom message parameters. You are responsible for formatting channels, emojis, and text data yourself.

Message Response

The MessageResponse hash contains the status, reason, and text from the response.

Responses from the Incoming Webhooks Integration are very sparse. Success messages will simply return a status of 200. Error messages will contain more details in the response text and reason.

More Examples

See the examples directory for more use cases.


Slack API

Programmatic access to the Slack API is provided via the ApiClient.

Note: Currently, bearer token authentication is the only supported authentication method. Contributions toward OAuth2 support would be greatly appreciated.

Getting a Client

Get an ApiClient object by instantiating it with a hash containing your API token, or passing a config hash to its factory method.

via factory():

<?php

use Crummy\Phlack\Bridge\Guzzle\ApiClient;

$slack = ApiClient::factory([ 'token' => 'my_bearer_token' ]);

via new ApiClient():

<?php

use Crummy\Phlack\Bridge\Guzzle\ApiClient;

$slack = new ApiClient([ 'token' => 'my_bearer_token' ]);

API Methods

The methods currently implemented are:

Consult the client's service description for information on the responses returned by the API methods.

Example: Listing all Channels

<?php

use Crummy\Phlack\Bridge\Guzzle\ApiClient;

$config = [ 'token' => 'my_bearer_token' ];
$slack = new ApiClient($config);

echo 'Fetching Channels List...' . PHP_EOL;
$result = $slack->ListChannels();

if (!$result['ok']) {
    die('FAIL! Error was: ' . $result['error'] . PHP_EOL);
}

foreach ($result['channels'] as $channel) {
    printf('%s: %s' . PHP_EOL, $channel['name'], $channel['purpose']['value']);
}

Resource Iterators

Example: ListFilesIterator

The ListFilesIterator eases the ability to iterate through multiple pages of data from the Slack API. Using the iterator eliminates the need to manually call the API multiple times to retrieve all pages of the result set.

<?php
//...
$iterator = $slack->getIterator('ListFiles');

$i = 0;
foreach ($iterator as $file) {
    $i++;
    echo $file['title'] . PHP_EOL;
}

echo PHP_EOL . 'Retrieved ' . $i . ' files.' . PHP_EOL;

A complete example is available in the examples directory.

Note: The ListFilesIterator is not strictly necessary to page through file results, but it's certainly easier than the alternative. An example without the iterator is also available.

More API Examples

See the API examples directory for more use cases.


Disclaimer

Any undocumented portion of this library should be considered EXPERIMENTAL AT BEST. Proceed with caution, and, as always, pull requests are welcome.

Credits

The regex in the LinkFormatter was pulled directly from StevenSloan and his slack-notifier project.

Contributing

Please see the CONTRIBUTING file for details.

License

Phlack is released under the MIT License. See the bundled LICENSE file for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].