2 Commits
3.1.0 ... 3.2.0

Author SHA1 Message Date
Kostya Kalimagin
07a9bb1ef6 Перенос на php 8, Фото сообщение beta, Исправления 2021-01-20 23:00:12 +08:00
Kostya Kalimagin
2baa3f70b6 Перенос на php 8 2021-01-16 12:18:29 +08:00
8 changed files with 312 additions and 487 deletions

View File

@@ -11,13 +11,13 @@ use hood\vk\core,
/**
* LongPoll
*
* @property string $key Ключ к серверу
* @property string $server Сервер
* @property string $ts Идентификатор последнего события
* $key Ключ к серверу
* $server Сервер
* $ts Идентификатор последнего события
*
* @method public function __construct(object $robot) Инициализация
* @method public function get(int $wait = 25) Получить события
* @method public function handle(callable $function, int $wait = 25) Обработать события
* public function __construct(object $robot) Инициализация
* public function get(int $wait = 25) Получить события
* public function handle(callable $function, int $wait = 25) Обработать события
*
* @see https://vk.com/dev/bots_longpoll
* @see https://vk.com/dev/groups.getLongPollServer
@@ -30,19 +30,10 @@ use hood\vk\core,
*/
final class longpoll
{
/**
* Робот
*
* @var string
*/
private robot $robot;
/**
* Ключ к серверу
*
* @see $this->get()
*
* @var string
*/
private string $key;
@@ -50,8 +41,6 @@ final class longpoll
* Сервер (URL)
*
* @see $this->get()
*
* @var string
*/
private string $server;
@@ -61,28 +50,23 @@ final class longpoll
* От него отсчитываются новые, необработанные события
*
* @see $this->get()
*
* @var string
*/
private string $ts;
/**
* Инициализация
*
* @param robot $robot Робот
* $robot Робот
*/
public function __construct(robot $robot)
public function __construct(private robot $robot)
{
// Инициализация робота
if (!isset($robot->id)) {
throw new Exception('Необходимо указать идентификатор ВКонтакте');
} else if (!isset($robot->key)) {
throw new Exception('Необходимо указать ключ для доступа к LongPoll');
} else if (!isset($robot->version)) {
throw new Exception('Необходимо указать версию используемого API ВКонтакте');
}
$this->robot = $robot;
match (true) {
!isset($robot->id) => throw new Exception('Необходимо указать идентификатор ВКонтакте'),
!isset($robot->key) => throw new Exception('Необходимо указать ключ для доступа к LongPoll'),
!isset($robot->version) => throw new Exception('Необходимо указать версию используемого API ВКонтакте'),
default => null
};
// Остановка процессов-дубликатов
if (!file_exists(core::init()->path_temp)) {
@@ -100,10 +84,8 @@ final class longpoll
*
* Полная настройка и активация LongPoll
*
* @param bool $status = true Активация или деактивация
* @param string ...$params Изменяемые параметры
*
* @return array
* $status = true Активация или деактивация
* ...$params Изменяемые параметры
*/
public function post(bool $status = true, string ...$params): array
{
@@ -186,15 +168,13 @@ final class longpoll
}
}
return $this->robot->browser->request('POST', 'groups.setLongPollSettings', $settings);
return $this->robot->browser->request(method: 'POST', uri: 'groups.setLongPollSettings', options: $settings);
}
/**
* Получить события
*
* @param int $wait Время ожидания новых событий (в секундах)
*
* @return array
* $wait Время ожидания новых событий (в секундах)
*/
public function get(int $wait = 25): array
{
@@ -202,8 +182,7 @@ final class longpoll
// Если не инициализирован LongPoll-сервер
// Запрос на получение доступа и данных LongPoll-сервера
echo 'запрос на получение данных лонгполл';
$response = json_decode($this->robot->browser->request('POST', 'groups.getLongPollServer', [
$response = json_decode($this->robot->browser->request(method: 'POST', uri: 'groups.getLongPollServer', options: [
'form_params' => [
'group_id' => $this->robot->id,
'v' => $this->robot->version,
@@ -231,10 +210,8 @@ final class longpoll
*
* Получает и обрабатывает события
*
* @param callable $function Обработка
* @param int $wait Время ожидания новых событий (в секундах)
*
* @return array
* $function Обработка
* $wait Время ожидания новых событий (в секундах)
*/
public function handle(callable $function, int $wait = 25): array
{
@@ -278,7 +255,7 @@ final class longpoll
public function __destruct()
{
if (file_exists($lock = core::init()->path['temp'] . '/' . $this->robot->id . '_' . (int) $this->robot->session . '.longpoll')) {
if (file_exists($lock = core::init()->path_temp . '/' . $this->robot->id . '_' . (int) $this->robot->session . '.longpoll')) {
// Если существует файл-блокировщик, то удалить его
unlink($lock);
}

View File

@@ -11,7 +11,7 @@ use hood\vk\robots\robot,
/**
* Сообщение
*
* @method public static function put(RobotAbstract $from, int $to, string $message, int $mode = 2) Отправить сообщение
* public static function put(RobotAbstract $from, int $to, string $message, int $mode = 2) Отправить сообщение
*
* @see https://vk.com/dev/messages.send
* @see https://vk.com/dev/messages.getById
@@ -24,22 +24,7 @@ use hood\vk\robots\robot,
final class messages extends method
{
/**
* @param string $message Сообщение
*/
protected string $message;
/**
* @param int|string|array|null $destination Получатель
*/
protected $destination;
/**
* @param array $attachments Вложения
*/
protected array $attachments = [];
/**
* @param int $mode Режим отправки
* $mode Режим отправки
*/
protected int $mode = 1;
@@ -48,37 +33,19 @@ final class messages extends method
*
* Если переданы все параметры, то сразу отправляет
*
* @param robot $robot Робот
* @param string $message Текст
* @param int|string|array|null $destination Получатель
* @param string|null ...$attachments Вложения
* $robot Робот
* $message Текст
* $destination Получатель
* $attachments Вложения
*
* @return self
*/
public function __construct(robot $robot, string $message, $destination = null, string ...$attachments)
{
// Инициализация параметров
// Робот
$this->robot = $robot;
// Сообщение
$this->message = $message;
// Получатель
if (isset($destination)) {
$this->destination = $destination;
} else {
return;
}
// Вложения
if (isset($attachments)) {
$this->attachments = $attachments;
} else {
return;
}
public function __construct(
protected robot $robot,
protected string $message,
protected int|string|array|null $destination = null,
protected array $attachments = []
) {
// Отправка, если все параметры инициализированы
return $this->send($destination);
}
@@ -86,13 +53,13 @@ final class messages extends method
/**
* Отправить сообщение
*
* @param int|string|array $destination Получатель
* $destination Получатель
*
* @see https://vk.com/dev/messages.send
*
* @return array Ответ сервера
* Ответ сервера
*/
public function send($destination): array
public function send(int|string|array $destination): array
{
// Идентификатор сообщения
$random_id = time();
@@ -103,28 +70,25 @@ final class messages extends method
}
# Ключ
if ($this->robot instanceof group) {
match (true) {
// Робот-группа
$settings['access_token'] = $this->robot->key;
} else if ($this->robot instanceof User) {
$this->robot instanceof group => $settings['access_token'] = $this->robot->key,
// Робот-пользователь
$settings['access_token'] = $this->robot->key;
}
$this->robot instanceof User => $settings['access_token'] = $this->robot->key
};
// Версия API
$settings['v'] = $this->robot->version;
// Цель отправки
if (is_int($destination)) {
match (true) {
// Отправить по идентификатору
$settings['peer_id'] = $destination;
} else if (is_array($destination)) {
is_int($destination) => $settings['peer_id'] = $destination,
// Массовая отправка по идентификаторам
$settings['user_ids'] = $destination;
} else {
// Отправить по домену
$settings['domain'] = $destination;
}
is_array($destination) => $settings['user_ids'] = $destination,
// Отправить по домену
default => $settings['domain'] = $destination
};
// Сообщение
$settings['message'] = $this->message;
@@ -135,7 +99,8 @@ final class messages extends method
// Фильтрация вложений
$forward_messages = [];
foreach ($this->attachments as &$attachment) {
if (iconv_substr($attachment, 0, 7, "UTF-8") === 'message') {
//var_dump($attachment);
if (iconv_substr($attachment, 0, 7, "UTF-8") === 'message') {
// Если среди вложений найдено сообщение для пересылки
$forward_messages[] = $attachment;
unset($attachment);
@@ -147,14 +112,17 @@ final class messages extends method
$settings['forward_messages'] = implode(',', $forward_messages);
}
if (!empty($attachments)) {
//var_dump($attachments);
if (!empty($this->attachments)) {
// Если есть вложения
$settings['attachment'] = implode(',', $attachments);
//echo 'lol';
$settings['attachment'] = implode(',', $this->attachments);
//var_dump($settings['attachment']);
}
// Запрос
$request = $this->robot->browser->request('POST', 'messages.send', ['form_params' => $settings]);
$request = $this->robot->browser->request(method: 'POST', uri: 'messages.send', options: ['form_params' => $settings]);
// Очистка
unset($settings);
@@ -165,13 +133,12 @@ final class messages extends method
// Если пришел ID сообщения
// Ключ
if ($this->robot instanceof Group) {
match (true) {
// Робот-группа
$settings['access_token'] = $this->robot->key;
} else if ($this->robot instanceof User) {
$this->robot instanceof Group => $settings['access_token'] = $this->robot->key,
// Робот-пользователь
$settings['access_token'] = $this->robot->key;
}
$this->robot instanceof User => $settings['access_token'] = $this->robot->key
};
// Версия API
$settings['v'] = $this->robot->version;
@@ -180,7 +147,7 @@ final class messages extends method
$settings['message_ids'] = $request["response"];
// Запрос
if ($this->robot->browser()->post('https://api.vk.com/method/messages.getById', $settings)['response']['count'] === 0) {
if ($this->robot->browser->post(uri: 'https://api.vk.com/method/messages.getById', options: $settings)['response']['count'] === 0) {
// Если сообщения не существует, то повторить отправку
$this->send($destination);
}
@@ -195,30 +162,27 @@ final class messages extends method
/**
* Получить информацию о сообщении
*
* @return array Информация о сообщении
* Информация о сообщении
*/
public function info(): array
{
# Ключ
if ($this->robot instanceof group) {
match (true) {
// Робот-группа
$settings['access_token'] = $this->robot->key;
} else if ($this->robot instanceof User) {
$this->robot instanceof group => $settings['access_token'] = $this->robot->key,
// Робот-пользователь
$settings['access_token'] = $this->robot->key;
}
$this->robot instanceof User => $settings['access_token'] = $this->robot->key,
};
// Цель отправки
if (is_int($this->destination)) {
match (true) {
// Отправить по идентификатору
$settings['peer_id'] = $this->destination;
} else if (is_array($this->destination)) {
is_int($this->destination) => $settings['peer_id'] = $this->destination,
// Массовая отправка по идентификаторам
$settings['user_ids'] = $this->destination;
} else {
// Отправить по домену
$settings['domain'] = $this->destination;
}
is_array($this->destination) => $settings['user_ids'] = $this->destination,
// Отправить по домену
default => $settings['domain'] = $this->destination
};
// Версия API
$settings['v'] = $this->robot->version;
@@ -232,7 +196,7 @@ final class messages extends method
// Фильтрация вложений
$forward_messages = [];
foreach ($this->attachments as &$attachment) {
if (iconv_substr($attachment, 0, 7, "UTF-8") === 'message') {
if (iconv_substr(str: $attachment, offset: 0, length: 7, charset: "UTF-8") === 'message') {
// Если среди вложений найдено сообщение для пересылки
$forward_messages[] = $attachment;
unset($attachment);

View File

@@ -9,27 +9,20 @@ use hood\vk\robots\robot;
/**
* Абстракция метода API
*
* @method protected static put(string $url, ...$params) Создать
* @method protected static post(string $url, ...$params) Изменить
* @method protected static get(string $url, ...$params) Получить
* @method protected static delete(string $url, ...$params) Удалить
* protected static put(string $url, ...$params) Создать
* protected static post(string $url, ...$params) Изменить
* protected static get(string $url, ...$params) Получить
* protected static delete(string $url, ...$params) Удалить
*
* @package hood\vk\api\methods
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*/
abstract class method
{
/**
* Робот
*
* @param robot $robot Робот
*/
protected robot $robot;
/**
* Создать
*
* @return array Ответ сервера
* Ответ сервера
*/
public static function put(): array
{
@@ -39,7 +32,7 @@ abstract class method
/**
* Изменить
*
* @return array Ответ сервера
* Ответ сервера
*/
public static function post(): array
{
@@ -49,7 +42,7 @@ abstract class method
/**
* Получить
*
* @return array Ответ сервера
* Ответ сервера
*/
public static function get(): array
{
@@ -59,7 +52,7 @@ abstract class method
/**
* Удалить
*
* @return array Ответ сервера
* Ответ сервера
*/
public static function delete(): array
{

View File

@@ -14,7 +14,7 @@ use Exception;
/**
* Фотографии (изображения)
*
* @method public static function put(RobotAbstract $from, int $to, string $message, int $mode = 2) Отправить сообщение
* public static function put(RobotAbstract $from, int $to, string $message, int $mode = 2) Отправить сообщение
*
* @see https://vk.com/dev/photos.getUploadServer
* @see https://vk.com/dev/messages.getById
@@ -24,23 +24,28 @@ use Exception;
*
* @todo Добавить обработку ошибок ($request['errors];)
*/
final class photos
final class photos extends method
{
/**
* $url
*/
protected $url;
/**
* Сохранить
*
* @param robot $robot Робот
* @param int $album_id Альбом
* @param int|null $group_id Группа
* @param string|null $caption Описание
* @param float|null $latitude Географическая широта (-90, 90)
* @param float|null $longitude Географическая долгота (-180, 180)
* $robot Робот
* $album_id Альбом
* $group_id Группа
* $caption Описание
* $latitude Географическая широта (-90, 90)
* $longitude Географическая долгота (-180, 180)
*
* @see https://vk.com/dev/photos.save
*
* @return array|null Ответ сервера
*/
public static function save(robot $robot, int $album_id, array $images, ?string $caption = null, ?int $group_id = null, ?float $latitude = null, ?float $longitude = null): ?array
public static function save(robot $robot, int $album_id, array $images, string $upload_url = null, string|null $caption = null, int|null $group_id = null, float|null $latitude = null, float|null $longitude = null): ?array
{
if (isset($robot->account)) {
// Если инициализирован аккаунт
@@ -61,7 +66,8 @@ final class photos
$settings['group_id'] = $group_id;
}
$upload = self::upload(...$images);
//загрузить
$upload = self::uploadMessage($robot, $upload_url, ...$images);
// Сервер
$settings['server'] = $upload['server'];
@@ -97,29 +103,34 @@ final class photos
* Загрузить
*
* @param Type $var
* @return void
*/
public static function upload(string ...$images)
public static function upload(string ...$images): void
{
if (count($images) > 5) {
throw new Exception('Запрещено отправлять более 5 фотографий');
}
}
/**
* загрузить
*/
public static function uploadMessage(robot $robot, string $upload_url, string ...$images)
{
return $robot->browser->api($upload_url, ...$images);
}
/**
* Получить сервер для загрузки изображений
*
* @param robot $robot Робот
* @param int|null $album_id Альбом
* @param int|group|null $group_id Группа
* $robot Робот
* $album_id Альбом
* $group_id Группа
*
* @see https://vk.com/dev/photos.getUploadServer
*
* @return array|null Ответ сервера
*/
public static function getUploadServer(robot $robot, ?int $album_id = null, $group_id = null): ?array
public static function getUploadServer(robot $robot, int|null $album_id = null, int|group|null $group_id = null): ?array
{
if (isset($robot->account)) {
// Если инициализирован аккаунт
@@ -133,11 +144,10 @@ final class photos
$settings['v'] = $robot->version;
// Альбом
if (isset($album_id)) {
$settings['album_id'] = $album_id;
} else {
$settings['album_id'] = self::getAlbums($robot);
}
match (true) {
isset($album_id) => $settings['album_id'] = $album_id,
default => $settings['album_id'] = self::getAlbums($robot)
};
// Группа
if (isset($group_id)) {
@@ -154,17 +164,17 @@ final class photos
/**
* Получить альбомы
*
* @param robot $robot Робот
* @param array $album_ids = null Идентификаторы альбомов
* @param int $offset = null Смещение для выборки подмножества
* @param int $count = null Количество для возврата
* @param bool $need_system = null Активация возврата системных альбомов
* @param bool $need_covers = null Активация возврата поля с обложкой альбома
* @param bool $photo_sizes = null Активация специального формата размеров фотографий
* $robot Робот
* $album_ids = null Идентификаторы альбомов
* $offset = null Смещение для выборки подмножества
* $count = null Количество для возврата
* $need_system = null Активация возврата системных альбомов
* $need_covers = null Активация возврата поля с обложкой альбома
* $photo_sizes = null Активация специального формата размеров фотографий
*
* @see https://vk.com/dev/photos.getUploadServer
*
* @return array Ответ сервера
* Ответ сервера
*/
public static function getAlbums(robot $robot, array $album_ids = null, int $offset = null, int $count = null, bool $need_system = null, bool $need_covers = null, bool $photo_sizes = null): array
{
@@ -192,8 +202,57 @@ final class photos
}
// Запрос
$request = $robot->browser()->api('photos.getUploadServer', $settings);
$request = $robot->browser->request('POST', 'photos.getUploadServer', $settings)->getBody()->getContents();
return (array) $request;
}
}
/**
* загрузить фото и получить его id
*
* $robot робот
*
* $img фото
*/
public function sex(robot $robot, $img)
{
if (!isset($this->url)) {
// Получить адрес сервера для загрузки фотографии в личное сообщение
$this->url = json_decode($robot->browser->request('POST', 'photos.getMessagesUploadServer', [
'form_params' => [
'group_id' => $robot->id,
'v' => $robot->version,
'access_token' => $robot->key,
'peer_id' => 0
]
])->getBody()->getContents())->response->upload_url;
}
//загрузить
$response = json_decode($robot->browser->request('POST', $this->url, [
'multipart' => [
[
'Content-type' => 'multipart/form-data',
'name' => 'photo',
'contents' => $img
]
]
])->getBody()->getContents());
//сохранить
$response = json_decode($robot->browser->request('POST', 'photos.saveMessagesPhoto', [
'form_params' => [
'group_id' => $robot->id,
'v' => $robot->version,
'access_token' => $robot->key,
'server' => $response->server,
'photo' => $response->photo,
'hash' => $response->hash
]
])->getBody()->getContents());
return 'photo' . $response->response[0]->owner_id . '_' . $response->response[0]->id;
}
}

View File

@@ -12,15 +12,15 @@ use hood\vk\loggers\jasmo,
/**
* Ядро
*
* @property-read int $robots Количество роботов
* @property string $timezone Временная зона (журналирование)
* @property array $path Пути (архитектура проекта)
* $robots Количество роботов
* $timezone Временная зона (журналирование)
* $path Пути (архитектура проекта)
*
* @method protected static function __construct() Инициализация
* @method public static function init() Запуск инициализации или получение инстанции
* @method public public function build() Сборщик
* @method public function set($id, $value) Запись в реестр
* @method public function get($id = null) Чтение из реестра
* protected static function __construct() Инициализация
* public static function init() Запуск инициализации или получение инстанции
* public public function build() Сборщик
* public function set($id, $value) Запись в реестр
* public function get($id = null) Чтение из реестра
*
* @package VK
* @author Арсен Мирзаев <red@hood.su>
@@ -31,15 +31,11 @@ final class core
/**
* Счётчик роботов
*
* @var int
*/
private int $robots = 0;
/**
* Реестр роботов
*
* @var array
*/
private array $registry = [];
@@ -47,38 +43,28 @@ final class core
* Временная зона
*
* Используется в логировании
*
* @var string
*/
private string $timezone;
/**
* Путь до корня проекта
*
* @var string
*/
private string $path_root;
/**
* Путь до папки журналов
*
* @var string
*/
private string $path_logs;
/**
* Путь до временной папки
*
* @var string
*/
private string $path_temp;
/**
* Журналист
*
* @param string $file Файл для журналирования
*
* @return self
* $file Файл для журналирования
*
* @todo Добавить установку иного журналиста по спецификации PSR-3
* @todo Более гибкое журналирование
@@ -94,12 +80,10 @@ final class core
/**
* Записать в реестр
*
* @param int $id
* @param robot $robot
* $id Идентификатор
* $robot робот
*
* @see hood\vk\traits\registry Модификация метода
*
* @return void
*/
public function set(int $id, robot $robot): void
{
@@ -117,14 +101,12 @@ final class core
*
* Если не передать идентификатор, то вернёт все значения
*
* @param int|null $id Идентификатор
* @param int|null $session Сессия
* $id Идентификатор
* $session Сессия
*
* @see hood\vk\traits\registry Модификация метода
*
* @return mixed
*/
public function get(int $id = null, int $session = null)
public function get(int|null $id = null, int|null $session = null): mixed
{
if (isset($id) && array_key_exists($id, $this->registry)) {
// Робот передан и найден
@@ -140,14 +122,12 @@ final class core
/**
* Удалить из реестра
*
* @param int|null $id Идентификатор
* @param int|null $session Сессия
* $id Идентификатор
* $session Сессия
*
* @see hood\vk\traits\registry Модификация метода
*
* @return void
*/
public function delete(int $id = null, int $session = null): void
public function delete(int|null $id = null, int|null $session = null): void
{
if (isset($id)) {
// Робот передан
@@ -188,76 +168,36 @@ final class core
/**
* Записать свойство
*
* @param mixed $name Название
* @param mixed $value Значение
*
* @return void
* $name Название
* $value Значение
*/
public function __set($name, $value): void
public function __set(mixed $name, mixed $value): void
{
if ($name === 'timezone') {
if (!isset($this->timezone)) {
$this->timezone = $value;
} else {
throw new Exception('Запрещено переопределять часовой пояс');
}
} else if ($name === 'path_root') {
if (!isset($this->path_root)) {
$this->path_root = $value;
} else {
throw new Exception('Запрещено переопределять корневой каталог');
}
} else if ($name === 'path_logs') {
if (!isset($this->path_logs)) {
$this->path_logs = $value;
} else {
throw new Exception('Запрещено переопределять каталог журналов');
}
} else if ($name === 'path_temp') {
if (!isset($this->path_temp)) {
$this->path_temp = $value;
} else {
throw new Exception('Запрещено переопределять каталог временных файлов');
}
}
match ($name) {
'timezone' => !isset($this->timezone) ? $this->timezone = $value : throw new Exception('Запрещено переопределять часовой пояс'),
'path_root' => !isset($this->path_root) ? $this->path_root = $value : throw new Exception('Запрещено переопределять корневой каталог'),
'path_logs' => !isset($this->path_logs) ? $this->path_logs = $value : throw new Exception('Запрещено переопределять каталог журналов'),
'path_temp' => !isset($this->path_temp) ? $this->path_temp = $value : throw new Exception('Запрещено переопределять каталог временных файлов')
};
}
/**
* Прочитать свойство
*
* Значение по умолчанию, есле не задано
*
* @param mixed $name Название
*
* @return mixed
* $name Название
*/
public function __get($name)
public function __get(mixed $name): mixed
{
if ($name === 'robots') {
return $this->robots;
} else if ($name === 'timezone') {
if (!isset($this->timezone)) {
// Значение по умолчанию
$this->timezone = 'Europe/Moscow';
}
return $this->timezone;
} else if ($name === 'path_root') {
if (!isset($this->path_root)) {
// Значение по умолчанию
$this->path_root = dirname(__DIR__);
}
return $this->path_root;
} else if ($name === 'path_logs') {
if (!isset($this->path_logs)) {
// Значение по умолчанию
$this->path_logs = $this->path_root . '/logs';
}
return $this->path_logs;
} else if ($name === 'path_temp') {
if (!isset($this->path_temp)) {
// Значение по умолчанию
$this->path_temp = $this->path_root . '/temp';
}
return $this->path_temp;
}
return match ($name) {
'robots' => $this->robots,
'timezone' => !isset($this->timezone) ? $this->timezone = 'Europe/Moscow' : $this->timezone,
'path_root' => !isset($this->path_root) ? $this->path_root = dirname(__DIR__) : $this->path_root,
'path_logs' => !isset($this->path_logs) ? $this->path_logs = $this->path_root . '/logs' : $this->path_logs,
'path_temp' => !isset($this->path_temp) ? $this->path_root . '/temp' : $this->path_temp,
default => null
};
}
/**
@@ -266,10 +206,8 @@ final class core
* Ищет класс описывающий робота,
* создаёт и возвращает его объект
*
* @param string $method Метод
* @param array $params Параметры
*
* @return robot
* $method Метод
* $params Параметры
*/
public function __call(string $method, array $params): robot
{

View File

@@ -13,61 +13,52 @@ use Throwable,
/**
* Робот-группа
*
* @property longpoll $longpoll LongPoll-сессия
* $longpoll LongPoll-сессия
*
* @method public function __set($name, $value) Запись свойства
* @method public function __get($name) Чтение свойства
* @method public function __isset($name) Проверка на инициализированность свойства
* public function __set($name, $value) Запись свойства
* public function __get($name) Чтение свойства
* public function __isset($name) Проверка на инициализированность свойства
*
* @package hood\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* hood\vk\robots
* Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*/
final class group extends robot
{
/**
* @var longpoll $longpoll LongPoll-сессия
* $longpoll LongPoll-сессия
*/
protected longpoll $longpoll;
/**
* Запись свойства
*
* @param string $name Название
* @param mixed $value Значение
* $name Название
* $value Значение
*
* @see hood\vk\robots\robot Наследуемый метод
*
* @return void
*/
public function __set(string $name, $value): void
public function __set(string $name, mixed $value): void
{
try {
parent::__set($name, $value);
} catch (Throwable $e) {
// Если свойство не найдено в родительском методе
if ($name === 'longpoll') {
if ($value instanceof LongPoll) {
$this->longpoll = $value;
} else {
$this->longpoll = new LongPoll($this);
}
}
throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
match ($name) {
'longpoll' => $value instanceof LongPoll ? $this->longpoll = $value : $this->longpoll = new LongPoll($this),
default => throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious())
};
}
}
/**
* Чтение свойства
*
* @param string $name Название
* $name Название
*
* @see hood\vk\robots\robot Наследуемый метод
*
* @return mixed
*/
public function __get(string $name)
public function __get(string $name): mixed
{
try {
return parent::__get($name);
@@ -88,7 +79,7 @@ final class group extends robot
/**
* Проверка на инициализированность свойства
*
* @param string $name Название
* $name Название
*
* @return mixed
*/

View File

@@ -18,26 +18,26 @@ use hood\accounts\vk as account;
/**
* Робот
*
* @property-read int $id Идентификатор
* @property-read int $session Сессия
* @property string $key Ключ
* @property float $version Версия API
* @property account $account Аккаунт
* @property browser $browser Браузер
* @property proxy $proxy Прокси
* @property captcha $captcha Обработчик капчи
* $id Идентификатор
* $session Сессия
* $key Ключ
* $version Версия API
* $account Аккаунт
* $browser Браузер
* $proxy Прокси
* $captcha Обработчик капчи
*
* @property int $messages_mode Режим отправки сообщений
* $messages_mode Режим отправки сообщений
*
* @method public function __construct(int $id = null, float $version = null) Конструктор
* @method public function key(string $key) Инициализация ключа
* @method public function account(account $account) Инициализация аккаунта
* @method public function __set($name, $value) Запись свойства
* @method public function __get($name) Чтение свойства
* @method public function __isset($name) Проверка на инициализированность свойства
* @method public function __call(string $method, array $params) Вызов метода
* @method public static function __callStatic(string $method, array $params) Вызов статического метода
* @method public function __toString() Конвертация в строку
* public function __construct(int $id = null, float $version = null) Конструктор
* public function key(string $key) Инициализация ключа
* public function account(account $account) Инициализация аккаунта
* public function __set($name, $value) Запись свойства
* public function __get($name) Чтение свойства
* public function __isset($name) Проверка на инициализированность свойства
* public function __call(string $method, array $params) Вызов метода
* public static function __callStatic(string $method, array $params) Вызов статического метода
* public function __toString() Конвертация в строку
*
* @package hood\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
@@ -45,42 +45,42 @@ use hood\accounts\vk as account;
abstract class robot
{
/**
* @var int Идентификатор
* Идентификатор
*/
protected int $id;
/**
* @var int Сессия
* Сессия
*/
protected int $session;
/**
* @var string Ключ
* Ключ
*/
protected string $key;
/**
* @var float Версия API
* Версия API
*/
protected float $version = 5.124;
/**
* @var string Аккаунт
* Аккаунт
*/
private account $account;
/**
* @var proxy Прокси
* Прокси
*/
protected proxy $proxy;
/**
* @var captcha Обработчик капчи
* Обработчик капчи
*/
protected captcha $captcha;
/**
* @var int $messages_mode Режим отправки сообщений
* $messages_mode Режим отправки сообщений
*/
protected int $messages_mode = 1;
@@ -88,10 +88,10 @@ abstract class robot
/**
* Конструктор
*
* @param int|null $id Идентификатор
* @param float|null $version Версия API
* $id Идентификатор
* $version Версия API
*/
public function __construct(int $id = null, float $version = null)
public function __construct(int|null $id = null, float|null $version = null)
{
// Инициализация ядра
$core = core::init();
@@ -114,9 +114,7 @@ abstract class robot
/**
* Инициализация ключа
*
* @param string $key Ключ
*
* @return self
* $key Ключ
*/
public function key(string $key): self
{
@@ -132,9 +130,7 @@ abstract class robot
/**
* Инициализация аккаунта
*
* @param account $account Аккаунт
*
* @return self
* $account Аккаунт
*/
public function account(account $account): self
{
@@ -150,9 +146,7 @@ abstract class robot
/**
* Инициализация прокси
*
* @param proxy $proxy Прокси
*
* @return self
* $proxy Прокси
*/
public function proxy(proxy $proxy): self
{
@@ -164,9 +158,7 @@ abstract class robot
/**
* Инициализация обработчика капчи
*
* @param captcha $captcha Обработчик капчи
*
* @return self
* $captcha Обработчик капчи
*/
public function captcha(captcha $captcha): self
{
@@ -178,155 +170,74 @@ abstract class robot
/**
* Записать свойство
*
* @param string $name Название
* @param mixed $value Значение
*
* @return void
* $name Название
* $value Значение
*/
public function __set(string $name, $value): void
public function __set(string $name, mixed $value): void
{
if ($name === 'id') {
if (!isset($this->id)) {
$this->id = (int) $value;
return;
} else {
throw new Exception('Запрещено перезаписывать идентификатор');
}
} else if ($name === 'session') {
if (!isset($this->session)) {
$this->session = (int) $value;
return;
} else {
throw new Exception('Запрещено перезаписывать сессию');
}
} else if ($name === 'key') {
if (!isset($this->key)) {
$this->key = (string) $value;
return;
} else {
throw new Exception('Запрещено перезаписывать ключ');
}
} else if ($name === 'version') {
if (!isset($this->version)) {
$this->version = (float) $value;
return;
} else {
throw new Exception('Запрещено перезаписывать версию API');
}
} else if ($name === 'account') {
if (!isset($this->account) && $value instanceof account) {
$this->account = $value;
return;
} else {
throw new Exception('Запрещено перезаписывать аккаунт');
}
} else if ($name === 'browser') {
if (!isset($this->browser) && $value instanceof browser) {
$this->browser = $value;
return;
} else {
throw new Exception('Запрещено перезаписывать браузер');
}
} else if ($name === 'proxy') {
$this->proxy = $value;
return;
} else if ($name === 'captcha') {
$this->captcha = $value;
return;
} else if ($name === 'messages_new') {
$this->messages_new = (int) $value;
return;
}
// Если свойство не найдено
throw new Exception('Свойство не найдено: ' . $name);
match ($name) {
'id' => !isset($this->id) ? $this->id = (int) $value : throw new Exception('Запрещено перезаписывать идентификатор'),
'session' => !isset($this->session) ? $this->session = (int) $value : throw new Exception('Запрещено перезаписывать сессию'),
'key' => !isset($this->key) ? $this->key = (string) $value : throw new Exception('Запрещено перезаписывать ключ'),
'version' => !isset($this->version) ? $this->version = (float) $value : throw new Exception('Запрещено перезаписывать версию API'),
'account' => !isset($this->account) && $value instanceof account ? $this->account = $value : throw new Exception('Запрещено перезаписывать аккаунт'),
'browser' => !isset($this->browser) && $value instanceof browser ? $this->browser = $value : throw new Exception('Запрещено перезаписывать браузер'),
'proxy' => $this->proxy = $value,
'captcha' => $this->captcha = $value,
'messages_new' => $this->messages_new = (int) $value,
// Если свойство не найдено:
default => throw new Exception('Свойство не найдено: ' . $name)
};
}
/**
* Прочитать свойство
*
* @param string $name Название
* $name Название
*
* @return mixed
*/
public function __get(string $name)
{
if ($name === 'id') {
if (isset($this->id)) {
return $this->id;
} else {
throw new Exception('Идентификатор не инициализирован');
}
} else if ($name === 'session') {
if (isset($this->session)) {
return $this->session;
} else {
throw new Exception('Сессия не инициализирована');
}
} else if ($name === 'key') {
if (isset($this->key)) {
return $this->key;
} else {
throw new Exception('Ключ не инициализирован');
}
} else if ($name === 'account') {
if (isset($this->account)) {
return $this->account;
} else {
throw new Exception('Аккаунт не инициализирован');
}
} else if ($name === 'version') {
if (isset($this->version)) {
return $this->version;
} else {
throw new Exception('Версия не инициализирована');
}
} else if ($name === 'browser') {
return $this->browser ?? $this->browser = new browser([
return match ($name) {
'id' => isset($this->id) ? $this->id : throw new Exception('Идентификатор не инициализирован'),
'session' => isset($this->session) ? $this->session : throw new Exception('Сессия не инициализирована'),
'key' => isset($this->key) ? $this->key : throw new Exception('Ключ не инициализирован'),
'version' => isset($this->version) ? $this->version : throw new Exception('Версия не инициализирована'),
'account' => isset($this->account) ? $this->account : throw new Exception('Аккаунт не инициализирован'),
'browser' => $this->browser ?? $this->browser = new browser([
'base_uri' => 'https://api.vk.com/method/',
'cookies' => true
]);
} else if ($name === 'proxy') {
return $this->proxy;
} else if ($name === 'captcha') {
return $this->captcha;
} else if ($name === 'messages_new') {
return $this->messages_new;
}
throw new Exception('Свойство не найдено: ' . $name);
]),
'proxy' => $this->proxy,
'captcha' => $this->captcha,
'messages_new' => $this->messages_new,
// Если свойство не найдено:
default => throw new Exception('Свойство не найдено: ' . $name)
};
}
/**
* Проверить свойство на инициализированность
*
* @param string $name Название
* $name Название
*
* @return mixed
*/
public function __isset(string $name)
{
if ($name === 'id') {
return isset($this->id);
} else if ($name === 'session') {
return isset($this->session);
} else if ($name === 'key') {
return isset($this->key);
} else if ($name === 'account') {
return isset($this->account);
} else if ($name === 'version') {
return isset($this->version);
} else if ($name === 'browser') {
return isset($this->browser);
} else if ($name === 'proxy') {
return isset($this->proxy);
} else if ($name === 'captcha') {
return isset($this->captcha);
} else if ($name === 'messages_new') {
return isset($this->messages_new);
}
throw new Exception('Свойство не найдено: ' . $name);
return match ($name) {
'id' => isset($this->id),
'session' => isset($this->session),
'key' => isset($this->key),
'account' => isset($this->account),
'version' => isset($this->version),
'browser' => isset($this->browser),
'proxy' => isset($this->proxy),
'captcha' => isset($this->captcha),
'messages_new' => isset($this->messages_new),
default => throw new Exception('Свойство не найдено: ' . $name)
};
}
/**
@@ -335,10 +246,8 @@ abstract class robot
* Ищет класс описывающий метод API ВКонтакте,
* создаёт и возвращает его объект
*
* @param string $method Метод
* @param array $params Параметры
*
* @return method
* $method Метод
* $params Параметры
*/
public function __call(string $method, array $params): method
{
@@ -356,10 +265,8 @@ abstract class robot
* Ищет класс описывающий метод API ВКонтакте,
* создаёт и возвращает его объект
*
* @param string $method Метод
* @param array $params Параметры
*
* @return method
* $method Метод
* $params Параметры
*/
public static function __callStatic(string $method, array $params): method
{
@@ -372,8 +279,6 @@ abstract class robot
/**
* Конвертировать в строку
*
* @return string
*/
public function __toString(): string
{

View File

@@ -27,8 +27,6 @@ trait singleton
/**
* Инициализация
*
* @return self
*/
public static function init(): self
{
@@ -52,7 +50,7 @@ trait singleton
/**
* Заблокирован
*/
private function __sleep()
public function __sleep()
{
throw new Exception('Сериализация запрещена');
}
@@ -60,7 +58,7 @@ trait singleton
/**
* Заблокирован
*/
private function __wakeup()
public function __wakeup()
{
throw new Exception('Десериализация запрещена');
}