Giter Club home page Giter Club logo

slackbot's Introduction

PHP SlackBot - Create Slack bots in PHP with ease

Build Status codecov

SlackBot is a framework agnostic PHP library that is designed to simplify the task of developing innovative bots for Slack.

Getting Started

  1. Open the Laravel/Symfony/PHP project your new Bot will live in

  2. Install SlackBot with composer

  3. Obtain a Bot Token on Slack

  4. Make your application respond to Slack Event requests

  5. Implement your bot logic

Installation using Composer

Require this package with composer using the following command:

$ composer require mpociot/slackbot

Using SlackBot within a Laravel app

SlackBot comes with a Service Provider to make using this library in your Laravel application as simple as possible.

Go to your config/app.php and add the service provider:

Mpociot\SlackBot\SlackBotServiceProvider::class,

Also add the alias / facade:

'SlackBot' => Mpociot\SlackBot\Facades\SlackBot::class

That's it.

Core Concepts

Bots built with SlackBot have a few key capabilities, which can be used to create clever, conversational applications. These capabilities map to the way real human people talk to each other.

Bots can hear things, say things and reply to what they hear.

With these two building blocks, almost any type of conversation can be created.

Basic Usage

Here's an example of using SlackBot with Slack's Event API.

This sample bot listens for the word "hello" - either in a direct message (a private message inside Slack between the user and the bot) or in a message the bot user is invited to.

$slackbot = new SlackBot();
$slackbot->initialize(<my_slack_bot_token>);

// give the bot something to listen for.
$slackbot->hears('hello', function (SlackBot $bot, $message) {
  $bot->reply('Hello yourself.');
});

Developing with SlackBot

Table of Contents

Receiving Messages

Matching Patterns and Keywords with hears()

SlackBot provides a hears() function, which will listen to specific patterns in public and/or private channels.

Argument Description
pattern A string with a regular expressions to match
callback Callback function that receives a SlackBot object, as well as additional matching regular expression parameters
in Defines where the Bot should listen for this message. Can be either SlackBot::DIRECT_MESSAGE or SlackBot::PUBLIC_CHANNEL
$slackbot->hears('keyword', function(SlackBot $bot, $message) {

  // do something to respond to message
  $bot->reply('You used a keyword!');

});

When using the built in regular expression matching, the results of the expression will be passed to the callback function. For example:

$slackbot->hears('open the {doorType} doors', function(SlackBot $bot, $doorType) {
  if ($doorType === 'pod bay') {
    return $bot->reply('I\'m sorry, Dave. I\'m afraid I can\'t do that.');
  }
  return $bot->reply('Okay');
});

Sending Messages

Bots have to send messages to deliver information and present an interface for their functionality. SlackBot bots can send messages in several different ways, depending on the type and number of messages that will be sent.

Single message replies to incoming commands can be sent using the $bot->reply() function.

Multi-message replies, particularly those that present questions for the end user to respond to, can be sent using the $bot->startConversation() function and the related conversation sub-functions.

Single Message Replies to Incoming Messages

Once a bot has received a message using hears(), a response can be sent using $bot->reply().

Messages sent using $bot->reply() are sent immediately. If multiple messages are sent via $bot->reply() in a single event handler, they will arrive in the client very quickly and may be difficult for the user to process. We recommend using $bot->startConversation() if more than one message needs to be sent.

You may pass either a string, or a Question object to the function.

As a second parameter, you may also send any additional fields supported by Slack:

Slack's chat.postMessage API accepts several additional fields. These fields can be used to adjust the message appearance, add attachments, or even change the displayed user name.

$bot->reply()

Argument Description
reply String or Question Outgoing response
callback Optional Array containing additional parameters

Simple reply example:

$slackbot->hears('keyword', function (SlackBot $bot, $message) {

  // do something to respond to message
  // ...

  $bot->reply("Tell me more!");

});

Slack-specific fields and attachments:

$slackbot->hears('keyword', function (SlackBot $bot, $message) {

    // do something...

    // then respond with a message object
    //
    $bot->reply("A more complex response",[
      'username' => "ReplyBot",
      'icon_emoji' => ":dash:",
    ]);

})

Example usage

// Listen to simple commands
SlackBot::hears('Hello', function (SlackBot $bot) {
    $bot->reply('Hi there!');
});

// Include regular expression matches
SlackBot::hears('Call me {name} the {attribute}', function (SlackBot $bot, $name, $attribute) {
    $bot->reply('Hi '.$name.'! You truly are '.$attribute);
});

// Use conversations
SlackBot::hears('order pizza', function (SlackBot $bot, $matches) {
    $bot->startConversation(new OrderPizzaConversation());
});

// Only listen in direct messages
SlackBot::hears('order pizza', function (SlackBot $bot, $matches) {
    $bot->startConversation(new OrderPizzaConversation());
}, SlackBot::DIRECT_MESSAGE);

// Default reply if nothing else matches
SlackBot::fallback(function(SlackBot $bot) {
    $bot->reply("I don't understand a word you just said.");
});

// Start listening
SlackBot::listen();

Conversation Syntax

use Mpociot\SlackBot\Conversation;

class OrderPizzaConversation extends Conversation
{

    protected $size;
    
    protected $toppings;
    
    public function askSize()
    {
    
        $question = Question::create('Which pizza do you want?')
                    ->addButton(
                        Button::create('Extra Large')->value('xl')
                    )
                    ->addButton(
                        Button::create('Mega Large')->value('xxl')
                    );
                    
        $this->ask($question, function($answer) {
            $this->say('Got you - your pizza needs to be '.$answer->getText());
            $this->size = $answer->getValue();
            
            $this->askTopping();
        });
    }
    
    public function askTopping()
    {
        $this->ask('What toppings do you want?', function($answer) {
            $this->say('Okay, I\'ll put some '.$answer->getText().' on your pizza');
            $this->toppings = $answer->getText();
            
        });
    }
    
    public function run()
    {
        $this->askSize();
    }
}

License

SlackBot is free software distributed under the terms of the MIT license.

slackbot's People

Contributors

mpociot avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.