Skip to content

Commit 8a9b0d6

Browse files
authored
Merge pull request #580 from noplanman/private_only_commands
New command parameter to enforce usage in private chats only.
2 parents 69ed1e8 + c186a45 commit 8a9b0d6

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Exclamation symbols (:exclamation:) note something of importance e.g. breaking c
1313
- `Telegram::enableAdmin()` now handles duplicate additions properly.
1414
- `Request::getMe()` failure doesn't break cron execution any more.
1515
### Security
16+
- New command parameter `$private_only` to enforce usage in private chats only.
1617

1718
## [0.46.0] - 2017-07-15
1819
### Added

src/Commands/Command.php

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,13 @@ abstract class Command
9797
*/
9898
protected $need_mysql = false;
9999

100+
/*
101+
* Make sure this command only executes on a private chat.
102+
*
103+
* @var bool
104+
*/
105+
protected $private_only = false;
106+
100107
/**
101108
* Command config
102109
*
@@ -145,6 +152,24 @@ public function preExecute()
145152
return $this->executeNoDb();
146153
}
147154

155+
if ($this->isPrivateOnly() && $this->removeNonPrivateMessage()) {
156+
$message = $this->getMessage();
157+
158+
if ($user = $message->getFrom()) {
159+
return Request::sendMessage([
160+
'chat_id' => $user->getId(),
161+
'parse_mode' => 'Markdown',
162+
'text' => sprintf(
163+
"/%s command is only available in a private chat.\n(`%s`)",
164+
$this->getName(),
165+
$message->getText()
166+
),
167+
]);
168+
}
169+
170+
return Request::emptyResponse();
171+
}
172+
148173
return $this->execute();
149174
}
150175

@@ -296,6 +321,16 @@ public function isEnabled()
296321
return $this->enabled;
297322
}
298323

324+
/**
325+
* If this command is intended for private chats only.
326+
*
327+
* @return bool
328+
*/
329+
public function isPrivateOnly()
330+
{
331+
return $this->private_only;
332+
}
333+
299334
/**
300335
* If this is a SystemCommand
301336
*
@@ -325,4 +360,27 @@ public function isUserCommand()
325360
{
326361
return ($this instanceof UserCommand);
327362
}
363+
364+
/**
365+
* Delete the current message if it has been called in a non-private chat.
366+
*
367+
* @return bool
368+
*/
369+
protected function removeNonPrivateMessage()
370+
{
371+
$message = $this->getMessage();
372+
$chat = $message->getChat();
373+
374+
if (!$chat->isPrivateChat()) {
375+
// Delete the falsely called command message.
376+
Request::deleteMessage([
377+
'chat_id' => $chat->getId(),
378+
'message_id' => $message->getMessageId(),
379+
]);
380+
381+
return true;
382+
}
383+
384+
return false;
385+
}
328386
}

0 commit comments

Comments
 (0)