Skip to content

Instantly share code, notes, and snippets.

@mpociot
Last active June 22, 2018 18:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpociot/2bc86b74317afea06b030dd047fe629e to your computer and use it in GitHub Desktop.
Save mpociot/2bc86b74317afea06b030dd047fe629e to your computer and use it in GitHub Desktop.
Simple BotMan middleware to limit the bot, so that it only responds to certain allowed users.
<?php
namespace Mpociot\BotMan\Middleware;
use Mpociot\BotMan\Message;
use Mpociot\BotMan\Interfaces\MiddlewareInterface;
class Authorization implements MiddlewareInterface
{
/** @var array */
protected $allowedUsers;
/**
* @param array $allowedUsers list of allowed users
*/
public function __construct($allowedUsers = [])
{
$this->allowedUsers = $allowedUsers;
}
/**
* Create a new Authorization middleware instance.
* @param array $allowedUsers list of allowed users
* @return self
*/
public static function create($allowedUsers = [])
{
return new static($allowedUsers);
}
/**
* Handle / modify the message.
*
* @param Message $message
*/
public function handle(Message &$message)
{
// We don't need to modify the message here
return;
}
/**
* @param Message $message
* @param string $test
* @return bool
*/
public function isMessageMatching(Message $message, $test)
{
return in_array($message->getUser(), $this->allowedUsers);
}
}
<?php
// Usage example
$botman = BotManFactory::create($config);
// Apply middleware
$botman->middleware(Authorization::create([
'user_1',
'user_2'
]));
// give the bot something to listen for.
$botman->hears('hello', function (BotMan $bot, $message) {
$bot->reply('Hello yourself.');
});
@IacopoOrtis
Copy link

IacopoOrtis commented Jun 22, 2018

This does not work in case of fallback. Am I right ?

Ps:
I'm on V2.0
$botman->middleware->matching($authMiddleware);
public function matching(IncomingMessage $message, $pattern, $regexMatched) ;

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