diff --git a/composer.json b/composer.json index 5330b36..a7bed11 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,8 @@ "ext-json":"*", "ext-curl":"*", "skrtdev/async":"~0.7", - "monolog/monolog":"^2.1" + "monolog/monolog":"^2.1", + "benmorel/weakmap-polyfill": "^0.2.0" }, "suggest": { "ext-mbstring":"Needed to use the built-in Telegram Entites Parser", diff --git a/src/NovaGram/HandlersTrait.php b/src/NovaGram/HandlersTrait.php index e4ed776..2b05480 100644 --- a/src/NovaGram/HandlersTrait.php +++ b/src/NovaGram/HandlersTrait.php @@ -3,11 +3,12 @@ namespace skrtdev\NovaGram; use skrtdev\Telegram\{Message, CallbackQuery}; -use Closure; +use Closure, WeakMap; trait HandlersTrait{ protected array $commands = []; + protected WeakMap $statuses_cache; // closure handlers @@ -96,6 +97,34 @@ public function onText(string $pattern, Closure $handler): void } }); } + + public function onUserStatus(string $status, Closure $handler): void + { + $this->statuses_cache ??= new WeakMap(); + $this->onTextMessage(function (Message $message) use ($handler, $status) { + if(!isset($message->from)){ + return; + } + + $user = $message->from; + $real_status = $this->statuses_cache[$user] ??= $user->status(); + if($real_status === $status){ + $handler($message); + } + }); + } + + public function onChatStatus(string $status, Closure $handler): void + { + $this->statuses_cache ??= new WeakMap(); + $this->onTextMessage(function (Message $message) use ($handler, $status) { + $chat = $message->chat; + $real_status = $this->statuses_cache[$chat] ??= $chat->status(); + if($real_status === $status){ + $handler($message); + } + }); + } public function onCommand($commands, Closure $handler, string $description = null): void {