From c186a45b7ad839a0c24cbd697cde30935f924511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armando=20L=C3=BCscher?= Date: Fri, 4 Aug 2017 23:18:33 +0200 Subject: [PATCH] New command parameter to enforce usage in private chats only. --- CHANGELOG.md | 1 + src/Commands/Command.php | 58 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4172edf7e..53d2912a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Exclamation symbols (:exclamation:) note something of importance e.g. breaking c - `Telegram::enableAdmin()` now handles duplicate additions properly. - `Request::getMe()` failure doesn't break cron execution any more. ### Security +- New command parameter `$private_only` to enforce usage in private chats only. ## [0.46.0] - 2017-07-15 ### Added diff --git a/src/Commands/Command.php b/src/Commands/Command.php index ea6af4260..fa6bffd0f 100644 --- a/src/Commands/Command.php +++ b/src/Commands/Command.php @@ -97,6 +97,13 @@ abstract class Command */ protected $need_mysql = false; + /* + * Make sure this command only executes on a private chat. + * + * @var bool + */ + protected $private_only = false; + /** * Command config * @@ -145,6 +152,24 @@ public function preExecute() return $this->executeNoDb(); } + if ($this->isPrivateOnly() && $this->removeNonPrivateMessage()) { + $message = $this->getMessage(); + + if ($user = $message->getFrom()) { + return Request::sendMessage([ + 'chat_id' => $user->getId(), + 'parse_mode' => 'Markdown', + 'text' => sprintf( + "/%s command is only available in a private chat.\n(`%s`)", + $this->getName(), + $message->getText() + ), + ]); + } + + return Request::emptyResponse(); + } + return $this->execute(); } @@ -296,6 +321,16 @@ public function isEnabled() return $this->enabled; } + /** + * If this command is intended for private chats only. + * + * @return bool + */ + public function isPrivateOnly() + { + return $this->private_only; + } + /** * If this is a SystemCommand * @@ -325,4 +360,27 @@ public function isUserCommand() { return ($this instanceof UserCommand); } + + /** + * Delete the current message if it has been called in a non-private chat. + * + * @return bool + */ + protected function removeNonPrivateMessage() + { + $message = $this->getMessage(); + $chat = $message->getChat(); + + if (!$chat->isPrivateChat()) { + // Delete the falsely called command message. + Request::deleteMessage([ + 'chat_id' => $chat->getId(), + 'message_id' => $message->getMessageId(), + ]); + + return true; + } + + return false; + } }