Доработано под новый класс api, исправленны ошибки.

This commit is contained in:
tarashyanskiy 2021-02-25 11:17:24 +08:00
parent e535c7cbce
commit 701082644e
10 changed files with 283 additions and 394 deletions

187
composer.lock generated
View File

@ -84,10 +84,6 @@
"rest",
"web service"
],
"support": {
"issues": "https://github.com/guzzle/guzzle/issues",
"source": "https://github.com/guzzle/guzzle/tree/7.2.0"
},
"funding": [
{
"url": "https://github.com/GrahamCampbell",
@ -157,10 +153,6 @@
"keywords": [
"promise"
],
"support": {
"issues": "https://github.com/guzzle/promises/issues",
"source": "https://github.com/guzzle/promises/tree/1.4.0"
},
"time": "2020-09-30T07:37:28+00:00"
},
{
@ -232,10 +224,6 @@
"uri",
"url"
],
"support": {
"issues": "https://github.com/guzzle/psr7/issues",
"source": "https://github.com/guzzle/psr7/tree/1.7.0"
},
"time": "2020-09-30T07:37:11+00:00"
},
{
@ -280,11 +268,6 @@
"hood",
"vk"
],
"support": {
"chat": "https://vk.me/darkweb228",
"docs": "https://git.hood.su/hood/accounts/manual",
"issues": "https://git.hood.su/hood/accounts/issues"
},
"funding": [
{
"url": "https://git.hood.su/hood/accounts/thanks",
@ -339,10 +322,6 @@
"exception handler",
"middleware"
],
"support": {
"issues": "https://github.com/jasny/error-handler/issues",
"source": "https://github.com/jasny/error-handler"
},
"abandoned": true,
"time": "2017-01-25T01:27:18+00:00"
},
@ -416,10 +395,6 @@
"logging",
"psr-3"
],
"support": {
"issues": "https://github.com/Seldaek/monolog/issues",
"source": "https://github.com/Seldaek/monolog/tree/1.26.0"
},
"funding": [
{
"url": "https://github.com/Seldaek",
@ -479,9 +454,6 @@
"psr",
"psr-18"
],
"support": {
"source": "https://github.com/php-fig/http-client/tree/master"
},
"time": "2020-06-29T06:28:15+00:00"
},
{
@ -532,9 +504,6 @@
"request",
"response"
],
"support": {
"source": "https://github.com/php-fig/http-message/tree/master"
},
"time": "2016-08-06T14:39:51+00:00"
},
{
@ -582,9 +551,6 @@
"psr",
"psr-3"
],
"support": {
"source": "https://github.com/php-fig/log/tree/1.1.3"
},
"time": "2020-03-23T09:12:05+00:00"
},
{
@ -625,10 +591,6 @@
}
],
"description": "A polyfill for getallheaders.",
"support": {
"issues": "https://github.com/ralouphie/getallheaders/issues",
"source": "https://github.com/ralouphie/getallheaders/tree/develop"
},
"time": "2019-03-08T08:55:37+00:00"
}
],
@ -682,10 +644,6 @@
"constructor",
"instantiate"
],
"support": {
"issues": "https://github.com/doctrine/instantiator/issues",
"source": "https://github.com/doctrine/instantiator/tree/1.4.0"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
@ -748,10 +706,6 @@
"object",
"object graph"
],
"support": {
"issues": "https://github.com/myclabs/DeepCopy/issues",
"source": "https://github.com/myclabs/DeepCopy/tree/1.10.2"
},
"funding": [
{
"url": "https://tidelift.com/funding/github/packagist/myclabs/deep-copy",
@ -810,10 +764,6 @@
"parser",
"php"
],
"support": {
"issues": "https://github.com/nikic/PHP-Parser/issues",
"source": "https://github.com/nikic/PHP-Parser/tree/v4.10.4"
},
"time": "2020-12-20T10:01:03+00:00"
},
{
@ -870,10 +820,6 @@
}
],
"description": "Component for reading phar.io manifest information from a PHP Archive (PHAR)",
"support": {
"issues": "https://github.com/phar-io/manifest/issues",
"source": "https://github.com/phar-io/manifest/tree/master"
},
"time": "2020-06-27T14:33:11+00:00"
},
{
@ -921,10 +867,6 @@
}
],
"description": "Library for handling version information and constraints",
"support": {
"issues": "https://github.com/phar-io/version/issues",
"source": "https://github.com/phar-io/version/tree/3.0.4"
},
"time": "2020-12-13T23:18:30+00:00"
},
{
@ -974,10 +916,6 @@
"reflection",
"static analysis"
],
"support": {
"issues": "https://github.com/phpDocumentor/ReflectionCommon/issues",
"source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x"
},
"time": "2020-06-27T09:03:43+00:00"
},
{
@ -1030,10 +968,6 @@
}
],
"description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
"support": {
"issues": "https://github.com/phpDocumentor/ReflectionDocBlock/issues",
"source": "https://github.com/phpDocumentor/ReflectionDocBlock/tree/master"
},
"time": "2020-09-03T19:13:55+00:00"
},
{
@ -1079,10 +1013,6 @@
}
],
"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
"support": {
"issues": "https://github.com/phpDocumentor/TypeResolver/issues",
"source": "https://github.com/phpDocumentor/TypeResolver/tree/1.4.0"
},
"time": "2020-09-17T18:55:26+00:00"
},
{
@ -1146,10 +1076,6 @@
"spy",
"stub"
],
"support": {
"issues": "https://github.com/phpspec/prophecy/issues",
"source": "https://github.com/phpspec/prophecy/tree/1.12.2"
},
"time": "2020-12-19T10:15:11+00:00"
},
{
@ -1217,10 +1143,6 @@
"testing",
"xunit"
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.5"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1277,10 +1199,6 @@
"filesystem",
"iterator"
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-file-iterator/issues",
"source": "https://github.com/sebastianbergmann/php-file-iterator/tree/3.0.5"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1340,10 +1258,6 @@
"keywords": [
"process"
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-invoker/issues",
"source": "https://github.com/sebastianbergmann/php-invoker/tree/3.1.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1399,10 +1313,6 @@
"keywords": [
"template"
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-text-template/issues",
"source": "https://github.com/sebastianbergmann/php-text-template/tree/2.0.4"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1458,10 +1368,6 @@
"keywords": [
"timer"
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-timer/issues",
"source": "https://github.com/sebastianbergmann/php-timer/tree/5.0.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1472,16 +1378,16 @@
},
{
"name": "phpunit/phpunit",
"version": "9.5.1",
"version": "9.5.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "e7bdf4085de85a825f4424eae52c99a1cec2f360"
"reference": "f661659747f2f87f9e72095bb207bceb0f151cb4"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/e7bdf4085de85a825f4424eae52c99a1cec2f360",
"reference": "e7bdf4085de85a825f4424eae52c99a1cec2f360",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/f661659747f2f87f9e72095bb207bceb0f151cb4",
"reference": "f661659747f2f87f9e72095bb207bceb0f151cb4",
"shasum": ""
},
"require": {
@ -1557,10 +1463,6 @@
"testing",
"xunit"
],
"support": {
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
"source": "https://github.com/sebastianbergmann/phpunit/tree/9.5.1"
},
"funding": [
{
"url": "https://phpunit.de/donate.html",
@ -1571,7 +1473,7 @@
"type": "github"
}
],
"time": "2021-01-17T07:42:25+00:00"
"time": "2021-02-02T14:45:58+00:00"
},
{
"name": "sebastian/cli-parser",
@ -1617,10 +1519,6 @@
],
"description": "Library for parsing CLI options",
"homepage": "https://github.com/sebastianbergmann/cli-parser",
"support": {
"issues": "https://github.com/sebastianbergmann/cli-parser/issues",
"source": "https://github.com/sebastianbergmann/cli-parser/tree/1.0.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1673,10 +1571,6 @@
],
"description": "Collection of value objects that represent the PHP code units",
"homepage": "https://github.com/sebastianbergmann/code-unit",
"support": {
"issues": "https://github.com/sebastianbergmann/code-unit/issues",
"source": "https://github.com/sebastianbergmann/code-unit/tree/1.0.8"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1728,10 +1622,6 @@
],
"description": "Looks up which function or method a line of code belongs to",
"homepage": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/",
"support": {
"issues": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/issues",
"source": "https://github.com/sebastianbergmann/code-unit-reverse-lookup/tree/2.0.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1802,10 +1692,6 @@
"compare",
"equality"
],
"support": {
"issues": "https://github.com/sebastianbergmann/comparator/issues",
"source": "https://github.com/sebastianbergmann/comparator/tree/4.0.6"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1859,10 +1745,6 @@
],
"description": "Library for calculating the complexity of PHP code units",
"homepage": "https://github.com/sebastianbergmann/complexity",
"support": {
"issues": "https://github.com/sebastianbergmann/complexity/issues",
"source": "https://github.com/sebastianbergmann/complexity/tree/2.0.2"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1925,10 +1807,6 @@
"unidiff",
"unified diff"
],
"support": {
"issues": "https://github.com/sebastianbergmann/diff/issues",
"source": "https://github.com/sebastianbergmann/diff/tree/4.0.4"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -1988,10 +1866,6 @@
"environment",
"hhvm"
],
"support": {
"issues": "https://github.com/sebastianbergmann/environment/issues",
"source": "https://github.com/sebastianbergmann/environment/tree/5.1.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2065,10 +1939,6 @@
"export",
"exporter"
],
"support": {
"issues": "https://github.com/sebastianbergmann/exporter/issues",
"source": "https://github.com/sebastianbergmann/exporter/tree/4.0.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2129,10 +1999,6 @@
"keywords": [
"global state"
],
"support": {
"issues": "https://github.com/sebastianbergmann/global-state/issues",
"source": "https://github.com/sebastianbergmann/global-state/tree/5.0.2"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2186,10 +2052,6 @@
],
"description": "Library for counting the lines of code in PHP source code",
"homepage": "https://github.com/sebastianbergmann/lines-of-code",
"support": {
"issues": "https://github.com/sebastianbergmann/lines-of-code/issues",
"source": "https://github.com/sebastianbergmann/lines-of-code/tree/1.0.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2243,10 +2105,6 @@
],
"description": "Traverses array structures and object graphs to enumerate all referenced objects",
"homepage": "https://github.com/sebastianbergmann/object-enumerator/",
"support": {
"issues": "https://github.com/sebastianbergmann/object-enumerator/issues",
"source": "https://github.com/sebastianbergmann/object-enumerator/tree/4.0.4"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2298,10 +2156,6 @@
],
"description": "Allows reflection of object attributes, including inherited and non-public ones",
"homepage": "https://github.com/sebastianbergmann/object-reflector/",
"support": {
"issues": "https://github.com/sebastianbergmann/object-reflector/issues",
"source": "https://github.com/sebastianbergmann/object-reflector/tree/2.0.4"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2361,10 +2215,6 @@
],
"description": "Provides functionality to recursively process PHP variables",
"homepage": "http://www.github.com/sebastianbergmann/recursion-context",
"support": {
"issues": "https://github.com/sebastianbergmann/recursion-context/issues",
"source": "https://github.com/sebastianbergmann/recursion-context/tree/4.0.4"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2416,10 +2266,6 @@
],
"description": "Provides a list of PHP built-in functions that operate on resources",
"homepage": "https://www.github.com/sebastianbergmann/resource-operations",
"support": {
"issues": "https://github.com/sebastianbergmann/resource-operations/issues",
"source": "https://github.com/sebastianbergmann/resource-operations/tree/3.0.3"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2472,10 +2318,6 @@
],
"description": "Collection of value objects that represent the types of the PHP type system",
"homepage": "https://github.com/sebastianbergmann/type",
"support": {
"issues": "https://github.com/sebastianbergmann/type/issues",
"source": "https://github.com/sebastianbergmann/type/tree/2.3.1"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2525,10 +2367,6 @@
],
"description": "Library that helps with managing the version number of Git-hosted PHP projects",
"homepage": "https://github.com/sebastianbergmann/version",
"support": {
"issues": "https://github.com/sebastianbergmann/version/issues",
"source": "https://github.com/sebastianbergmann/version/tree/3.0.2"
},
"funding": [
{
"url": "https://github.com/sebastianbergmann",
@ -2539,7 +2377,7 @@
},
{
"name": "symfony/polyfill-ctype",
"version": "v1.22.0",
"version": "v1.22.1",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git",
@ -2597,9 +2435,6 @@
"polyfill",
"portable"
],
"support": {
"source": "https://github.com/symfony/polyfill-ctype/tree/v1.22.0"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
@ -2654,10 +2489,6 @@
}
],
"description": "A small library for converting tokenized PHP source code into XML and potentially other formats",
"support": {
"issues": "https://github.com/theseer/tokenizer/issues",
"source": "https://github.com/theseer/tokenizer/tree/master"
},
"funding": [
{
"url": "https://github.com/theseer",
@ -2713,10 +2544,6 @@
"check",
"validate"
],
"support": {
"issues": "https://github.com/webmozarts/assert/issues",
"source": "https://github.com/webmozarts/assert/tree/1.9.1"
},
"time": "2020-07-08T17:02:28+00:00"
}
],
@ -2731,5 +2558,5 @@
"php": "~8.0"
},
"platform-dev": [],
"plugin-api-version": "2.0.0"
"plugin-api-version": "1.1.0"
}

View File

@ -16,6 +16,7 @@ use GuzzleHttp\Promise\Each;
*
* @var robot $robot Робот
* @var array $settings Настройки
* @var float $version Версия API
*/
class api implements ArrayAccess
{
@ -24,7 +25,8 @@ class api implements ArrayAccess
*/
public function __construct(
protected robot $robot,
protected array $settings = []
protected array $settings = [],
protected float $version = 5.124
) {
if (empty($settings)) {
// Настройки не получены
@ -81,7 +83,7 @@ class api implements ArrayAccess
$this->settings['access_token'] = $this->robot->key;
// Версия API
$this->settings['v'] = $this->robot->version;
$this->settings['v'] = $this->version;
}
/**
@ -184,9 +186,8 @@ class api implements ArrayAccess
{
if (isset($settings)) {
unset($this->settings[$offset]);
} else {
} else {
throw new Exception('Настройки не инициализированы');
}
}
}
}

View File

@ -11,13 +11,13 @@ use hood\vk\core,
/**
* LongPoll
*
* $key Ключ к серверу
* $server Сервер
* $ts Идентификатор последнего события
* @property string $key Ключ к серверу
* @property string $server Сервер
* @property string $ts Идентификатор последнего события
*
* public function __construct(object $robot) Инициализация
* public function get(int $wait = 25) Получить события
* public function handle(callable $function, int $wait = 25) Обработать события
* @method public function __construct(object $robot) Инициализация
* @method public function get(int $wait = 25) Получить события
* @method public function handle(callable $function, int $wait = 25) Обработать события
*
* @see https://vk.com/dev/bots_longpoll
* @see https://vk.com/dev/groups.getLongPollServer
@ -34,6 +34,8 @@ final class longpoll
* Ключ к серверу
*
* @see $this->get()
*
* @var string
*/
private string $key;
@ -41,6 +43,8 @@ final class longpoll
* Сервер (URL)
*
* @see $this->get()
*
* @var string
*/
private string $server;
@ -50,13 +54,15 @@ final class longpoll
* От него отсчитываются новые, необработанные события
*
* @see $this->get()
*
* @var string
*/
private string $ts;
/**
* Инициализация
*
* $robot Робот
* @param robot $robot Робот
*/
public function __construct(private robot $robot)
{
@ -84,24 +90,27 @@ final class longpoll
*
* Полная настройка и активация LongPoll
*
* $status = true Активация или деактивация
* ...$params Изменяемые параметры
* @param bool $status = true Активация или деактивация
* @param string ...$params Изменяемые параметры
*
* @return array
*/
public function post(bool $status = true, string ...$params): array
{
// Инициализация настроек
$settings = [
'group_id' => $this->robot->id,
'access_token' => $this->robot->key,
'v' => $this->robot->version,
'api_version' => $this->robot->version
];
// Реиницилазиция
$this->robot->api->reinit();
if ($status === true && !array_key_exists('enabled', $settings)) {
// Инициализация настроек
$this->robot->api['group_id'] = $this->robot->id;
$this->robot->api['access_token'] = $this->robot->key;
$this->robot->api['v'] = $this->robot->version;
$this->robot->api['api_version'] = $this->robot->version;
if ($status === true && !array_key_exists('enabled', $this->robot->api['settings'])) {
// Если запущена активация и не был передан параметр статуса LongPoll
// Установка параметра активации LongPoll
$settings['enabled'] = 1;
$this->robot->api['enabled'] = 1;
}
// Установка переданных параметров
@ -118,77 +127,80 @@ final class longpoll
// Если параметр не указывает на установку всех значений
// Установка значения
$settings[$param] = $status;
$this->robot->api[$param] = $status;
} else {
// Иначе установить все значения
// Если передан параметр: установка ВСЕХ значений
$settings['message_new'] = $status;
$settings['message_reply'] = $status;
$settings['message_allow'] = $status;
$settings['message_deny'] = $status;
$settings['message_edit'] = $status;
$settings['message_typing_state'] = $status;
$settings['photo_new'] = $status;
$settings['audio_new'] = $status;
$settings['video_new'] = $status;
$settings['wall_reply_new'] = $status;
$settings['wall_reply_edit'] = $status;
$settings['wall_reply_delete'] = $status;
$settings['wall_reply_restore'] = $status;
$settings['wall_post_new'] = $status;
$settings['wall_repost'] = $status;
$settings['board_post_new'] = $status;
$settings['board_post_edit'] = $status;
$settings['board_post_restore'] = $status;
$settings['board_post_delete'] = $status;
$settings['photo_comment_new'] = $status;
$settings['photo_comment_edit'] = $status;
$settings['photo_comment_delete'] = $status;
$settings['photo_comment_restore'] = $status;
$settings['video_comment_new'] = $status;
$settings['video_comment_edit'] = $status;
$settings['video_comment_delete'] = $status;
$settings['video_comment_restore'] = $status;
$settings['market_comment_new'] = $status;
$settings['market_comment_edit'] = $status;
$settings['market_comment_delete'] = $status;
$settings['market_comment_restore'] = $status;
$settings['poll_vote_new'] = $status;
$settings['group_join'] = $status;
$settings['group_leave'] = $status;
$settings['group_change_settings'] = $status;
$settings['group_change_photo'] = $status;
$settings['group_officers_edit'] = $status;
$settings['user_block'] = $status;
$settings['user_unblock'] = $status;
$settings['like_add'] = $status;
$settings['like_remove'] = $status;
$settings['message_event'] = $status;
$this->robot->api['message_new'] = $status;
$this->robot->api['message_reply'] = $status;
$this->robot->api['message_allow'] = $status;
$this->robot->api['message_deny'] = $status;
$this->robot->api['message_edit'] = $status;
$this->robot->api['message_typing_state'] = $status;
$this->robot->api['photo_new'] = $status;
$this->robot->api['audio_new'] = $status;
$this->robot->api['video_new'] = $status;
$this->robot->api['wall_reply_new'] = $status;
$this->robot->api['wall_reply_edit'] = $status;
$this->robot->api['wall_reply_delete'] = $status;
$this->robot->api['wall_reply_restore'] = $status;
$this->robot->api['wall_post_new'] = $status;
$this->robot->api['wall_repost'] = $status;
$this->robot->api['board_post_new'] = $status;
$this->robot->api['board_post_edit'] = $status;
$this->robot->api['board_post_restore'] = $status;
$this->robot->api['board_post_delete'] = $status;
$this->robot->api['photo_comment_new'] = $status;
$this->robot->api['photo_comment_edit'] = $status;
$this->robot->api['photo_comment_delete'] = $status;
$this->robot->api['photo_comment_restore'] = $status;
$this->robot->api['video_comment_new'] = $status;
$this->robot->api['video_comment_edit'] = $status;
$this->robot->api['video_comment_delete'] = $status;
$this->robot->api['video_comment_restore'] = $status;
$this->robot->api['market_comment_new'] = $status;
$this->robot->api['market_comment_edit'] = $status;
$this->robot->api['market_comment_delete'] = $status;
$this->robot->api['market_comment_restore'] = $status;
$this->robot->api['poll_vote_new'] = $status;
$this->robot->api['group_join'] = $status;
$this->robot->api['group_leave'] = $status;
$this->robot->api['group_change_settings'] = $status;
$this->robot->api['group_change_photo'] = $status;
$this->robot->api['group_officers_edit'] = $status;
$this->robot->api['user_block'] = $status;
$this->robot->api['user_unblock'] = $status;
$this->robot->api['like_add'] = $status;
$this->robot->api['like_remove'] = $status;
$this->robot->api['message_event'] = $status;
}
}
return $this->robot->browser->request(method: 'POST', uri: 'groups.setLongPollSettings', options: $settings);
return $this->robot->browser->request(method: 'POST', uri: 'groups.setLongPollSettings', options: $this->robot->api['settings']);
}
/**
* Получить события
*
* $wait Время ожидания новых событий (в секундах)
* @param int $wait Время ожидания новых событий (в секундах)
*
* @return array
*/
public function get(int $wait = 25): array
{
if (empty($this->key) || empty($this->server) || empty($this->ts)) {
// Если не инициализирован LongPoll-сервер
// Реиницилазиция
$this->robot->api->reinit();
// Инициализация настроек
$this->robot->api['group_id'] = $this->robot->id;
// Запрос на получение доступа и данных LongPoll-сервера
$response = json_decode($this->robot->browser->request(method: 'POST', uri: 'groups.getLongPollServer', options: [
'form_params' => [
'group_id' => $this->robot->id,
'v' => $this->robot->version,
'access_token' => $this->robot->key
],
'form_params' => $this->robot->api['settings']
])->getBody()->getContents())->response;
// Ключ доступа
@ -210,8 +222,10 @@ final class longpoll
*
* Получает и обрабатывает события
*
* $function Обработка
* $wait Время ожидания новых событий (в секундах)
* @param callable $function Обработка
* @param int $wait Время ожидания новых событий (в секундах)
*
* @return array
*/
public function handle(callable $function, int $wait = 25): array
{

View File

@ -9,7 +9,7 @@ use hood\vk\robots\robot;
/**
* Сообщение
*
* public static function put(RobotAbstract $from, int $to, string $message, int $mode = 2) Отправить сообщение
* @method 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
@ -22,7 +22,7 @@ use hood\vk\robots\robot;
final class messages extends method
{
/**
* $mode Режим отправки
* @param int $mode Режим отправки
*/
protected int $mode = 1;
@ -31,10 +31,12 @@ final class messages extends method
*
* Если переданы все параметры, то сразу отправляет
*
* $robot Робот
* $message Текст
* $destination Получатель
* $attachments Вложения
* @param robot $robot Робот
* @param string $message Текст
* @param int|string|array|null $destination Получатель
* @param array $attachments Вложения
*
* @return self
*/
public function __construct(
protected robot $robot,
@ -49,7 +51,7 @@ final class messages extends method
/**
* Отправить сообщение
*
* $destination Получатель
* @param int|string|array $destination Получатель
*
* @see https://vk.com/dev/messages.send
*
@ -90,22 +92,21 @@ final class messages extends method
if (!empty($forward_messages)) {
// Если есть пересылаемые сообщения
$settings['forward_messages'] = implode(',', $forward_messages);
$this->robot->api['forward_messages'] = implode(',', $forward_messages);
}
//var_dump($attachments);
if (!empty($this->attachments)) {
// Если есть вложения
//echo 'lol';
$settings['attachment'] = implode(',', $this->attachments);
//var_dump($settings['attachment']);
$this->robot->api['attachment'] = implode(',', $this->attachments);
}
// Запрос
$request = $this->robot->browser->request(method: 'POST', uri: 'messages.send', options: ['form_params' => $settings]);
$request = $this->robot->browser->request(method: 'POST', uri: 'messages.send', options: ['form_params' => $this->robot->api['settings']]);
// Очистка
unset($settings);
//unset($settings);
if ($this->mode >= 2) {
// Если установлен режим 2 (усиленная проверка отправленного сообщения)
@ -113,17 +114,14 @@ final class messages extends method
if (!empty($request["response"])) {
// Если пришел ID сообщения
// Ключ
$settings['access_token'] = $this->robot->key;
// Версия API
$settings['v'] = $this->robot->version;
// Реиницилазиция
$this->robot->api->reinit();
// Запрашиваемые сообщения
$settings['message_ids'] = $request["response"];
$this->robot->api['message_ids'] = $request["response"];
// Запрос
if ($this->robot->browser->post(uri: 'https://api.vk.com/method/messages.getById', options: $settings)['response']['count'] === 0) {
if ($this->robot->browser->post(uri: 'https://api.vk.com/method/messages.getById', options: $this->robot->api['settings'])['response']['count'] === 0) {
// Если сообщения не существует, то повторить отправку
$this->send($destination);
}
@ -138,20 +136,22 @@ final class messages extends method
/**
* Получить информацию о сообщении
*
* Информация о сообщении
* @return array Информация о сообщении
*/
public function info(): array
{
$settings = $this->init();
//Инициализация
//$settings = $this->init();
$this->robot->api->init();
// Цель отправки
self::chooseDestination($settings, $this->destination);
$this->robot->api->chooseDestination($this->destination);
// Сообщение
$settings['message'] = $this->message;
$this->robot->api['message'] = $this->message;
// Режим отправки
$settings['mode'] = $this->mode;
$settings['mode'] = $this->mode; //!!!!!!!!!!!!!!!!!!!!!!
// Фильтрация вложений
$forward_messages = [];
@ -167,13 +167,13 @@ final class messages extends method
if (!empty($forward_messages)) {
// Если есть пересылаемые сообщения
$settings['forward_messages'] = implode(',', $forward_messages);
$this->robot->api['forward_messages'] = implode(',', $forward_messages);
}
if (!empty($attachments)) {
// Если есть вложения
$settings['attachment'] = implode(',', $attachments);
$this->robot->api['attachment'] = implode(',', $this->attachments);
}
return $settings;

View File

@ -8,12 +8,12 @@ use hood\vk\robots\robot;
/**
* Абстракция метода API
*
* protected static put(string $url, ...$params) Создать
* protected static post(string $url, ...$params) Изменить
* protected static get(string $url, ...$params) Получить
* protected static delete(string $url, ...$params) Удалить
*
*
* @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) Удалить
*
* @package hood\vk\api\methods
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*/
@ -21,8 +21,8 @@ abstract class method
{
/**
* Создать
*
* Ответ сервера
*
* @return array Ответ сервера
*/
public static function put(): array
{
@ -31,8 +31,8 @@ abstract class method
/**
* Изменить
*
* Ответ сервера
*
* @return array Ответ сервера
*/
public static function post(): array
{
@ -41,8 +41,8 @@ abstract class method
/**
* Получить
*
* Ответ сервера
*
* @return array Ответ сервера
*/
public static function get(): array
{
@ -51,8 +51,8 @@ abstract class method
/**
* Удалить
*
* Ответ сервера
*
* @return array Ответ сервера
*/
public static function delete(): array
{

View File

@ -14,7 +14,7 @@ use Exception;
/**
* Фотографии (изображения)
*
* public static function put(RobotAbstract $from, int $to, string $message, int $mode = 2) Отправить сообщение
* @method 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
@ -34,12 +34,12 @@ final class photos extends method
/**
* Сохранить
*
* $robot Робот
* $album_id Альбом
* $group_id Группа
* $caption Описание
* $latitude Географическая широта (-90, 90)
* $longitude Географическая долгота (-180, 180)
* @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)
*
* @see https://vk.com/dev/photos.save
*
@ -103,6 +103,7 @@ final class photos extends method
* Загрузить
*
* @param Type $var
* @return void
*/
public static function upload(string ...$images): void
{
@ -122,9 +123,9 @@ final class photos extends method
/**
* Получить сервер для загрузки изображений
*
* $robot Робот
* $album_id Альбом
* $group_id Группа
* @param robot $robot Робот
* @param int|null $album_id Альбом
* @param int|group|null $group_id Группа
*
* @see https://vk.com/dev/photos.getUploadServer
*
@ -164,17 +165,17 @@ final class photos extends method
/**
* Получить альбомы
*
* $robot Робот
* $album_ids = null Идентификаторы альбомов
* $offset = null Смещение для выборки подмножества
* $count = null Количество для возврата
* $need_system = null Активация возврата системных альбомов
* $need_covers = null Активация возврата поля с обложкой альбома
* $photo_sizes = null Активация специального формата размеров фотографий
* @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 Активация специального формата размеров фотографий
*
* @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
{
@ -208,25 +209,27 @@ final class photos extends method
}
/**
* загрузить фото и получить его id
*
* $robot робот
*
* $img фото
*/
* загрузить фото и получить его id
*
* $robot робот
*
* $img фото
*/
public function sex(robot $robot, $img)
public function get_photo(robot $robot, $img)
{
// Реиницилазиция
$this->robot->api->reinit();
// Инициализация настроек
$this->robot->api['group_id'] = $robot->id;
$this->robot->api['peer_id'] = 0;
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
]
'form_params' => $this->robot->api['settings']
])->getBody()->getContents())->response->upload_url;
}
@ -241,18 +244,18 @@ final class photos extends method
]
])->getBody()->getContents());
$this->robot->api->reinit();
$this->robot->api['group_id'] = $robot->id;
$this->robot->api['server'] = $response->server;
$this->robot->api['photo'] = $response->photo;
$this->robot->api['hash'] = $response->hash;
//сохранить
$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
]
'form_params' => $this->robot->api['settings']
])->getBody()->getContents());
//Ссылка на фото
return 'photo' . $response->response[0]->owner_id . '_' . $response->response[0]->id;
}
}
}

View File

@ -12,15 +12,15 @@ use hood\vk\loggers\jasmo,
/**
* Ядро
*
* $robots Количество роботов
* $timezone Временная зона (журналирование)
* $path Пути (архитектура проекта)
* @property-read int $robots Количество роботов
* @property string $timezone Временная зона (журналирование)
* @property array $path Пути (архитектура проекта)
*
* protected static function __construct() Инициализация
* public static function init() Запуск инициализации или получение инстанции
* public public function build() Сборщик
* public function set($id, $value) Запись в реестр
* public function get($id = null) Чтение из реестра
* @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) Чтение из реестра
*
* @package VK
* @author Арсен Мирзаев <red@hood.su>
@ -29,13 +29,17 @@ final class core
{
use singleton;
/**
/**
* Счётчик роботов
*
* @var int
*/
private int $robots = 0;
/**
* Реестр роботов
*
* @var array
*/
private array $registry = [];
@ -43,28 +47,38 @@ 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;
/**
* Журналист
*
* $file Файл для журналирования
* @param string $file Файл для журналирования
*
* @return self
*
* @todo Добавить установку иного журналиста по спецификации PSR-3
* @todo Более гибкое журналирование
@ -80,10 +94,12 @@ final class core
/**
* Записать в реестр
*
* $id Идентификатор
* $robot робот
* @param int $id
* @param robot $robot
*
* @see hood\vk\traits\registry Модификация метода
*
* @return void
*/
public function set(int $id, robot $robot): void
{
@ -101,10 +117,12 @@ final class core
*
* Если не передать идентификатор, то вернёт все значения
*
* $id Идентификатор
* $session Сессия
* @param int|null $id Идентификатор
* @param int|null $session Сессия
*
* @see hood\vk\traits\registry Модификация метода
*
* @return mixed
*/
public function get(int|null $id = null, int|null $session = null): mixed
{
@ -122,10 +140,12 @@ final class core
/**
* Удалить из реестра
*
* $id Идентификатор
* $session Сессия
* @param int|null $id Идентификатор
* @param int|null $session Сессия
*
* @see hood\vk\traits\registry Модификация метода
*
* @return void
*/
public function delete(int|null $id = null, int|null $session = null): void
{
@ -168,8 +188,10 @@ final class core
/**
* Записать свойство
*
* $name Название
* $value Значение
* @param mixed $name Название
* @param mixed $value Значение
*
* @return void
*/
public function __set(mixed $name, mixed $value): void
{
@ -183,10 +205,10 @@ final class core
/**
* Прочитать свойство
*
* Значение по умолчанию, есле не задано
*
* $name Название
* @param mixed $name Название
*
* @return mixed
*/
public function __get(mixed $name): mixed
{
@ -206,8 +228,10 @@ final class core
* Ищет класс описывающий робота,
* создаёт и возвращает его объект
*
* $method Метод
* $params Параметры
* @param string $method Метод
* @param array $params Параметры
*
* @return robot
*/
public function __call(string $method, array $params): robot
{

View File

@ -13,29 +13,31 @@ use Throwable,
/**
* Робот-группа
*
* $longpoll LongPoll-сессия
* @property longpoll $longpoll LongPoll-сессия
*
* public function __set($name, $value) Запись свойства
* public function __get($name) Чтение свойства
* public function __isset($name) Проверка на инициализированность свойства
* @method public function __set($name, $value) Запись свойства
* @method public function __get($name) Чтение свойства
* @method public function __isset($name) Проверка на инициализированность свойства
*
* hood\vk\robots
* Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
* @package hood\vk\robots
* @author Arsen Mirzaev Tatyano-Muradovich <red@hood.su>
*/
final class group extends robot
{
/**
* $longpoll LongPoll-сессия
* @var longpoll $longpoll LongPoll-сессия
*/
protected longpoll $longpoll;
/**
* Запись свойства
*
* $name Название
* $value Значение
* @param string $name Название
* @param mixed $value Значение
*
* @see hood\vk\robots\robot Наследуемый метод
*
* @return void
*/
public function __set(string $name, mixed $value): void
{
@ -54,9 +56,11 @@ final class group extends robot
/**
* Чтение свойства
*
* $name Название
* @param string $name Название
*
* @see hood\vk\robots\robot Наследуемый метод
*
* @return mixed
*/
public function __get(string $name): mixed
{
@ -79,11 +83,11 @@ final class group extends robot
/**
* Проверка на инициализированность свойства
*
* $name Название
* @param string $name Название
*
* @return mixed
*/
public function __isset(string $name)
public function __isset(string $name): bool
{
try {
return parent::__isset($name);

View File

@ -47,42 +47,37 @@ use hood\accounts\vk as account;
abstract class robot
{
/**
* Идентификатор
*/
protected int $id;
/**
* Сессия
* @var int Сессия
*/
protected int $session;
/**
* Ключ
* @var string Ключ
*/
protected string $key;
/**
* Аккаунт
* @var string Аккаунт
*/
private account $account;
/**
* Прокси
* @var proxy Прокси
*/
protected proxy $proxy;
/**
* Обработчик капчи
* @var captcha Обработчик капчи
*/
protected captcha $captcha;
/**
* Режим отправки сообщений
* @var int Режим отправки сообщений
*/
protected int $messages_mode = 1;
/**
* API ВКонтакте
* @var api API ВКонтакте
*/
protected api $api;
@ -91,10 +86,9 @@ abstract class robot
* Конструктор
*
* @param int $id Идентификатор
* @param float $version Версия API
*/
public function __construct(
int|null $id = null
protected int|null $id = null,
) {
// Инициализация ядра
$core = core::init();
@ -112,7 +106,9 @@ abstract class robot
/**
* Инициализация ключа
*
* $key Ключ
* @param string $key Ключ
*
* @return self
*/
public function key(string $key): self
{
@ -128,7 +124,9 @@ abstract class robot
/**
* Инициализация аккаунта
*
* $account Аккаунт
* @param account $account Аккаунт
*
* @return self
*/
public function account(account $account): self
{
@ -144,7 +142,9 @@ abstract class robot
/**
* Инициализация прокси
*
* $proxy Прокси
* @param proxy $proxy Прокси
*
* @return self
*/
public function proxy(proxy $proxy): self
{
@ -156,7 +156,9 @@ abstract class robot
/**
* Инициализация обработчика капчи
*
* $captcha Обработчик капчи
* @param captcha $captcha Обработчик капчи
*
* @return self
*/
public function captcha(captcha $captcha): self
{
@ -168,8 +170,10 @@ abstract class robot
/**
* Записать свойство
*
* $name Название
* $value Значение
* @param string $name Название
* @param mixed $value Значение
*
* @return void
*/
public function __set(string $name, mixed $value): void
{
@ -191,6 +195,8 @@ abstract class robot
* Прочитать свойство
*
* @param string $name Название
*
* @return mixed
*/
public function __get(string $name): mixed
{
@ -215,6 +221,8 @@ abstract class robot
* Проверить свойство на инициализированность
*
* @param string $name Название
*
* @return mixed
*/
public function __isset(string $name): bool
{
@ -238,8 +246,10 @@ abstract class robot
* Ищет класс описывающий метод API ВКонтакте,
* создаёт и возвращает его объект
*
* $method Метод
* $params Параметры
* @param string $method Метод
* @param array $params Параметры
*
* @return method
*/
public function __call(string $method, array $params): method
{
@ -257,8 +267,10 @@ abstract class robot
* Ищет класс описывающий метод API ВКонтакте,
* создаёт и возвращает его объект
*
* $method Метод
* $params Параметры
* @param string $method Метод
* @param array $params Параметры
*
* @return method
*/
public static function __callStatic(string $method, array $params): method
{
@ -271,6 +283,8 @@ abstract class robot
/**
* Конвертировать в строку
*
* @return string
*/
public function __toString(): string
{

View File

@ -27,6 +27,8 @@ trait singleton
/**
* Инициализация
*
* @return self
*/
public static function init(): self
{