Make a Laravel app respond to a slash command from Slack

Overview

Make a Laravel app respond to a slash command from Slack

Latest Version on Packagist MIT Licensed Build Status Quality Score StyleCI Total Downloads

This package makes it easy to make your Laravel app respond to Slack's Slash commands.

Once you've setup your Slash command over at Slack and installed this package into a Laravel app you can create handlers that can handle a slash command. Here's an example of such a handler that will send a response back to slack.

namespace App\SlashCommandHandlers;

use App\SlashCommand\BaseHandler;
use Spatie\SlashCommand\Request;
use Spatie\SlashCommand\Response;

class CatchAll extends BaseHandler
{
    /**
     * If this function returns true, the handle method will get called.
     *
     * @param \Spatie\SlashCommand\Request $request
     *
     * @return bool
     */
    public function canHandle(Request $request): bool
    {
        return true;
    }

    /**
     * Handle the given request. Remember that Slack expects a response
     * within three seconds after the slash command was issued. If
     * there is more time needed, dispatch a job.
     * 
     * @param \Spatie\SlashCommand\Request $request
     * 
     * @return \Spatie\SlashCommand\Response
     */
    public function handle(Request $request): Response
    {
        return $this->respondToSlack("You have typed this text: `{$request->text}`");
    }
}

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-slack-slash-command

This service provider must be installed.

// config/app.php
'providers' => [
    ...
    Spatie\SlashCommand\SlashCommandServiceProvider::class,
];

You can publish the config-file with:

php artisan vendor:publish --provider="Spatie\SlashCommand\SlashCommandServiceProvider"

This is the contents of the published file:

return [

    /*
     * At the integration settings over at Slack you can configure the url to which the 
     * slack commands are posted. Specify the path component of that url here. 
     * 
     * For `http://example.com/slack` you would put `slack` here.
     */
    'url' => 'slack',

    /*
     * The token generated by Slack with which to verify if a incoming slash command request is valid.
     */
    'token' => env('SLACK_SLASH_COMMAND_VERIFICATION_TOKEN'),
    
    /*
     * The signing_secret generated by Slack with which to verify if a incoming slash command request is valid.
     */
    'signing_secret' => env('SLACK_SIGNING_SECRET'),

    /*
     * Verify requests from slack with signing_secret signature
     */
    'verify_with_signing' => false,

    /*
     * The handlers that will process the slash command. We'll call handlers from top to bottom
     * until the first one whose `canHandle` method returns true.
     */
    'handlers' => [
        //add your own handlers here


        //this handler will display instructions on how to use the various commands.
        Spatie\SlashCommand\Handlers\Help::class,

        //this handler will respond with a `Could not handle command` message.
        Spatie\SlashCommand\Handlers\CatchAll::class,
    ],
];

Change verify_with_signing parameter to verify requests from slack by signing_secret:

// config/laravel-slack-slash-command.php
'verify_with_signing' => true

Documentation

You'll find the documentation on https://docs.spatie.be/laravel-slack-slash-command.

Find yourself stuck using the package? Found a bug? Do you have general questions or suggestions for improving the media library? Feel free to create an issue on GitHub, we'll try to address it as soon as possible.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

The message and attachment functionalities were heavily inspired on Regan McEntyre's Slack package.

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Fix error when calling setFields with an array

    Fix error when calling setFields with an array

    fix error "You must pass either an array or an instance of Spatie\SlashCommand\AttachmentField" in setFields method.

    The error is caused by a incompatible signature on addField method

    opened by edbizarro 10
  • Unable to post to app

    Unable to post to app

    After installing the package I had to manually copy the config as the vendor:publish command did not work -

    php artisan vendor:publish --provider="Spatie\SlashCommand\SlashCommandServiceProvider" --tag="config"
    Nothing to publish for tag [config].
    

    I left the config url to slack but when I POST to my domain.app/slack I get route the default NotFoundHttpException in RouteCollection.php line 161:.

    Should I be defining any routes for this or does the config itself handle the routing?

    I have setup ngrok to use my local homestead app in slack but since this does not work I tried with postman to post directly. Still the same result.

    opened by richdynamix 9
  • Allow for attachments to have actions

    Allow for attachments to have actions

    I needed this feature while using the package, and figured I'd extract my custom logic into a contribution back upstream. This feature aims to add the ability to add actions to an attachment, in basically the same fashion as you'd add fields.

    Example:

    $attachment = Attachment::create()
            ->setColor('good')
            ->setText('This is good!')
            ->addAction(
                AttachmentAction::create('good', 'This is a good button!', 'button')
            )
    

    I still need to add the ability to add menu actions, but those are significantly more involved. With that, I've got a couple of questions for the maintainers.

    • Would you like to keep a generic AttachmentAction that has all the abilities of both buttons and menus, or split the two off into a Button and Menu class.
    • Would you like to keep the class name AttachmentAction, or instead change it to (FQCN) \Spatie\SlashCommands\Attachment\Action?
    opened by hskrasek 8
  • Discussion around Help command, SlackSlashCommandException, CatchAll improvments

    Discussion around Help command, SlackSlashCommandException, CatchAll improvments

    Pinging @barryvdh

    First of all thanks for all the work you did on this package.

    I've opened this issue to discuss a few things regarding your PRs before tagging a new version.

    • I've refactored that CatchAll command a bit for readability, could you tests if it works properly in your app?
    • in one of the PR's you've added validate to SignatureHandler. Is that method necessary?
    • We have some extensive docs on this package. If you have the time, I'd appreciate if you could add some info on your changes. But don't feel obligated to do this in any way.
    • On first thought there are now breaking changes, so I would probably tag a new feature version. Have I missed any breaking changes?
    opened by freekmurze 6
  • Dependencies inside Slash Command Jobs

    Dependencies inside Slash Command Jobs

    First of all, been playing with this all day and its saved me hours of development. Big fan already. 👍

    I was looking at ways to change the format of the output as it can become hard to read if there are many items in the response. One way I was thinking was using the Jobs to break up the items into mx 5 responses, giving the output a break in between the lines.

    Following on from your tutorial it mentions that you can inject the dependencies into the handle method of the job i.e. -

    namespace App\SlashCommand\Jobs;
    
    use Spatie\SlashCommand\Jobs\SlashCommandResponseJob;
    
    class SlowApiJobJob extends SlashCommandResponseJob
    {
        // notice here that Laravel will automatically inject dependencies here
        public function handle(MyApi $myApi)
        {
            $response = $myApi->fetchResponse();
    
            $this
               ->respondToSlack("Here is your response: {$response}")
               ->send();
        }
    }
    

    However Laravel fails and complains that Declaration of MyApp\Jobs\LatestPostsJob::handle(MyApp\Contracts\PostRepository $postRepository) must be compatible with Spatie\SlashCommand\Jobs\SlashCommandResponseJob::handle()

    I tried to add this to a construct method but I got the following - Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to MyApp\Jobs\LatestPostsJob::__construct() must be an instance of MyApp\Contracts\PostRepository, none given

    Is there something I am missing?

    bug 
    opened by richdynamix 5
  • [Question] Would you think of maybe implementing

    [Question] Would you think of maybe implementing

    Would you think of maybe implementing the ability to start sending dialog responses to slack? In conjunction with the existing delayed response setup this would be a great addition to the existing library.

    opened by Caroga 4
  • Create Help command

    Create Help command

    According to https://api.slack.com/slash-commands#best_practices it is best to create a help function. This creates that, for the SignatureHandlers. Requires the signature to be public.

    Ideas for improvement:

    • Add a command name/description for each handler, like the Console, to show all commands.
    • Use the Console Descriptor to generate extensive documentation based on the signature parts.
    opened by barryvdh 4
  • Allowed PHP Version ^7.3|^8.0 in composer.json

    Allowed PHP Version ^7.3|^8.0 in composer.json

    Overview

    I changed the required PHP Version in composer.json to allow PHP 8 by setting the value to ^7.3|^8.0. This should allow the package to work in PHP versions >= 7.3 and >= 8.0.

    Note: I am very unsure what branch this should merge to, so I just set it to master 🤷

    Testing Steps

    • [x] composer install using PHP 7.4 (my old env)
    • [x] composer install using PHP 8.0 (my new env)
    • [ ] What other tests are run on a release?
    opened by schwindy 3
  • Error 500 when a second handler is added

    Error 500 when a second handler is added

    I've been following the instructions and I believe I set it all up correctly and my Hodor class works as it should, but when I add a second handler like the Repeat class from examples and register it, the whole program breaks and returns error 500 for both classes.

    I would really appreciate it if you could point me in the right direction please as I can't figure out what I am doing wrong, thanks a lot

    opened by selimirez 3
  • FatalThrowableError: Class 'App\SlashCommandHandlers\Attachment' not found

    FatalThrowableError: Class 'App\SlashCommandHandlers\Attachment' not found

    While following the tutorial, a class not found error is thrown when using the examples that use attachments unless the following is added:

    use Spatie\SlashCommand\Attachment; use Spatie\SlashCommand\AttachmentField;

    Not sure if this the correct behavior or if something is wrong with my set up. If these should be included, it should note this in the tutorial documentation.

    opened by chrisparana 3
  • Error after installation: syntax error, unexpected ':', expecting ';' or '{'

    Error after installation: syntax error, unexpected ':', expecting ';' or '{'

    I've just been following your blog post (https://murze.be/2016/07/building-a-slack-bot-with-laravel/) and for fun and to test it - used your Hodor class example.

    I followed all your installation steps and everything installed fine - however when Slack posts to my Laravel app I get an error that:

    syntax error, unexpected ':', expecting ';' or '{'

    Which is referring to ../vendor/spatie/laravel-slack-slash-command/src/Controller.php:31:

    public function getResponse(): IlluminateResponse
    {
        $this->guardAgainstInvalidRequest();
    
        $handler = $this->determineHandler();
    
        try {
            if ($handler instanceof SignatureHandler) {
                $handler->validate();
            }
            $response = $handler->handle($this->request);
        } catch (SlackSlashCommandException $exception) {
            $response = $exception->getResponse($this->request);
        } catch (Exception $exception) {
            $response = $this->convertToResponse($exception);
        }
    
         return $response->getIlluminateResponse();
    }
    

    Am I missing something?

    opened by jryd 3
Releases(1.11.3)
Owner
Spatie
We create open source, digital products and courses for the developer community
Spatie
A simple PHP package for sending messages to Slack, with a focus on ease of use and elegant syntax.

Slack for PHP A simple PHP package for sending messages to Slack with incoming webhooks, focussed on ease-of-use and elegant syntax. Note: this packag

Regan McEntyre 1.2k Oct 29, 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
A collection of command line scripts for Magento 2 code generation, and a PHP module system for organizing command line scripts.

What is Pestle? Pestle is A PHP Framework for creating and organizing command line programs An experiment in implementing python style module imports

Alan Storm 526 Dec 5, 2022
Get mobile app version and other related data from Google Play Store, Apple App Store and Huawei AppGallery

Mobile App Version Get mobile app version and other related data from Google Play Store, Apple App Store and Huawei AppGallery. Installation Add to co

Omer Salaj 11 Mar 15, 2022
This is an example app demonstrating how to deploy a php app to runway.

Runway Example php App This is an example app demonstrating how to deploy a php app to runway. clone this repo, and navigate into that directory runwa

Planetary Quantum GmbH 0 Aug 9, 2022
HTMX example app that demonstrates how to use HTMX to add javascript interactivity to a serverside rendered PHP app

HTMX examle app This demo app demonstrates how to use HTMX to transform a server side rendered PHP app into a more 'interactive' app with AJAX request

Alexander Morland 3 Dec 11, 2022
salah eddine bendyab 18 Aug 17, 2021
From the team that brought you laravel-random-command comes another gem!

?? Why require one if you can require them all? From the team that brought you laravel-random-command comes another gem! Requiring all our packages se

Spatie 46 Oct 5, 2022
Dispatcher is a Laravel artisan command scheduling tool used to schedule artisan commands within your project so you don't need to touch your crontab when deploying.

Dispatcher Dispatcher allows you to schedule your artisan commands within your Laravel project, eliminating the need to touch the crontab when deployi

Indatus 1.1k Dec 21, 2022
This module adds a command to easily generate "modules" in Laravel and install them using composer.

Laravel Module Create This module adds a command to easily generate "modules" in Laravel and install them using composer Installation Simply install t

null 2 Feb 18, 2022
A Laravel package which helps you to flush sessions with an artisan command.

A simple laravel Package to flush sessions via artisan command. Sometimes we store data on sessions such as cart data or maybe any information regardi

Erfan Ahmed Siam 5 Jun 1, 2023
Laravel package to make it easy to use the gorgeous emojis from EmojiOne

laravel-emojione Laravel package to make it easier working with the gorgeous emojis from EmojiOne. Remember to read the EmojiOne Free License and prov

Christoffer Korvald 140 Nov 29, 2022
Make Laravel and Storyblok work together beautifully.

Use Storyblok’s amazing headless CMS in way that feels familiar to Laravel developers This package allows you to use fantastic Storyblok headless CMS

Richard Le Poidevin 47 Oct 27, 2022
The fastest way to make a powerful JSON:API compatible Rest API with Laravel.

The first fully customizable Laravel JSON:API builder. "CRUD" and protect your resources with 0 (zero) extra line of code. Installation You can instal

BinarCode 394 Dec 23, 2022
The Laravel eCommerce Accept Payment Gateway allows the customer to make use of Accept payment gateway in the Bagisto eCommerce website.

Introduction Bagisto WeAccept add-on allow customers to pay for others using WeAccept payment gateway. Requirements: Bagisto: 1.3.2 Installation with

Bagisto 2 May 31, 2022
A trait to make building your own custom Laravel Model Searches a lot easier.

BrekiTomasson\LaravelModelFinder A simple trait that makes building your own custom Laravel Model Searches a lot easier and safer. It ensures that you

Breki Tomasson 3 Nov 27, 2022
Command bus package for PHP

#Chief Chief is a powerful standalone command bus package for PHP 5.4+. Contents What is a command bus Installation Usage Class-based command handlers

Adam Nicholson 49 Apr 29, 2021
The swiss army knife for Magento developers, sysadmins and devops. The tool provides a huge set of well tested command line commands which save hours of work time. All commands are extendable by a module API.

netz98 magerun CLI tools for Magento 2 The n98 magerun cli tools provides some handy tools to work with Magento from command line. Build Status Latest

netz98 758 Dec 28, 2022
Heal and Feed Command For PocketMine-MP

Description Heal and Feed Command For PocketMine-MP. If you are have a question, please make a issues Features Simple Configuration With UI Can heal a

null 2 Feb 15, 2022