vk/hood/vk/system/api/methods/messages.php

219 lines
7.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
namespace hood\vk\api\methods;
use hood\vk\robots\robot,
hood\vk\robots\group,
hood\vk\robots\user;
/**
* Сообщение
*
* 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
*
* @package hood\vk\api
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*
* @todo Доработать строгий режим отправки: проверку сообщения в беседе (не имеет ID сообщений)
*/
final class messages extends method
{
/**
* $mode Режим отправки
*/
protected int $mode = 1;
/**
* Создать сообщение
*
* Если переданы все параметры, то сразу отправляет
*
* $robot Робот
* $message Текст
* $destination Получатель
* $attachments Вложения
*
* @return self
*/
public function __construct(
protected robot $robot,
protected string $message,
protected int|string|array|null $destination = null,
protected array $attachments = []
) {
// Отправка, если все параметры инициализированы
return $this->send($destination);
}
/**
* Отправить сообщение
*
* $destination Получатель
*
* @see https://vk.com/dev/messages.send
*
* Ответ сервера
*/
public function send(int|string|array $destination): array
{
// Идентификатор сообщения
$random_id = time();
if ($this->mode = 1) {
// Перемножение (по умолчанию)
$random_id *= rand();
}
# Ключ
match (true) {
// Робот-группа
$this->robot instanceof group => $settings['access_token'] = $this->robot->key,
// Робот-пользователь
$this->robot instanceof User => $settings['access_token'] = $this->robot->key
};
// Версия API
$settings['v'] = $this->robot->version;
// Цель отправки
match (true) {
// Отправить по идентификатору
is_int($destination) => $settings['peer_id'] = $destination,
// Массовая отправка по идентификаторам
is_array($destination) => $settings['user_ids'] = $destination,
// Отправить по домену
default => $settings['domain'] = $destination
};
// Сообщение
$settings['message'] = $this->message;
// Идентификатор сообщения
$settings['random_id'] = $random_id;
// Фильтрация вложений
$forward_messages = [];
foreach ($this->attachments as &$attachment) {
//var_dump($attachment);
if (iconv_substr($attachment, 0, 7, "UTF-8") === 'message') {
// Если среди вложений найдено сообщение для пересылки
$forward_messages[] = $attachment;
unset($attachment);
}
}
if (!empty($forward_messages)) {
// Если есть пересылаемые сообщения
$settings['forward_messages'] = implode(',', $forward_messages);
}
//var_dump($attachments);
if (!empty($this->attachments)) {
// Если есть вложения
//echo 'lol';
$settings['attachment'] = implode(',', $this->attachments);
//var_dump($settings['attachment']);
}
// Запрос
$request = $this->robot->browser->request(method: 'POST', uri: 'messages.send', options: ['form_params' => $settings]);
// Очистка
unset($settings);
if ($this->mode >= 2) {
// Если установлен режим 2 (усиленная проверка отправленного сообщения)
if (!empty($request["response"])) {
// Если пришел ID сообщения
// Ключ
match (true) {
// Робот-группа
$this->robot instanceof Group => $settings['access_token'] = $this->robot->key,
// Робот-пользователь
$this->robot instanceof User => $settings['access_token'] = $this->robot->key
};
// Версия API
$settings['v'] = $this->robot->version;
// Запрашиваемые сообщения
$settings['message_ids'] = $request["response"];
// Запрос
if ($this->robot->browser->post(uri: 'https://api.vk.com/method/messages.getById', options: $settings)['response']['count'] === 0) {
// Если сообщения не существует, то повторить отправку
$this->send($destination);
}
} else {
// Что-то придумать :)
}
}
return (array) $request;
}
/**
* Получить информацию о сообщении
*
* Информация о сообщении
*/
public function info(): array
{
# Ключ
match (true) {
// Робот-группа
$this->robot instanceof group => $settings['access_token'] = $this->robot->key,
// Робот-пользователь
$this->robot instanceof User => $settings['access_token'] = $this->robot->key,
};
// Цель отправки
match (true) {
// Отправить по идентификатору
is_int($this->destination) => $settings['peer_id'] = $this->destination,
// Массовая отправка по идентификаторам
is_array($this->destination) => $settings['user_ids'] = $this->destination,
// Отправить по домену
default => $settings['domain'] = $this->destination
};
// Версия API
$settings['v'] = $this->robot->version;
// Сообщение
$settings['message'] = $this->message;
// Режим отправки
$settings['mode'] = $this->mode;
// Фильтрация вложений
$forward_messages = [];
foreach ($this->attachments as &$attachment) {
if (iconv_substr(str: $attachment, offset: 0, length: 7, charset: "UTF-8") === 'message') {
// Если среди вложений найдено сообщение для пересылки
$forward_messages[] = $attachment;
unset($attachment);
}
}
if (!empty($forward_messages)) {
// Если есть пересылаемые сообщения
$settings['forward_messages'] = implode(',', $forward_messages);
}
if (!empty($attachments)) {
// Если есть вложения
$settings['attachment'] = implode(',', $attachments);
}
return $settings;
}
}