Interested how Laravel works under the hood? → Check my Laravel Core Adventures Course

BotMan Quick Tip - How to use a default pattern

#chatbot

BotMan is a framework agnostic PHP library for building chatbots. In today's tip I want to show you how to use a default pattern when using an array of callbacks.

Array of callbacks

When you are building a conversation with BotMan, you will often use the ask method. The first argument is the question which can be a string or a Question object. The second argument can be a callback which receives the user's answer. This looks like this:


// Inside a BotMan conversation class

public function askSize()
{
	$this->ask('What pizza size do you want?', function(Answer $answer) {
		$this->size = $answer->getText();
		$this->say('Got it. Your pizza will be '.$answer->getText());
	});
}

But you can also set an array of callbacks as the second argument of the ask method:


// Inside a BotMan conversation class

$this->ask('Shall we proceed? Say YES or NO', [
        [
            'pattern' => 'yes|yep',
            'callback' => function () {
                $this->say('Okay - we\'ll keep going');
            }
        ],
        [
            'pattern' => 'nah|no|nope',
            'callback' => function () {
                $this->say('PANIC!! Stop the engines NOW!');
            }
        ]
    ]);

This is great when you want to provide specific options for handling an answer. If the user agrees do this, if he denies do this etc. But additionally you often need to handle the answer, even if your options are not matched. This is when you need a default pattern.

Default pattern

To use a default pattern we will add another callback to the array.


// Inside a BotMan conversation class
$this->ask('Shall we proceed? Say YES or NO', [
	[
		'pattern' => 'yes|yep',
		'callback' => function () {
			$this->say('Okay - we\'ll keep going');
		}
	],
	[
		'pattern' => 'nah|no|nope',
		'callback' => function () {
			$this->say('PANIC!! Stop the engines NOW!');
		}
	],
	[
		'pattern' => '.*',
		'callback' => function () {
			// do something else
		}
	],
        
]);

Since all patterns are regular expressions, we provide one (.*) that matches every answer. This way this callback will always be called when the other's don't. This makes it our default pattern.

Note: Make sure the default pattern is always the last one of the array.

Conclusion

I have been using BotMan a lot lately and I still encounter new tricks that help be more productive with it. Already got an idea for another tip. Stay tuned :-)

Do you enjoy my posts?

Sign up for my newsletter to receive updates on my latest content.

You will receive monthly updates on my latest articles and products. I do care about the protection of your data. Read my Privacy Policy.