Files
coruna-lab/app/Telegram/Middleware/GroupAdminOnly.php
T
2026-08-11 02:26:43 +08:00

66 lines
1.9 KiB
PHP

<?php
namespace App\Telegram\Middleware;
use Illuminate\Support\Facades\Log;
use SergiX44\Nutgram\Nutgram;
use SergiX44\Nutgram\Telegram\Properties\ChatMemberStatus;
use SergiX44\Nutgram\Telegram\Properties\ChatType;
/**
* Allow only group/supergroup administrators (or the creator).
* Must run after {@see AuthorizedChat}.
*/
class GroupAdminOnly
{
public function __invoke(Nutgram $bot, callable $next): mixed
{
$chatId = $bot->chatId();
$userId = $bot->userId();
if ($chatId === null || $userId === null) {
return null;
}
$type = $bot->chat()?->type;
$typeValue = $type instanceof ChatType ? $type->value : (string) $type;
if (! in_array($typeValue, [ChatType::GROUP->value, ChatType::SUPERGROUP->value, 'group', 'supergroup'], true)) {
Log::info('telegram GroupAdminOnly: rejected non-group chat', [
'chat_id' => $chatId,
'type' => $typeValue,
]);
return null;
}
try {
$member = $bot->getChatMember($chatId, $userId);
} catch (\Throwable $e) {
Log::warning('telegram GroupAdminOnly: getChatMember failed', [
'chat_id' => $chatId,
'user_id' => $userId,
'error' => $e->getMessage(),
]);
$bot->sendMessage('⛔ Unable to verify admin status.');
return null;
}
$status = $member?->status;
$statusValue = $status instanceof ChatMemberStatus ? $status->value : (string) $status;
$ok = in_array($statusValue, [
ChatMemberStatus::CREATOR->value,
ChatMemberStatus::ADMINISTRATOR->value,
'creator',
'administrator',
], true);
if (! $ok) {
$bot->sendMessage('⛔ Only group admins can use this command.');
return null;
}
return $next($bot);
}
}