A simple PHP package for sending messages to Slack, with a focus on ease of use and elegant syntax.

Related tags

Miscellaneous slack
Overview

Slack for PHP

Build Status Scrutinizer Code Quality StyleCI

A simple PHP package for sending messages to Slack with incoming webhooks, focussed on ease-of-use and elegant syntax. Note: this package is no longer being actively maintained.

Requirements

  • PHP 5.5, 5.6, 7.0 or HHVM

Installation

You can install the package using the Composer package manager. You can install it by running this command in your project root:

composer require maknz/slack

Then create an incoming webhook on your Slack account for the package to use. You'll need the webhook URL to instantiate the client (or for the configuration file if using Laravel).

Basic Usage

Instantiate the client

// Instantiate without defaults
$client = new Maknz\Slack\Client('https://hooks.slack.com/...');

// Instantiate with defaults, so all messages created
// will be sent from 'Cyril' and to the #accounting channel
// by default. Any names like @regan or #channel will also be linked.
$settings = [
	'username' => 'Cyril',
	'channel' => '#accounting',
	'link_names' => true
];

$client = new Maknz\Slack\Client('https://hooks.slack.com/...', $settings);

Settings

The default settings are pretty good, but you may wish to set up default behaviour for your client to be used for all messages sent. All settings are optional and you don't need to provide any. Where not provided, we'll fallback to what is configured on the webhook integration, which are managed at Slack, or our sensible defaults.

Field Type Description
channel string The default channel that messages will be sent to
username string The default username for your bot
icon string The default icon that messages will be sent with, either :emoji: or a URL to an image
link_names bool Whether names like @regan or #accounting should be linked in the message (defaults to false)
unfurl_links bool Whether Slack should unfurl text-based URLs (defaults to false)
unfurl_media bool Whether Slack should unfurl media-based URLs, like tweets or Youtube videos (defaults to true)
allow_markdown bool Whether markdown should be parsed in messages, or left as plain text (defaults to true)
markdown_in_attachments array Which attachment fields should have markdown parsed (defaults to none)

Sending messages

Sending a basic message (preview)

$client->send('Hello world!');

Sending a message to a non-default channel

$client->to('#accounting')->send('Are we rich yet?');

Sending a message to a user

$client->to('@regan')->send('Yo!');

Sending a message to a channel as a different bot name (preview)

$client->from('Jake the Dog')->to('@FinnTheHuman')->send('Adventure time!');

Sending a message with a different icon (preview)

// Either with a Slack emoji
$client->to('@regan')->withIcon(':ghost:')->send('Boo!');

// or a URL
$client->to('#accounting')->withIcon('http://example.com/accounting.png')->send('Some accounting notification');

Send an attachment (preview)

$client->to('#operations')->attach([
	'fallback' => 'Server health: good',
	'text' => 'Server health: good',
	'color' => 'danger',
])->send('New alert from the monitoring system'); // no message, but can be provided if you'd like

Send an attachment with fields (preview)

$client->to('#operations')->attach([
	'fallback' => 'Current server stats',
	'text' => 'Current server stats',
	'color' => 'danger',
	'fields' => [
		[
			'title' => 'CPU usage',
			'value' => '90%',
			'short' => true // whether the field is short enough to sit side-by-side other fields, defaults to false
		],
		[
			'title' => 'RAM usage',
			'value' => '2.5GB of 4GB',
			'short' => true
		]
	]
])->send('New alert from the monitoring system'); // no message, but can be provided if you'd like

Send an attachment with an author (preview)

$client->to('@regan')->attach([
	'fallback' => 'Keep up the great work! I really love how the app works.',
	'text' => 'Keep up the great work! I really love how the app works.',
	'author_name' => 'Jane Appleseed',
	'author_link' => 'https://yourapp.com/feedback/5874601',
	'author_icon' => 'https://static.pexels.com/photos/61120/pexels-photo-61120-large.jpeg'
])->send('New user feedback');

Advanced usage

Markdown

By default, Markdown is enabled for message text, but disabled for attachment fields. This behaviour can be configured in settings, or on the fly:

Send a message enabling or disabling Markdown

$client->to('#weird')->disableMarkdown()->send('Disable *markdown* just for this message');

$client->to('#general')->enableMarkdown()->send('Enable _markdown_ just for this message');

Send an attachment specifying which fields should have Markdown enabled

$client->to('#operations')->attach([
	'fallback' => 'It is all broken, man',
	'text' => 'It is _all_ broken, man',
	'pretext' => 'From user: *JimBob*',
	'color' => 'danger',
	'mrkdwn_in' => ['pretext', 'text']
])->send('New alert from the monitoring system');

Explicit message creation

For convenience, message objects are created implicitly by calling message methods on the client. We can however do this explicitly to avoid hitting the magic method.

// Implicitly
$client->to('@regan')->send('I am sending this implicitly');

// Explicitly
$message = $client->createMessage();

$message->to('@regan')->setText('I am sending this explicitly');

$message->send();

Attachments

When using attachments, the easiest way is to provide an array of data as shown in the examples, which is actually converted to an Attachment object under the hood. You can also attach an Attachment object to the message:

$attachment = new Attachment([
	'fallback' => 'Some fallback text',
	'text' => 'The attachment text'
]);

// Explicitly create a message from the client
// rather than using the magic passthrough methods
$message = $client->createMessage();

$message->attach($attachment);

// Explicitly set the message text rather than
// implicitly through the send method
$message->setText('Hello world')->send();

Each attachment field is also an object, an AttachmentField. They can be used as well instead of their data in array form:

$attachment = new Attachment([
	'fallback' => 'Some fallback text',
	'text' => 'The attachment text',
	'fields' => [
		new AttachmentField([
			'title' => 'A title',
			'value' => 'A value',
			'short' => true
		])
	]
]);

You can also set the attachments and fields directly if you have a whole lot of them:

// implicitly create a message and set the attachments
$client->setAttachments($bigArrayOfAttachments);

// or explicitly
$client->createMessage()->setAttachments($bigArrayOfAttachments);
$attachment = new Attachment([]);

$attachment->setFields($bigArrayOfFields);

Contributing

If you're having problems, spot a bug, or have a feature suggestion, please log and issue on Github. If you'd like to have a crack yourself, fork the package and make a pull request. Please include tests for any added or changed functionality. If it's a bug, include a regression test.

Issues
  • Can't use with this SDK

    Can't use with this SDK

    Hi.. I get this error:

     Catchable fatal error: Argument 1 passed to React\Promise\Promise::__construct() must be callable, null given, called in /home/yakir/slack-app/vendor/react/promise/src/Deferred.php on line 25 and defined in /home/yakir/slack-app/vendor/react/promise/src/Promise.php on line 16
    

    That's the code:

    use \Maknz\Slack\Client;
    
    include( __DIR__ . '/vendor/autoload.php' );
    $settings = [];
    $client = new Client( 'my.endpoint', $settings );
    $client->send( 'Test msg' );
    
    opened by KingYes 17
  • Added .env for portability

    Added .env for portability

    Settings are now .env customizable.

    SLACK_ENDPOINT=https://hooks.slack.com/services/
    SLACK_CHANNEL=#general
    SLACK_USERNAME=Slack-News
    SLACK_ICON=
    SLACK_LINK_NAMES=true
    SLACK_UNFURL_LINKS=false
    SLACK_UNFURL_MEDIA=true
    SLACK_MARKDOWN=true
    

    After adding settings to .env, you can now use the Slack facade directly.

    Slack::send('🎉');
    
    opened by sonnygauran 15
  • Ensure utf8

    Ensure utf8

    If non-utf8 data is provided, the json encoding fails and an Exception is thrown.

    Instead the data should be converted to utf8, if non-utf8 data is provided.

    todo 
    opened by tomsommer 11
  • Add dev settings for default channel

    Add dev settings for default channel

    I'm looking for a way to be able to test Slack messages from PHP without disturbing "real" channels.

    I'm thinking about two options: dev_channel (string) and dev_env (bool).

    • dev_channel: Specifies a channel to post when the dev_env is enabled. Will override all channel global or local (on message) settings.
    • dev_env: Activate the dev env and the dev_channel option. Could be use with framework envs for example.

    Code example:

    $settings = [
        'username' => 'Cyril',
        'channel' => '#accounting',
        'dev_channel' => '#test',
        'dev_env' => true,
        'link_names' => true
    ];
    
    $client = new Maknz\Slack\Client('http://your.slack.endpoint', $settings);
    
    $client->send('Hello world!'); // Will send to #test
    $client->to('#other_channel')->send('Are we rich yet?'); // Will send to #test too
    

    What do you think? I'll work on a PR for that.

    opened by soullivaneuh 10
  • Adding as_user and ability to change channel topics

    Adding as_user and ability to change channel topics

    Are these things that would be easily done in the future. I think they'd be a great addition :) Any insight or help getting this accomplished would be hugely appreciated.

    I think enabling as_user would be great so you don't see BOT for every post. (if this can't be done I apologize)

    And changing channel topics would be great for Slack community mods whom want to schedule those for whatever particular reason.

    opened by tjmapes 9
  • can't generate config file

    can't generate config file

    I have a brand new installation of Laravel 5.2 and after adding the package with composer require maknz/slack (Using version ^1.7 for maknz/slack) and then trying to run php artisan vendor:publish --provider="Maknz/Slack/SlackServiceProviderLaravel5" I get the following output:

    Nothing to publish for tag [].

    Did I miss something?

    opened by westwick 8
  • Sending repeats infinitely

    Sending repeats infinitely

    Interesting things happening if you write something like this in your errors Handler class:

    public function report(Exception $e)
        {
            if (app()->environment() == 'production') {
                Slack::send('*' . \Request::url() . '* ' . (string)$e);
            }
    
            return parent::report($e);
        }
    

    it starts repeats infinitely. How can I investigate if it's package or laravel or forge problem?

    opened by justutiz 7
  • Adding author_* and thumb_url features for attachments

    Adding author_* and thumb_url features for attachments

    As per attachments (https://api.slack.com/docs/attachments) you are now able to define Author related fields, and have a Thumbnail URL (close functionality to image_url, except for formatting differences).

    These changes extend the Attachment model to handle author_name, author_link, author_icon and thumbnail_url

    opened by drewbroadley 7
  • added Attachment Actions (buttons) with confirmations

    added Attachment Actions (buttons) with confirmations

    Slack added buttons to attachments: https://slackhq.com/get-more-done-with-message-buttons-5fa5b283a59 https://api.slack.com/docs/message-buttons

    opened by IonBazan 6
  • Can we get a new release?

    Can we get a new release?

    opened by OskarStark 6
  • Guzzle 7 added to required packages

    Guzzle 7 added to required packages

    null

    opened by anujparajuli 1
  • getmaple/slack-laravel Require maknz/slack (Laravel 8)

    getmaple/slack-laravel Require maknz/slack (Laravel 8)

    maknz/slack not working for laravel 8

    Tried alek13/slack package in replacement of maknz/slack but giving same issue

    Please add support for guzzle 7.

    opened by pshnarola 1
  • Php 8.0 support

    Php 8.0 support

    Since this repo is abandoned (see #94), you can just use php-slack/slack fork

    composer remove maknz/slack
    composer require alek13/slack
    
    opened by alek13 0
  • adding block support

    adding block support

    This adds basic block support to the library (https://api.slack.com/block-kit)

    opened by enygma 1
  • Add support for Guzzle 7

    Add support for Guzzle 7

    Would you mind adding support for Guzzle 7 (to composer.json)? I'm attempting to install https://packagist.org/packages/microsoft/microsoft-graph#1.18.0 but it conflicts with the Guzzle version required by maknz/slack 1.7.0.

    opened by nmeirik 1
  • Bulk message sending without consuming  slack rate limits

    Bulk message sending without consuming slack rate limits

    The demo https://github.com/maknz/slack#sending-a-message-to-a-user is showing how to sent a message to one user. Do you consider any bulk message sending without consuming slack rate limits? Something like $client->to(['@regan', '@reganone', '@regantwo'])->send('Yo!');

    opened by ronlinet 0
  • Use postAsync()

    Use postAsync()

    Use GuzzleHttp\Client::postAsync() instead of post() and return the promise so program execution isn't waiting on Slack messages.

    opened by joshuaadickerson 1
  • Nexylan namespace move (used by slack-bundle)

    Nexylan namespace move (used by slack-bundle)

    FYI, we move a copy of this abandoned library under the Nexylan namespace: https://github.com/nexylan/slack

    The 1.x branch is not touched, with same code and release so the migration will be smooth.

    The unreleased change of this library plus other ones are under the v2.0.0.

    The nexylan/slack-bundle now require this package and the v2.0 release support is in progress.

    Ref: https://twitter.com/soullivaneuh/status/953671333279354880

    @maknz I let you update the README to add the reference if you want to.

    Regards.

    opened by soullivaneuh 11
  • (!) Abandoned! See fork php-slack/slack

    (!) Abandoned! See fork php-slack/slack

    Hi, @maknz !

    Thank you for this great package! And for this big job!

    As you say in "Maintance notice" commit: "this package is no longer being actively maintained".

    But its really hard to find this message (I spend much time myself for understand, that this package abandoned).

    It would be better to mark it as "abandoned" on Packagist. And archive repo on GitHub, so it will become read-only.

    I make a fork php-slack/slack & will support this great package for open source community.

    .

    opened by alek13 4
  • (!) Abandoned! See alek13/slack

    (!) Abandoned! See alek13/slack

    #94

    opened by alek13 0
Releases(1.7.0)
  • 1.7.0(Jun 3, 2015)

    You can now specify author_name, author_link and author_icon fields in your attachments.

    Demonstration of author fields

    You can also specify a thumb_url to provide a thumbnail image with the attachment.

    Demonstration of thumb url

    Source code(tar.gz)
    Source code(zip)
  • 1.6.0(Jun 2, 2015)

  • 1.5.0(Mar 16, 2015)

  • 1.4.0(Mar 4, 2015)

  • 1.3.0(Feb 22, 2015)

    You can now typehint for a Maknz\Slack\Client in the constructor of classes created via Laravel's IoC container, rather than being forced to use the Slack facade. Thanks @tzookb for the addition.

    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Feb 13, 2015)

  • 1.1.0(Feb 1, 2015)

    • Markdown support: the ability to disable Markdown parsing of messages, and the ability to specify Markdown parsing for attachment properties.
    • Slack have updated unfurling to differentiate text-based URLs and media-based URLs, which have both been added as settings on the client.

    Upgrading

    Laravel users may wish to re-publish their configuration with php artisan config:publish maknz/slack to get the new fields. Make sure to backup your current config file so you can port your settings across to the new file.

    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Jan 9, 2015)

    • Decoupled messaging from the client to prevent side effects and be a bit more usable
    • Moved from PSR-2 to PSR-4 autoloading
    • Implemented missing link_names and unfurl_links options
    • Tidied up the documentation

    Upgrading from 0.x.x to 1.0.0

    The API has stayed much the same, so as long as you were following examples in the README, there shouldn't be any breaks for basic usage. If you have problems or want aspects of the new layout explained, log an issue.

    If you're using Laravel, you may wish to re-publish the configuration (php artisan config:publish maknz/slack) in order to get the new configuration options. Everything will work without it though.

    Source code(tar.gz)
    Source code(zip)
  • 0.3.0(Jan 6, 2015)

  • 0.2.2(Nov 19, 2014)

  • 0.2.1(Sep 26, 2014)

  • 0.2.0(Sep 8, 2014)

    This release revamps the interface for using the library, and adds functionality for attachments and icons. We now cover all functionality provided by Slack's incoming webhooks.

    The interface has changed from 0.1.x, where you used to type:

    Slack::send('message', '#channel', 'username');
    

    you would now use

    Slack::from('username')->to('#channel')->send('message');
    

    which is more expressive and elegant.

    See the README for detailed examples of the new syntax, and also how to use the new attachment and icon functionality.

    If upgrading from 0.1.x, you will need to change your code if you are customising the channel and username in the call to Slack::send() to use the syntax above, and you will need to re-publish the Laravel configuration using php artisan config:publish maknz/slack.

    The package can now be used (more easily) outside of Laravel. Instructions are in the README.

    Source code(tar.gz)
    Source code(zip)
  • 0.1.1(Jun 14, 2014)

  • 0.1.0(May 5, 2014)

Owner
Regan McEntyre
Regan McEntyre
A htaccess boilerplate for all Magento Community installations. Features focus on speed, SEO and security.

magento-htaccess A htaccess boilerplate for all Magento Community installations. Features focus on speed, SEO and security. The file should be placed

Creare 115 Aug 27, 2021
JsonQ is a simple, elegant PHP package to Query over any type of JSON Data

php-jsonq JsonQ is a simple, elegant PHP package to Query over any type of JSON Data. It'll make your life easier by giving the flavour of an ORM-like

Nahid Bin Azhar 787 Dec 28, 2021
Open Source Smart Meter with focus on privacy - you remain the master of your data.

volkszaehler.org volkszaehler.org is a free smart meter implementation with focus on data privacy. Demo demo.volkszaehler.org Quickstart The easiest w

volkszaehler.org project 159 Dec 29, 2021
PHP-nats publisher - This is a simple package to publish messages to Nats

Nats publisher This is a simple package to publish messages to Nats Installation You can install the package using the Composer package manager. You c

Evert Jan Hakvoort 4 Jan 12, 2022
Make a Laravel app respond to a slash command from Slack

Make a Laravel app respond to a slash command from Slack This package makes it easy to make your Laravel app respond to Slack's Slash commands. Once y

Spatie 228 Jan 8, 2022
Shiki is a beautiful syntax highlighter powered by the same language engine that many code editors use.

Shiki is a beautiful syntax highlighter powered by the same language engine that many code editors use. This package allows you to use Shiki from PHP.

Spatie 186 Jan 14, 2022
A Sublime Text 3 package for highlighting both Sass and SCSS syntax.

Syntax Highlighting for Sass This is a Sublime Text 3 package which purely forced on highlighting both Sass and SCSS syntax as accuracy as possible. P

Peiwen Lu 291 Dec 28, 2021
Xenon\LaravelBDSms is a sms gateway package for sending text message to Bangladeshi mobile numbers using several gateways like sslcommerz, greenweb, dianahost,metronet in Laravel framework

Xenon\LaravelBDSms is a sms gateway package for sending text message to Bangladeshi mobile numbers using several gateways for Laravel. You should use

Ariful Islam 48 Dec 27, 2021
Debug - The Debug component provides tools to ease debugging PHP code.

Debug Component CAUTION: this component is deprecated since Symfony 4.4. Instead, use the ErrorHandler component. The Debug component provides tools t

Symfony 7.3k Jan 11, 2022
A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

A lightweight php class for formatting sql statements. Handles automatic indentation and syntax highlighting.

Doctrine 1.1k Jan 17, 2022
Utility that helps you switch git configurations with ease.

git-profile Utility that helps you switch git configurations with ease Preface It is possible that you have multiple git configurations. For example:

Zeeshan Ahmad 239 Nov 26, 2021
DBML parser for PHP8. It's a PHP parser for DBML syntax.

DBML parser written on PHP8 DBML (database markup language) is a simple, readable DSL language designed to define database structures. This page outli

Pavel Buchnev 22 Jan 10, 2022
CPAY is a sdk that encapsulates the Orange Money api with an intuitive syntax allowing you to integrate the Orange Money payment into your PHP project.

CPAY CHOCO PAY is a sdk that encapsulates the Orange Money api with an intuitive syntax allowing you to integrate the Orange Money payment into your P

faso-dev 1 Dec 23, 2021
This tool check syntax of PHP files faster than serial check with fancier output.

PHP Parallel Lint This application checks syntax of PHP files in parallel. It can output in plain text, colored text, json and checksyntax formats. Ad

PHP Parallel lint 148 Jan 17, 2022
jMQTT is a plugin for Jeedom aiming to connect Jeedom to an MQTT broker to subscribe and publish messages

jMQTT is a plugin for Jeedom aiming to connect Jeedom to an MQTT broker to subscribe and publish messages

null 16 Jan 6, 2022
Private groups to share messages, photos, videos, links with friends and family.

A truly private space for you and your friends What is Zusam ? Zusam (/tsuˈzam/) is a free and open-source way to self-host private forums for groups

Zusam 40 Dec 30, 2021
Spf codemirror - CodeMirror syntax-highlighting for Textpattern

spf_codemirror I’m no longer able to develop this plugin due to ill health. If anyone would like to take over, message me, and I’ll transfer the sourc

Gustavo Reis 6 Mar 16, 2018