Skip to content

Fallback command #5

Description

@davbe

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...

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions