Mattermost Webhooks and PHP
In a recent attempt to automate a few things even more, I was looking for a way to post messages to our Mattermost instance via the Incoming Webhook feature of Mattermost. I did a quick search on Packagist for Mattermost client libraries and as it turns out there a quite a few. I picked the thibaud-dauce/mattermost-php package simply because it was the first match ;)
Installing the library via Composer is a no-brainer:
composer.phar require thibaud-dauce/mattermost-php
The library uses Guzzle under the hood to communicate with the Mattermost Incoming Webhooks. Luckily, a current version of Guzzle is used which is PSR-7 compliant. This allowed me to use Guzzle to consume a JSON file from an HTTP server like this:
$client = new \GuzzleHttp\Client; $response = $client->request('GET', 'http://somehost.loc/data.json'); $data = json_decode($response->getBody()->getContents());
To instantiate the Mattermost object which handles the communication part against the Mattermost API, all I needed to do was to create a new Mattermost instance and pass the Guzzle client as a constructor dependency:
$mattermost = new \ThibaudDauce\Mattermost\Mattermost($client);
The Mattermost client just offers one public method called send() to send the given message to the Mattermost server. That means we need to create a Message object first:
$message = new \ThibaudDauce\Mattermost\Message(); $message->text('Hello world!');
The library also supports message attachments which need to be configured via a callable:
$message = new Message(); $message->text('Hello world!'); $message->attachment( function(\ThibaudDauce\Mattermost\Attachment $attachment) { $attachment->fallback('This is some fallback text') ->pretext('This message will appear above the attachment') ->imageUrl('http://somehost.loc/image.png'); } );
Last, not least pass the $message as well as the url of the incoming webhook to the Mattermost::send() method:
$mattermost->send( $message, 'http://mattermost.loc/hooks/gya1uqt2eept7jawzxx1ml8yey' );
This will send the message to the channel which the incoming webhook is registered for.