Skip to content

New command parameter to enforce usage in private chats only. #580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
58 changes: 58 additions & 0 deletions src/Commands/Command.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down Expand Up @@ -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();
}

Expand Down Expand Up @@ -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
*
Expand Down Expand Up @@ -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;
}
}