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 * LongPoll
* *
* @property string $key Ключ к серверу * $key Ключ к серверу
* @property string $server Сервер * $server Сервер
* @property string $ts Идентификатор последнего события * $ts Идентификатор последнего события
* *
* @method public function __construct(object $robot) Инициализация * public function __construct(object $robot) Инициализация
* @method public function get(int $wait = 25) Получить события * public function get(int $wait = 25) Получить события
* @method public function handle(callable $function, int $wait = 25) Обработать события * public function handle(callable $function, int $wait = 25) Обработать события
* *
* @see https://vk.com/dev/bots_longpoll * @see https://vk.com/dev/bots_longpoll
* @see https://vk.com/dev/groups.getLongPollServer * @see https://vk.com/dev/groups.getLongPollServer
@@ -30,19 +30,10 @@ use hood\vk\core,
*/ */
final class longpoll final class longpoll
{ {
/**
* Робот
*
* @var string
*/
private robot $robot;
/** /**
* Ключ к серверу * Ключ к серверу
* *
* @see $this->get() * @see $this->get()
*
* @var string
*/ */
private string $key; private string $key;
@@ -50,8 +41,6 @@ final class longpoll
* Сервер (URL) * Сервер (URL)
* *
* @see $this->get() * @see $this->get()
*
* @var string
*/ */
private string $server; private string $server;
@@ -61,28 +50,23 @@ final class longpoll
* От него отсчитываются новые, необработанные события * От него отсчитываются новые, необработанные события
* *
* @see $this->get() * @see $this->get()
*
* @var string
*/ */
private string $ts; private string $ts;
/** /**
* Инициализация * Инициализация
* *
* @param robot $robot Робот * $robot Робот
*/ */
public function __construct(robot $robot) public function __construct(private robot $robot)
{ {
// Инициализация робота // Инициализация робота
if (!isset($robot->id)) { match (true) {
throw new Exception('Необходимо указать идентификатор ВКонтакте'); !isset($robot->id) => throw new Exception('Необходимо указать идентификатор ВКонтакте'),
} else if (!isset($robot->key)) { !isset($robot->key) => throw new Exception('Необходимо указать ключ для доступа к LongPoll'),
throw new Exception('Необходимо указать ключ для доступа к LongPoll'); !isset($robot->version) => throw new Exception('Необходимо указать версию используемого API ВКонтакте'),
} else if (!isset($robot->version)) { default => null
throw new Exception('Необходимо указать версию используемого API ВКонтакте'); };
}
$this->robot = $robot;
// Остановка процессов-дубликатов // Остановка процессов-дубликатов
if (!file_exists(core::init()->path_temp)) { if (!file_exists(core::init()->path_temp)) {
@@ -100,10 +84,8 @@ final class longpoll
* *
* Полная настройка и активация LongPoll * Полная настройка и активация LongPoll
* *
* @param bool $status = true Активация или деактивация * $status = true Активация или деактивация
* @param string ...$params Изменяемые параметры * ...$params Изменяемые параметры
*
* @return array
*/ */
public function post(bool $status = true, string ...$params): array 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 Время ожидания новых событий (в секундах) * $wait Время ожидания новых событий (в секундах)
*
* @return array
*/ */
public function get(int $wait = 25): array public function get(int $wait = 25): array
{ {
@@ -202,8 +182,7 @@ final class longpoll
// Если не инициализирован LongPoll-сервер // Если не инициализирован LongPoll-сервер
// Запрос на получение доступа и данных LongPoll-сервера // Запрос на получение доступа и данных LongPoll-сервера
echo 'запрос на получение данных лонгполл'; $response = json_decode($this->robot->browser->request(method: 'POST', uri: 'groups.getLongPollServer', options: [
$response = json_decode($this->robot->browser->request('POST', 'groups.getLongPollServer', [
'form_params' => [ 'form_params' => [
'group_id' => $this->robot->id, 'group_id' => $this->robot->id,
'v' => $this->robot->version, 'v' => $this->robot->version,
@@ -231,10 +210,8 @@ final class longpoll
* *
* Получает и обрабатывает события * Получает и обрабатывает события
* *
* @param callable $function Обработка * $function Обработка
* @param int $wait Время ожидания новых событий (в секундах) * $wait Время ожидания новых событий (в секундах)
*
* @return array
*/ */
public function handle(callable $function, int $wait = 25): array public function handle(callable $function, int $wait = 25): array
{ {
@@ -278,7 +255,7 @@ final class longpoll
public function __destruct() 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); 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.send
* @see https://vk.com/dev/messages.getById * @see https://vk.com/dev/messages.getById
@@ -24,22 +24,7 @@ use hood\vk\robots\robot,
final class messages extends method final class messages extends method
{ {
/** /**
* @param string $message Сообщение * $mode Режим отправки
*/
protected string $message;
/**
* @param int|string|array|null $destination Получатель
*/
protected $destination;
/**
* @param array $attachments Вложения
*/
protected array $attachments = [];
/**
* @param int $mode Режим отправки
*/ */
protected int $mode = 1; protected int $mode = 1;
@@ -48,37 +33,19 @@ final class messages extends method
* *
* Если переданы все параметры, то сразу отправляет * Если переданы все параметры, то сразу отправляет
* *
* @param robot $robot Робот * $robot Робот
* @param string $message Текст * $message Текст
* @param int|string|array|null $destination Получатель * $destination Получатель
* @param string|null ...$attachments Вложения * $attachments Вложения
* *
* @return self * @return self
*/ */
public function __construct(robot $robot, string $message, $destination = null, string ...$attachments) public function __construct(
{ protected robot $robot,
// Инициализация параметров protected string $message,
protected int|string|array|null $destination = null,
// Робот protected array $attachments = []
$this->robot = $robot; ) {
// Сообщение
$this->message = $message;
// Получатель
if (isset($destination)) {
$this->destination = $destination;
} else {
return;
}
// Вложения
if (isset($attachments)) {
$this->attachments = $attachments;
} else {
return;
}
// Отправка, если все параметры инициализированы // Отправка, если все параметры инициализированы
return $this->send($destination); 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 * @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(); $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; $this->robot instanceof group => $settings['access_token'] = $this->robot->key,
} else if ($this->robot instanceof User) {
// Робот-пользователь // Робот-пользователь
$settings['access_token'] = $this->robot->key; $this->robot instanceof User => $settings['access_token'] = $this->robot->key
} };
// Версия API // Версия API
$settings['v'] = $this->robot->version; $settings['v'] = $this->robot->version;
// Цель отправки // Цель отправки
if (is_int($destination)) { match (true) {
// Отправить по идентификатору // Отправить по идентификатору
$settings['peer_id'] = $destination; is_int($destination) => $settings['peer_id'] = $destination,
} else if (is_array($destination)) {
// Массовая отправка по идентификаторам // Массовая отправка по идентификаторам
$settings['user_ids'] = $destination; is_array($destination) => $settings['user_ids'] = $destination,
} else { // Отправить по домену
// Отправить по домену default => $settings['domain'] = $destination
$settings['domain'] = $destination; };
}
// Сообщение // Сообщение
$settings['message'] = $this->message; $settings['message'] = $this->message;
@@ -135,7 +99,8 @@ final class messages extends method
// Фильтрация вложений // Фильтрация вложений
$forward_messages = []; $forward_messages = [];
foreach ($this->attachments as &$attachment) { 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; $forward_messages[] = $attachment;
unset($attachment); unset($attachment);
@@ -147,14 +112,17 @@ final class messages extends method
$settings['forward_messages'] = implode(',', $forward_messages); $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); unset($settings);
@@ -165,13 +133,12 @@ final class messages extends method
// Если пришел ID сообщения // Если пришел ID сообщения
// Ключ // Ключ
if ($this->robot instanceof Group) { match (true) {
// Робот-группа // Робот-группа
$settings['access_token'] = $this->robot->key; $this->robot instanceof Group => $settings['access_token'] = $this->robot->key,
} else if ($this->robot instanceof User) {
// Робот-пользователь // Робот-пользователь
$settings['access_token'] = $this->robot->key; $this->robot instanceof User => $settings['access_token'] = $this->robot->key
} };
// Версия API // Версия API
$settings['v'] = $this->robot->version; $settings['v'] = $this->robot->version;
@@ -180,7 +147,7 @@ final class messages extends method
$settings['message_ids'] = $request["response"]; $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); $this->send($destination);
} }
@@ -195,30 +162,27 @@ final class messages extends method
/** /**
* Получить информацию о сообщении * Получить информацию о сообщении
* *
* @return array Информация о сообщении * Информация о сообщении
*/ */
public function info(): array public function info(): array
{ {
# Ключ # Ключ
if ($this->robot instanceof group) { match (true) {
// Робот-группа // Робот-группа
$settings['access_token'] = $this->robot->key; $this->robot instanceof group => $settings['access_token'] = $this->robot->key,
} else if ($this->robot instanceof User) {
// Робот-пользователь // Робот-пользователь
$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; is_int($this->destination) => $settings['peer_id'] = $this->destination,
} else if (is_array($this->destination)) {
// Массовая отправка по идентификаторам // Массовая отправка по идентификаторам
$settings['user_ids'] = $this->destination; is_array($this->destination) => $settings['user_ids'] = $this->destination,
} else { // Отправить по домену
// Отправить по домену default => $settings['domain'] = $this->destination
$settings['domain'] = $this->destination; };
}
// Версия API // Версия API
$settings['v'] = $this->robot->version; $settings['v'] = $this->robot->version;
@@ -232,7 +196,7 @@ final class messages extends method
// Фильтрация вложений // Фильтрация вложений
$forward_messages = []; $forward_messages = [];
foreach ($this->attachments as &$attachment) { 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; $forward_messages[] = $attachment;
unset($attachment); unset($attachment);

View File

@@ -9,27 +9,20 @@ use hood\vk\robots\robot;
/** /**
* Абстракция метода API * Абстракция метода API
* *
* @method protected static put(string $url, ...$params) Создать * protected static put(string $url, ...$params) Создать
* @method protected static post(string $url, ...$params) Изменить * protected static post(string $url, ...$params) Изменить
* @method protected static get(string $url, ...$params) Получить * protected static get(string $url, ...$params) Получить
* @method protected static delete(string $url, ...$params) Удалить * protected static delete(string $url, ...$params) Удалить
* *
* @package hood\vk\api\methods * @package hood\vk\api\methods
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su> * @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*/ */
abstract class method abstract class method
{ {
/**
* Робот
*
* @param robot $robot Робот
*/
protected robot $robot;
/** /**
* Создать * Создать
* *
* @return array Ответ сервера * Ответ сервера
*/ */
public static function put(): array public static function put(): array
{ {
@@ -39,7 +32,7 @@ abstract class method
/** /**
* Изменить * Изменить
* *
* @return array Ответ сервера * Ответ сервера
*/ */
public static function post(): array public static function post(): array
{ {
@@ -49,7 +42,7 @@ abstract class method
/** /**
* Получить * Получить
* *
* @return array Ответ сервера * Ответ сервера
*/ */
public static function get(): array public static function get(): array
{ {
@@ -59,7 +52,7 @@ abstract class method
/** /**
* Удалить * Удалить
* *
* @return array Ответ сервера * Ответ сервера
*/ */
public static function delete(): 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/photos.getUploadServer
* @see https://vk.com/dev/messages.getById * @see https://vk.com/dev/messages.getById
@@ -24,23 +24,28 @@ use Exception;
* *
* @todo Добавить обработку ошибок ($request['errors];) * @todo Добавить обработку ошибок ($request['errors];)
*/ */
final class photos final class photos extends method
{ {
/**
* $url
*/
protected $url;
/** /**
* Сохранить * Сохранить
* *
* @param robot $robot Робот * $robot Робот
* @param int $album_id Альбом * $album_id Альбом
* @param int|null $group_id Группа * $group_id Группа
* @param string|null $caption Описание * $caption Описание
* @param float|null $latitude Географическая широта (-90, 90) * $latitude Географическая широта (-90, 90)
* @param float|null $longitude Географическая долгота (-180, 180) * $longitude Географическая долгота (-180, 180)
* *
* @see https://vk.com/dev/photos.save * @see https://vk.com/dev/photos.save
* *
* @return array|null Ответ сервера * @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)) { if (isset($robot->account)) {
// Если инициализирован аккаунт // Если инициализирован аккаунт
@@ -61,7 +66,8 @@ final class photos
$settings['group_id'] = $group_id; $settings['group_id'] = $group_id;
} }
$upload = self::upload(...$images); //загрузить
$upload = self::uploadMessage($robot, $upload_url, ...$images);
// Сервер // Сервер
$settings['server'] = $upload['server']; $settings['server'] = $upload['server'];
@@ -97,29 +103,34 @@ final class photos
* Загрузить * Загрузить
* *
* @param Type $var * @param Type $var
* @return void
*/ */
public static function upload(string ...$images) public static function upload(string ...$images): void
{ {
if (count($images) > 5) { if (count($images) > 5) {
throw new Exception('Запрещено отправлять более 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 Робот * $robot Робот
* @param int|null $album_id Альбом * $album_id Альбом
* @param int|group|null $group_id Группа * $group_id Группа
* *
* @see https://vk.com/dev/photos.getUploadServer * @see https://vk.com/dev/photos.getUploadServer
* *
* @return array|null Ответ сервера * @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)) { if (isset($robot->account)) {
// Если инициализирован аккаунт // Если инициализирован аккаунт
@@ -133,11 +144,10 @@ final class photos
$settings['v'] = $robot->version; $settings['v'] = $robot->version;
// Альбом // Альбом
if (isset($album_id)) { match (true) {
$settings['album_id'] = $album_id; isset($album_id) => $settings['album_id'] = $album_id,
} else { default => $settings['album_id'] = self::getAlbums($robot)
$settings['album_id'] = self::getAlbums($robot); };
}
// Группа // Группа
if (isset($group_id)) { if (isset($group_id)) {
@@ -154,17 +164,17 @@ final class photos
/** /**
* Получить альбомы * Получить альбомы
* *
* @param robot $robot Робот * $robot Робот
* @param array $album_ids = null Идентификаторы альбомов * $album_ids = null Идентификаторы альбомов
* @param int $offset = null Смещение для выборки подмножества * $offset = null Смещение для выборки подмножества
* @param int $count = null Количество для возврата * $count = null Количество для возврата
* @param bool $need_system = null Активация возврата системных альбомов * $need_system = null Активация возврата системных альбомов
* @param bool $need_covers = null Активация возврата поля с обложкой альбома * $need_covers = null Активация возврата поля с обложкой альбома
* @param bool $photo_sizes = null Активация специального формата размеров фотографий * $photo_sizes = null Активация специального формата размеров фотографий
* *
* @see https://vk.com/dev/photos.getUploadServer * @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 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; 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 Количество роботов * $robots Количество роботов
* @property string $timezone Временная зона (журналирование) * $timezone Временная зона (журналирование)
* @property array $path Пути (архитектура проекта) * $path Пути (архитектура проекта)
* *
* @method protected static function __construct() Инициализация * protected static function __construct() Инициализация
* @method public static function init() Запуск инициализации или получение инстанции * public static function init() Запуск инициализации или получение инстанции
* @method public public function build() Сборщик * public public function build() Сборщик
* @method public function set($id, $value) Запись в реестр * public function set($id, $value) Запись в реестр
* @method public function get($id = null) Чтение из реестра * public function get($id = null) Чтение из реестра
* *
* @package VK * @package VK
* @author Арсен Мирзаев <red@hood.su> * @author Арсен Мирзаев <red@hood.su>
@@ -31,15 +31,11 @@ final class core
/** /**
* Счётчик роботов * Счётчик роботов
*
* @var int
*/ */
private int $robots = 0; private int $robots = 0;
/** /**
* Реестр роботов * Реестр роботов
*
* @var array
*/ */
private array $registry = []; private array $registry = [];
@@ -47,38 +43,28 @@ final class core
* Временная зона * Временная зона
* *
* Используется в логировании * Используется в логировании
*
* @var string
*/ */
private string $timezone; private string $timezone;
/** /**
* Путь до корня проекта * Путь до корня проекта
*
* @var string
*/ */
private string $path_root; private string $path_root;
/** /**
* Путь до папки журналов * Путь до папки журналов
*
* @var string
*/ */
private string $path_logs; private string $path_logs;
/** /**
* Путь до временной папки * Путь до временной папки
*
* @var string
*/ */
private string $path_temp; private string $path_temp;
/** /**
* Журналист * Журналист
* *
* @param string $file Файл для журналирования * $file Файл для журналирования
*
* @return self
* *
* @todo Добавить установку иного журналиста по спецификации PSR-3 * @todo Добавить установку иного журналиста по спецификации PSR-3
* @todo Более гибкое журналирование * @todo Более гибкое журналирование
@@ -94,12 +80,10 @@ final class core
/** /**
* Записать в реестр * Записать в реестр
* *
* @param int $id * $id Идентификатор
* @param robot $robot * $robot робот
* *
* @see hood\vk\traits\registry Модификация метода * @see hood\vk\traits\registry Модификация метода
*
* @return void
*/ */
public function set(int $id, robot $robot): void public function set(int $id, robot $robot): void
{ {
@@ -117,14 +101,12 @@ final class core
* *
* Если не передать идентификатор, то вернёт все значения * Если не передать идентификатор, то вернёт все значения
* *
* @param int|null $id Идентификатор * $id Идентификатор
* @param int|null $session Сессия * $session Сессия
* *
* @see hood\vk\traits\registry Модификация метода * @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)) { if (isset($id) && array_key_exists($id, $this->registry)) {
// Робот передан и найден // Робот передан и найден
@@ -140,14 +122,12 @@ final class core
/** /**
* Удалить из реестра * Удалить из реестра
* *
* @param int|null $id Идентификатор * $id Идентификатор
* @param int|null $session Сессия * $session Сессия
* *
* @see hood\vk\traits\registry Модификация метода * @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)) { if (isset($id)) {
// Робот передан // Робот передан
@@ -188,76 +168,36 @@ final class core
/** /**
* Записать свойство * Записать свойство
* *
* @param mixed $name Название * $name Название
* @param mixed $value Значение * $value Значение
*
* @return void
*/ */
public function __set($name, $value): void public function __set(mixed $name, mixed $value): void
{ {
if ($name === 'timezone') { match ($name) {
if (!isset($this->timezone)) { 'timezone' => !isset($this->timezone) ? $this->timezone = $value : throw new Exception('Запрещено переопределять часовой пояс'),
$this->timezone = $value; 'path_root' => !isset($this->path_root) ? $this->path_root = $value : throw new Exception('Запрещено переопределять корневой каталог'),
} else { 'path_logs' => !isset($this->path_logs) ? $this->path_logs = $value : throw new Exception('Запрещено переопределять каталог журналов'),
throw new Exception('Запрещено переопределять часовой пояс'); 'path_temp' => !isset($this->path_temp) ? $this->path_temp = $value : 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('Запрещено переопределять каталог временных файлов');
}
}
} }
/** /**
* Прочитать свойство * Прочитать свойство
*
* Значение по умолчанию, есле не задано
* *
* @param mixed $name Название * $name Название
*
* @return mixed
*/ */
public function __get($name) public function __get(mixed $name): mixed
{ {
if ($name === 'robots') { return match ($name) {
return $this->robots; 'robots' => $this->robots,
} else if ($name === 'timezone') { 'timezone' => !isset($this->timezone) ? $this->timezone = 'Europe/Moscow' : $this->timezone,
if (!isset($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,
$this->timezone = 'Europe/Moscow'; 'path_temp' => !isset($this->path_temp) ? $this->path_root . '/temp' : $this->path_temp,
} default => null
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;
}
} }
/** /**
@@ -266,10 +206,8 @@ final class core
* Ищет класс описывающий робота, * Ищет класс описывающий робота,
* создаёт и возвращает его объект * создаёт и возвращает его объект
* *
* @param string $method Метод * $method Метод
* @param array $params Параметры * $params Параметры
*
* @return robot
*/ */
public function __call(string $method, array $params): robot 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) Запись свойства * public function __set($name, $value) Запись свойства
* @method public function __get($name) Чтение свойства * public function __get($name) Чтение свойства
* @method public function __isset($name) Проверка на инициализированность свойства * public function __isset($name) Проверка на инициализированность свойства
* *
* @package hood\vk\robots * hood\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su> * Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*/ */
final class group extends robot final class group extends robot
{ {
/** /**
* @var longpoll $longpoll LongPoll-сессия * $longpoll LongPoll-сессия
*/ */
protected longpoll $longpoll; protected longpoll $longpoll;
/** /**
* Запись свойства * Запись свойства
* *
* @param string $name Название * $name Название
* @param mixed $value Значение * $value Значение
* *
* @see hood\vk\robots\robot Наследуемый метод * @see hood\vk\robots\robot Наследуемый метод
*
* @return void
*/ */
public function __set(string $name, $value): void public function __set(string $name, mixed $value): void
{ {
try { try {
parent::__set($name, $value); parent::__set($name, $value);
} catch (Throwable $e) { } catch (Throwable $e) {
// Если свойство не найдено в родительском методе // Если свойство не найдено в родительском методе
if ($name === 'longpoll') { match ($name) {
if ($value instanceof LongPoll) { 'longpoll' => $value instanceof LongPoll ? $this->longpoll = $value : $this->longpoll = new LongPoll($this),
$this->longpoll = $value; default => throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious())
} else { };
$this->longpoll = new LongPoll($this);
}
}
throw new Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
} }
} }
/** /**
* Чтение свойства * Чтение свойства
* *
* @param string $name Название * $name Название
* *
* @see hood\vk\robots\robot Наследуемый метод * @see hood\vk\robots\robot Наследуемый метод
*
* @return mixed
*/ */
public function __get(string $name) public function __get(string $name): mixed
{ {
try { try {
return parent::__get($name); return parent::__get($name);
@@ -88,7 +79,7 @@ final class group extends robot
/** /**
* Проверка на инициализированность свойства * Проверка на инициализированность свойства
* *
* @param string $name Название * $name Название
* *
* @return mixed * @return mixed
*/ */

View File

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

View File

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