php-slack-bot icon indicating copy to clipboard operation
php-slack-bot copied to clipboard

Fallback command

Open DavBE opened this issue 8 years ago • 0 comments

Hello,

Not an issue but a addition I made. This is a fallback command that will be executed when no command is found. Sort of like a catch-all command, but loaded commands will be executed first. I don't know much how this pull request thing work so here it is, as a patch file for Bot.php :

14d13
<     private $fallBackCommand = null;
38,46d36
<     public function loadFallBackCommand($command) {
<         if ($command instanceof Command\BaseCommand) {
<             $this->fallBackCommand = $command;
<         }
<         else {
<             throw new \Exception('Command must implement PhpSlackBot\Command\BaseCommand');
<         }
<     }
<
205,207d194
<                 }
<                 if (null !== $this->fallBackCommand) {
<                     return $this->fallBackCommand;

Usage :

require 'vendor/autoload.php';
use PhpSlackBot\Bot;

// This special command executes when no command is found
class FallBackCommand extends \PhpSlackBot\Command\BaseCommand {

    protected function configure() {
        // We don't have to configure a command name in this case
    }

    protected function execute($data, $context) {
        if ($data['type'] == 'message') {
            $channel = $this->getChannelNameFromChannelId($data['channel']);
            $username = $this->getUserNameFromUserId($data['user']);
            echo $username.' from '.($channel ? $channel : 'DIRECT MESSAGE').' : '.$data['text'].PHP_EOL;
        }
    }

}

$bot = new Bot();
$bot->setToken('TOKEN'); // Get your token here https://my.slack.com/services/new/bot
$bot->loadFallBackAllCommand(new FallBackCommand());
$bot->run();

Hopefully there will be no bug in this code...

DavBE avatar May 11 '16 19:05 DavBE