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.

Comments
  • 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
  • StyleCI for better Code-Style

    StyleCI for better Code-Style

    @maknz cause of the fallen keyword "code-style" in PR #44 why not using StyleCI? https://styleci.io/ It's free for open source and also used by laravel core - a simple config could look like:

    preset: laravel
    
    risky: false
    
    linting: true
    

    And you can enable auto PR & auto merge & disable CI - this will fix all CS issues in PRs on the fly and no one has to care about CodeStyle.

    todo 
    opened by Gummibeer 4
  • NexySlackBundle documentation and suggestion

    NexySlackBundle documentation and suggestion

    Closes #37.

    As discussed on the related issue, I worked for a Symfony integration on an external bundle.

    The basics are here, the bundle is stable and ready to use, so I think it's time to link it on your documentation. ;-)

    Feel free to comment if you want to review some things before merge. :+1:

    Official announcement: https://twitter.com/soullivaneuh/status/707244694540001280

    opened by soullivaneuh 4
  • How to upload files

    How to upload files

    Hey man,

    So been using your Slack Package for Laravel awhile now and been loving the simplicity of it all.

    I have had a new request though that I am having a hard time figuring out how to deal with. I have been asked to send some alerts as jpg images. I know the slack API has this ability ( https://api.slack.com/methods/files.upload ) but I do not see anything in your code that deals with this. Am I just blind or does it not exist?

    If it does not exist can you point me in the right direction on where to add this to your codebase.

    Cheers

    Ryan Stephens

    opened by thorakmedichi 4
  • 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
  • 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
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
Kiaan PHP is a web application framework with expressive, elegant syntax.

About Kiaan framework Kiaan is a web application framework for PHP. Kiaan is easy, flexible and professional. Documentation You can learn kiaan with t

Kiaan 30 Oct 17, 2022
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 114 Sep 18, 2022
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 176 Jan 4, 2023
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 834 Dec 25, 2022
UMySQL is an extremely simple PHP library for communicating with MySQL databases with ease while keeping overhead to a bare minimum.

Uncomplicated MySQL UMySQL is an extremely simple PHP library for communicating with MySQL databases with ease while keeping overhead to a bare minimu

José Miguel Moreno 4 Oct 24, 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 229 Jan 4, 2023
Make WhatsApp ChatBot and use WhatsApp API to send the WhatsApp messages in php .

Ultramsg.com WhatsApp Bot using WhatsApp API and ultramsg Demo WhatsApp API ChatBot using Ultramsg API with php. Chatbot tasks: The output of the comm

Ultramsg 33 Nov 19, 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 239 Nov 18, 2022
A Slack integration to post GIF replies from replygif.net

Archibald Archibald is a Slack integration written in PHP to post tag-selected GIF replies from replygif.net into your current Slack channel or Direct

Lukas Gächter 11 Nov 1, 2020
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 7 Oct 24, 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 Jun 26, 2022
The ErrorHandler component provides tools to manage errors and ease debugging PHP code

ErrorHandler Component The ErrorHandler component provides tools to manage errors and ease debugging PHP code. Getting Started $ composer require symf

Symfony 2.2k Jan 3, 2023
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 95 Jan 3, 2023
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 8, 2023
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 240 Jul 18, 2022
A complete solution for group projects in organizations that lets you track your work in any scenario. Working in a team is a cumbersome task, ease it using our project management system.

SE-Project-Group24 What is Evolo? Evolo is Dashboard based Project Management System. A complete solution for group projects in organizations that let

Devanshi Savla 2 Oct 7, 2022
✌ An elegant PHP framework for web developers

About Attla framework Attla framework is a PHP framework with expressive, elegant syntax, facilitating common tasks used in many web projects. We buil

Attla 10 Dec 5, 2021
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.4k Dec 29, 2022