Skip to content

Rules approval for new users #43

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 3 commits into from
Oct 3, 2020
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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@ TG_GITHUB_AUTH_TOKEN='github-token'
# Telegram Payments
TG_PAYMENT_PROVIDER_TOKEN='123:TEST:abc'

# Support group activation expiry and ban times
TG_SUPPORT_GROUP_ACTIVATION_EXPIRE_TIME='15 min'
TG_SUPPORT_GROUP_BAN_TIME='1 day'

# URLs
TG_URL_DONATE='https://...'
TG_URL_PATREON='https://...'
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Exclamation symbols (:exclamation:) note something of importance e.g. breaking c

## [Unreleased]
### Added
- Rules must be agreed to before allowing a user to post in the group.
### Changed
### Deprecated
### Removed
Expand Down
17 changes: 7 additions & 10 deletions commands/CallbackqueryCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Commands\UserCommands\DonateCommand;
use Longman\TelegramBot\Commands\UserCommands\RulesCommand;
use Longman\TelegramBot\Entities\ServerResponse;

/**
Expand Down Expand Up @@ -47,18 +48,14 @@ class CallbackqueryCommand extends SystemCommand
public function execute(): ServerResponse
{
$callback_query = $this->getCallbackQuery();
parse_str($callback_query->getData(), $data);
parse_str($callback_query->getData(), $callback_data);

if ('donate' === $data['command']) {
DonateCommand::createPaymentInvoice(
$callback_query->getFrom()->getId(),
$data['amount'],
$data['currency']
);
if ('donate' === $callback_data['command']) {
return DonateCommand::handleCallbackQuery($callback_query, $callback_data);
}

return $callback_query->answer([
'text' => 'Awesome, an invoice has been sent to you.',
]);
if ('rules' === $callback_data['command']) {
return RulesCommand::handleCallbackQuery($callback_query, $callback_data);
}

return $callback_query->answer();
Expand Down
22 changes: 22 additions & 0 deletions commands/DonateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use JsonException;
use LitEmoji\LitEmoji;
use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\CallbackQuery;
use Longman\TelegramBot\Entities\InlineKeyboard;
use Longman\TelegramBot\Entities\Payments\LabeledPrice;
use Longman\TelegramBot\Entities\Payments\SuccessfulPayment;
Expand Down Expand Up @@ -57,6 +58,27 @@ class DonateCommand extends UserCommand
*/
protected $private_only = true;

/**
* Handle the callback queries regarding the /donate command.
*
* @param CallbackQuery $callback_query
* @param array $callback_data
*
* @return ServerResponse
*/
public static function handleCallbackQuery(CallbackQuery $callback_query, array $callback_data): ServerResponse
{
self::createPaymentInvoice(
$callback_query->getFrom()->getId(),
$callback_data['amount'],
$callback_data['currency']
);

return $callback_query->answer([
'text' => 'Awesome, an invoice has been sent to you.',
]);
}

/**
* @return ServerResponse
* @throws TelegramException
Expand Down
18 changes: 18 additions & 0 deletions commands/GenericmessageCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Longman\TelegramBot\Commands\UserCommands\DonateCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Request;

/**
* Generic message command
Expand Down Expand Up @@ -51,8 +52,12 @@ public function execute(): ServerResponse

// Handle new chat members.
if ($message->getNewChatMembers()) {
$this->deleteThisMessage(); // Service message.
return $this->getTelegram()->executeCommand('newchatmembers');
}
if ($message->getLeftChatMember()) {
$this->deleteThisMessage(); // Service message.
}

// Handle successful payment of donation.
if ($payment = $message->getSuccessfulPayment()) {
Expand All @@ -66,4 +71,17 @@ public function execute(): ServerResponse

return parent::execute();
}

/**
* Delete the current message.
*
* @return ServerResponse
*/
private function deleteThisMessage(): ServerResponse
{
return Request::deleteMessage([
'chat_id' => $this->getMessage()->getChat()->getId(),
'message_id' => $this->getMessage()->getMessageId(),
]);
}
}
101 changes: 90 additions & 11 deletions commands/NewchatmembersCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@

namespace Longman\TelegramBot\Commands\SystemCommands;

use LitEmoji\LitEmoji;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\DB;
use Longman\TelegramBot\Entities\ChatMember;
use Longman\TelegramBot\Entities\ChatPermissions;
use Longman\TelegramBot\Entities\InlineKeyboard;
use Longman\TelegramBot\Entities\Message;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Entities\User;
use Longman\TelegramBot\Exception\TelegramException;
Expand All @@ -39,7 +44,12 @@ class NewchatmembersCommand extends SystemCommand
/**
* @var string
*/
protected $version = '0.4.0';
protected $version = '0.5.0';

/**
* @var Message
*/
private $message;

/**
* @var int
Expand All @@ -62,17 +72,23 @@ class NewchatmembersCommand extends SystemCommand
*/
public function execute(): ServerResponse
{
$message = $this->getMessage();
$this->chat_id = $message->getChat()->getId();
$this->user_id = $message->getFrom()->getId();
$this->message = $this->getMessage();
$this->chat_id = $this->message->getChat()->getId();
$this->user_id = $this->message->getFrom()->getId();

$this->group_name = $message->getChat()->getTitle();
$this->group_name = $this->message->getChat()->getTitle();

['users' => $new_users, 'bots' => $new_bots] = $this->getNewUsersAndBots();

// Kick bots if they weren't added by an admin.
$this->kickDisallowedBots($new_bots);

// Restrict all permissions for new users.
$this->restrictNewUsers($new_users);

// Set the joined date for all new group members.
$this->updateUsersJoinedDate($new_users);

return $this->refreshWelcomeMessage($new_users);
}

Expand All @@ -94,11 +110,20 @@ private function refreshWelcomeMessage(array $new_users): ServerResponse
return '<a href="tg://user?id=' . $new_user->getId() . '">' . filter_var($new_user->getFirstName(), FILTER_SANITIZE_SPECIAL_CHARS) . '</a>';
}, $new_users));

$text = "Welcome {$new_users_text} to the <b>{$this->group_name}</b> group\n";
$text .= 'Please remember that this is <b>NOT</b> the Telegram Support Chat.' . PHP_EOL;
$text .= 'Read the <a href="https://t.me/PHP_Telegram_Support_Bot?start=rules">Rules</a> that apply here.';

$welcome_message_sent = $this->replyToChat($text, ['parse_mode' => 'HTML', 'disable_web_page_preview' => true]);
$text = ":wave: Welcome {$new_users_text} to the <b>{$this->group_name}</b> group\n\n";
$text .= 'Please read and agree to the rules before posting here, thank you!';

$welcome_message_sent = $this->replyToChat(
LitEmoji::encodeUnicode($text),
[
'parse_mode' => 'HTML',
'disable_web_page_preview' => true,
'disable_notification' => true,
'reply_markup' => new InlineKeyboard([
['text' => LitEmoji::encodeUnicode(':orange_book: Read the Rules'), 'url' => 'https://t.me/' . getenv('TG_BOT_USERNAME') . '?start=rules'],
]),
]
);
if (!$welcome_message_sent->isOk()) {
return Request::emptyResponse();
}
Expand Down Expand Up @@ -145,7 +170,7 @@ private function getNewUsersAndBots(): array
$users = [];
$bots = [];

foreach ($this->getMessage()->getNewChatMembers() as $member) {
foreach ($this->message->getNewChatMembers() as $member) {
if ($member->getIsBot()) {
$bots[] = $member;
continue;
Expand Down Expand Up @@ -177,4 +202,58 @@ private function kickDisallowedBots(array $bots): void
]);
}
}

/**
* Write users join date to DB.
*
* @param array $new_users
*
* @return bool
*/
private function updateUsersJoinedDate($new_users): bool
{
$new_users_ids = array_map(static function (User $user) {
return $user->getId();
}, $new_users);

// Update "Joined Date" for new users.
return DB::getPdo()->prepare("
UPDATE " . TB_USER . "
SET `joined_at` = ?
WHERE `id` IN (?)
")->execute([date('Y-m-d H:i:s'), implode(',', $new_users_ids)]);
}

/**
* Restrict permissions in support group for passed users.
*
* @param array $new_users
*
* @return array
*/
private function restrictNewUsers($new_users): array
{
$responses = [];

/** @var User[] $new_users */
foreach ($new_users as $new_user) {
$user_id = $new_user->getId();
$responses[$user_id] = Request::restrictChatMember([
'chat_id' => getenv('TG_SUPPORT_GROUP_ID'),
'user_id' => $user_id,
'permissions' => new ChatPermissions([
'can_send_messages' => false,
'can_send_media_messages' => false,
'can_send_polls' => false,
'can_send_other_messages' => false,
'can_add_web_page_previews' => false,
'can_change_info' => false,
'can_invite_users' => false,
'can_pin_messages' => false,
]),
]);
}

return $responses;
}
}
Loading