### View rendering usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Example of a view class and how to send it from an action. ```php // App/Views/ProfileView.php class ProfileView extends BaseView { public function render(Context $ctx, int $userId): Message { return $ctx->msg("Профиль: $userId"); } } // inside an Action $ctx->sendView(ProfileView::class, $userId: 123); ``` -------------------------------- ### Sending shortcuts usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Example of using reply() and msg() to send messages. ```php public function handle(Context $ctx): void { $ctx->reply('Привет!'); $ctx->msg('Подробнее:')->kbd([['btn']])->send(); } ``` -------------------------------- ### Dependency resolution usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Example of a class using constructor injection and the context's get() method to resolve services. ```php class BanAction extends BaseCommand { public function __construct(private SomeService $service) {} public function handle(Context $ctx, int $userId): void { /* $ctx->get(OtherService::class) also works inside */ } } ``` -------------------------------- ### Read/write operations example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Store.md Demonstrates set, save, sset, get, unset, and close. set() and unset() are in-memory until save() is called; sset() combines set and save. close() is optional because the destructor calls it. ```php $store = Store::load('game_state'); $store->set('score', 42)->set('level', 3); $store->save(); // commit both $store->sset('last_visit', time()); // set + commit in one call $score = $store->get('score'); // 42 $store->unset('level')->save(); $store->close(); // optional; destructor does it too ``` -------------------------------- ### Usage examples for reply() and msg() Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVK.md Shows two usage examples: reply() for a fast answer to the current dialog, and msg() with a fluent Message builder that adds a keyboard and sends. ```php $vk->reply('Привет'); // fast answer to current dialog $vk->msg('Hello')->kbd([['btn1']])->send(); // full Message builder ``` -------------------------------- ### Bot usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Shows how to create a bot, register commands, buttons, and redirects, then run the bot inside a callback or LongPoll listener. ```php $bot = Bot::create($vk); $bot->cmd('img', '!картинка')->img('cat.jpg')->text('Вот твой кот'); $bot->cmd('sum', '!посчитай %n + %n')->func(function ($msg, $params) { $msg->text($params[0] + $params[1]); }); $bot->preg_cmd('more_word', "!\!напиши (.*)!")->func(function ($msg, $params) { $msg->text("Ваше предложение: $params[1]"); }); $bot->btn('fish', 'Рыбка')->text('Вы выбрали Рыбку!'); $bot->redirect('other', 'first'); $bot->run(); // inside callback / LongPoll listen ``` -------------------------------- ### Fluent configuration example with captcha handler Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Auth.md Demonstrates creating an Auth instance with scope, app selection, and a captcha handler. The captcha handler receives the captcha sid and image URL and must return the answer. This example uses the official app mode with 'android'. ```php use DigitalStars\SimpleVK\Auth; $auth = Auth::create('login', 'password') ->scope('friends,messages,offline') ->app('android') ->captchaHandler(function ($sid, $img) { return prompt_captcha($img); // human/OCR answers }); ``` -------------------------------- ### Implementing and using RoleGuard middleware Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher-Models.md Example of a RoleGuard middleware implementation and its application to a command using the UseMiddleware attribute. ```php use DigitalStars\SimpleVK\EventDispatcher\{MiddlewareInterface, Context}; use DigitalStars\SimpleVK\Attributes\UseMiddleware; class RoleGuard implements MiddlewareInterface { public function process(Context $context, callable $next): void { if ($context->getAttribute('user_id') !== 1) { // deny $context->reply('Доступ запрещён'); return; } $next($context); // allow } } #[UseMiddleware(RoleGuard::class)] #[Trigger(command: '!admin')] class AdminPanel extends BaseCommand { /* ... */ } ``` -------------------------------- ### Creating a post with text and image Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Post.md Example of using Post::create to build a post with text and an image. ```php use DigitalStars\SimpleVK\Post; $post = Post::create($vk)->text('Новость дня')->img('news.png'); ``` -------------------------------- ### Dispatching other actions usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Example of running another command conditionally based on an attribute. ```php class HelpCommand extends BaseCommand { public function handle(Context $ctx): void { if ($ctx->getAttribute('need_help')) { $ctx->run(OtherCommand::class, ['topic' => 'rules']); } } } ``` -------------------------------- ### listen usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/LongPoll.md Example of using the listen method with a group token. The callback initializes variables and sends a reply when a message_new event with the text 'Привет' is received. ```php use DigitalStars\SimpleVK\LongPoll; $vk = LongPoll::create('GROUP_TOKEN', '5.199'); $vk->setUserLogError(123456); $vk->listen(function () use ($vk) { $data = $vk->initVars($peer_id, $user_id, $type, $message); if ($type === 'message_new' && $message === 'Привет') { $vk->msg('Привет, ~!fn~')->send(); } }); ``` -------------------------------- ### Example view using BaseView Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher-Models.md Example of a view class that extends BaseView and implements a render method returning a Message. The render method uses Context and an integer user ID to create a message. ```php use DigitalStars\SimpleVK\EventDispatcher\BaseView; use DigitalStars\SimpleVK\Message; class ProfileView extends BaseView { public function render(Context $ctx, int $userId): Message { return $ctx->msg("Профиль: $userId"); } } ``` -------------------------------- ### Instantiate Streaming client Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Streaming.md Example of creating a Streaming client with a streaming token and VK API version 5.199. Requires the DigitalStars\SimpleVK\Streaming namespace. ```php use DigitalStars\SimpleVK\Streaming; $stream = new Streaming('STREAM_TOKEN', '5.199'); ``` -------------------------------- ### Sending and editing messages examples Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Message.md Examples of sending a message to the event peer, sending to multiple peers, and editing a message using finalSendID and sendEdit. ```php $vk->msg('Привет')->send(); // to the event peer $vk->msg('Всем!')->send([123, 456]); // multi-peer $vk->msg('Edit me')->finalSendID(123)->sendEdit(123, null, 7); // edit message 7 in chat 123 ``` -------------------------------- ### SiteAuth::redir usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SiteAuth.md Example call to the static redir helper, passing the authorization link from get_link(). This is equivalent to calling auth() on the first visit. ```php SiteAuth::redir($auth->get_link()); // same as calling $auth->auth() on first visit ``` -------------------------------- ### Sending a post immediately and scheduled Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Post.md Examples of sending a post immediately, scheduling it for a future time, and handling an invalid past date. ```php // immediate publish $res = Post::create($vk)->text('Первый пост!')->img('hero.jpg')->send(); // $res['post_id'] — the new post id // scheduled publish (unix timestamp in the future) $post = Post::create($vk, null); $post->text('Автопостинг')->send(null, strtotime('+1 hour')); try { $post->send(null, time() - 60); // past date } catch (SimpleVkException $e) { // 'Неверно указан $publish_date' } ``` -------------------------------- ### Attribute bag usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Example of setting and getting an attribute to store per-event data. ```php $ctx->setAttribute('ban_check', true); if ($ctx->getAttribute('ban_check', false)) { /* ... */ } ``` -------------------------------- ### EventDispatcher usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher.md Shows how to instantiate the EventDispatcher with a SimpleVK instance and a DispatcherConfig, optionally providing a PSR-11 container. After creation, call handle() inside the callback or LongPoll loop to process events. ```php use DigitalStars\SimpleVK\SimpleVK; use DigitalStars\SimpleVK\EventDispatcher\{EventDispatcher, DispatcherConfig}; $vk = SimpleVK::create($token, '5.199'); $config = (new DispatcherConfig(__DIR__ . '/Actions', debug: true)) ->withContainer($container); // PSR-11 DI — optional $dispatcher = new EventDispatcher($vk, $config); // inside the callback / LongPoll loop: $dispatcher->handle(); ``` -------------------------------- ### Example command using BaseCommand and Trigger Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher-Models.md Example of a command handler that extends BaseCommand and uses the #[Trigger] attribute. The handle method receives a Context and replies with a message. ```php use DigitalStars\SimpleVK\EventDispatcher\{BaseCommand, Context}; use DigitalStars\SimpleVK\Attributes\Trigger; #[Trigger(command: '!привет')] class SayHello extends BaseCommand { public function handle(Context $ctx): void { $ctx->reply('Привет!'); } } ``` -------------------------------- ### Usage example for kbd, forward, and reply Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Message.md Shows how to use the kbd, forward, and reply methods in a chain with the msg() method. The kbd method accepts an array of button arrays, forward takes message IDs, and reply takes a message ID, conversation message ID, and peer ID. ```php $vk->msg('Выбери:') ->kbd([[$vk->buttonText('Да', 'green'), $vk->buttonCallback('Нет', 'red')]], inline: true) ->send(); $vk->msg('Смотри')->forward([123, 124])->send(); $vk->msg('В ответ')->reply(456, null, 789)->send(); // reply inside chat 789 ``` -------------------------------- ### Example usage of Diagnostics::run() Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Diagnostics.md Shows how to invoke the diagnostics from a PHP script. Requires the Composer autoloader and runs in the same environment as the bot: for a Callback bot open the script in a browser, for a LongPoll bot run php diagnostics.php in the console. ```php setConfirm('CONFIRMATION_STRING'); $data = $vk->initVars($peer_id, $user_id, $type, $message); if ($type === 'message_new') { $vk->msg('Привет, ~!fn~')->send(); } ``` -------------------------------- ### Manual event injection example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVK.md Creates a SimpleVK instance with explicit raw JSON event data, useful for tests or workers where php://input is not used. ```php // Manual event injection (tests, workers): explicit raw JSON $vk = new SimpleVK('TOKEN', '5.199', null, '{"type":"message_new","object":{...}}'); ``` -------------------------------- ### Carousel usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Message.md Example of chaining carousel() to add multiple carousel elements with title, description, image, and action, then sending the message. ```php $vk->msg('Каталог') ->carousel()->title('Товар 1')->description('Описание')->img('cat.jpg') ->carousel()->title('Товар 2')->action('https://vk.com') ->send(); ``` -------------------------------- ### sendAllDialogs usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVK.md Example usage of sendAllDialogs: sends a message with an image to all dialogs. ```php $vk->sendAllDialogs($vk->msg('Рассылка!')->img('pic.jpg')); ``` -------------------------------- ### Use initVars and clientSupport together Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVK.md Usage example: calls initVars to populate common event fields, then clientSupport to retrieve client capabilities. The second call returns the capabilities array into $capabilities. ```php $vk->initVars($peer_id, $user_id, $type, $message, $payload, $id, $attachments); $capabilities = $vk->clientSupport($kbd, $inline, $carousel, $actions, $lang); ``` -------------------------------- ### Chained bot commands and actions Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Example of chaining bot commands, buttons, and messages. The first line builds a command with a keyboard; the second adds a button action; the third sends a message with a delay and runs another action; the last runs the bot. ```php $bot->cmd('first')->kbd([['fish', 'cat']])->text('Выберите животное:'); $bot->btn('fish', 'Рыбка')->text('Вы выбрали Рыбку!'); // chain continues building action 'fish' $bot->msg('Привет')->b_sleep(1)->text('Как дела?')->a_run('second')->send(); $bot->run(); ``` -------------------------------- ### SiteAuth usage with auth callback Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SiteAuth.md Complete usage example: creates a SiteAuth instance with required settings and optional scope, then calls auth() with a callback that extracts the access token and group tokens. On first visit it redirects to VK; on callback it receives the token data. ```php use DigitalStars\SimpleVK\SiteAuth; $auth = SiteAuth::create([ 'client_id' => 123456, 'client_secret' => 'secret', 'redirect_uri' => 'https://example.com/vk-callback', 'scope' => 'email,photos', ]); // entry script: first call redirects to VK, second receives the code $auth->auth(function (array $data) { $token = $data['access_token'] ?? null; $groupTokens = $data['token_groups'] ?? []; save_session_token($token, $groupTokens); echo 'Logged in'; }); ``` -------------------------------- ### placeholders usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVK.md Example usage of the placeholders method: sends a message with a ~!fn~ token that is replaced with a clickable mention of the user's first name. ```php $vk->msg('Привет, ~!fn~')->send(); // → Привет, @id1(Павел) ``` -------------------------------- ### Using static logging methods Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVkException.md Usage example of the static logging API. Sets a custom error directory, disables file logging, and logs a manual entry. The comment shows the resulting log file name. ```php SimpleVkException::setErrorDirPath(__DIR__ . '/my_errors/'); // logs → my_errors/error_log2025-01-01.php SimpleVkException::disableWriteError(); // stop file logging SimpleVkException::logCustomError('manual entry'); ``` -------------------------------- ### Authorization usage examples Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Auth.md Shows three usage patterns: official-app token from login/password, custom-app with cookies, and passing credentials directly to SimpleVK. The custom-app flow requires calling app() with the app ID, checking isAuth(), and calling auth() if needed. ```php // official apps: token from login+password $auth = Auth::create('login', 'password'); $token = $auth->getAccessToken(); $vk = SimpleVK::create($token, '5.199'); // custom app with cookies $auth->app(6123456); if (!$auth->isAuth()) { $auth->auth(); } $token = $auth->getAccessToken(); // or hand the credentials straight to SimpleVK (login flow): $vk = SimpleVK::create('login', 'password', '5.199'); ``` -------------------------------- ### ClickMeButton with #[AsButton] Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher-Models.md Example of a concrete button handler using the #[AsButton] attribute to define label, payload, color, and type. The handle method receives a Context and replies when the button is pressed. The payload 'click_me' is used for routing. ```php use DigitalStars\SimpleVK\EventDispatcher\BaseButton; use DigitalStars\SimpleVK\Attributes\AsButton; #[AsButton(label: 'Нажми меня', payload: 'click_me', color: 'green', type: 'callback')] class ClickMeButton extends BaseButton { public function handle(Context $ctx): void { $ctx->reply('Кнопка нажата!'); } } ``` -------------------------------- ### Dispatcher handle() usage examples Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher.md Shows three usage patterns: callback flow with confirm code, LongPoll flow with a listener, and manual event injection. The callback flow requires a confirm code; the LongPoll flow uses a token and API version; manual injection passes an event array directly. ```php // Callback flow $vk->setConfirm('code'); $dispatcher->handle(); // LongPoll flow $lp = LongPoll::create($token, '5.199'); $lp->listen(fn() => $dispatcher->handle()); // manual event injection $dispatcher->handle(['type' => 'message_new', 'object' => [...]]); ``` -------------------------------- ### Using listen with a callback Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Streaming.md Example of passing a callback to listen. The callback receives raw frame data; parse it yourself or use a custom reader. The comment notes the callback gets raw bytes, not the parsed event. ```php $stream->listen(function ($data) use ($stream) { // $data is the raw WebSocket frame — parse it yourself, // or use the pre-processed fields via a custom reader. handle_stream_event($data); }); ``` -------------------------------- ### AsButton usage example on a button class Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Attributes.md Shows how to apply the AsButton attribute to a custom button class that extends BaseButton. The attribute sets the button label, payload, color, and type. During keyboard serialization, dynamic properties set via BaseButton methods override these attribute values, and the payload gets an 'action' key appended. ```php #[AsButton(label: 'Кнопка', payload: 'my_btn', color: 'green', type: 'callback')] class MyButton extends BaseButton { public function handle(Context $ctx): void { /* ... */ } } ``` -------------------------------- ### Compile and load cache_bot.php Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Shows how to compile the bot config to a cache file and then load it back. The first line writes the compiled file, the second restores it via `include`. ```php $source = $bot->compile('compile', 'cache_bot'); // write compiled file $bot->load(include 'cache_bot.php'); // restore ``` -------------------------------- ### PackagistReporter::checkAndReport Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/InternalUtils.md Reports anonymous install statistics to Packagist. Active only in archive installs; no-op if a marker file exists or if any failure occurs. ```APIDOC ## PackagistReporter::checkAndReport ### Description Sends anonymous install statistics to Packagist for archive installs. Checks for a marker file to avoid duplicate reports; reads `vendor/composer/installed.json` and POSTs download data to `https://packagist.org/downloads/`. All failures are silently ignored. ### Method checkAndReport ### Signature public static function checkAndReport(): void ### Return Value - **void** - No return value. ``` -------------------------------- ### Command Registration (cmd, preg_cmd, btn, redirect) Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Fluent methods for registering actions: cmd for mask commands, preg_cmd for regex commands, btn for button actions, and redirect for fallback routing. ```APIDOC ## Command Registration (cmd, preg_cmd, btn, redirect) ### Description Fluent methods for registering actions: cmd for mask commands, preg_cmd for regex commands, btn for button actions, and redirect for fallback routing. ### Methods - `cmd($name, $mask)` - Registers a mask command action - `preg_cmd($name, $pattern)` - Registers a regex command action - `btn($name, $label)` - Registers a button action - `redirect($from, $to)` - Sets a redirect from one action to another ### Example ```php $bot = Bot::create($vk); $bot->cmd('img', '!картинка')->img('cat.jpg')->text('Вот твой кот'); $bot->cmd('sum', '!посчитай %n + %n')->func(function ($msg, $params) { $msg->text($params[0] + $params[1]); }); $bot->preg_cmd('more_word', "!\!напиши (.*)!")->func(function ($msg, $params) { $msg->text("Ваше предложение: $params[1]"); }); $bot->btn('fish', 'Рыбка')->text('Вы выбрали Рыбку!'); $bot->redirect('other', 'first'); $bot->run(); // inside callback / LongPoll listen ``` ``` -------------------------------- ### Configure factory or container Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/DispatcherConfig.md Shows two ways to configure object creation: withFactory using a closure that instantiates with a service, or withContainer using a PSR-11 container. The comment indicates these are alternatives. ```php $config = (new DispatcherConfig(__DIR__ . '/Actions')) ->withFactory(fn(string $class) => new $class(new MyService())); // or $config->withContainer($psr11Container); ``` -------------------------------- ### ErrorHandler usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/ErrorHandler.md Example usage of the ErrorHandler trait. Creates a SimpleVK instance, activates error reporting with a VK user ID, enables short traces, and filters a path. The callable variant shows how to handle errors yourself with a custom logger. ```php $vk = SimpleVK::create($token, '5.199')->setUserLogError(123456)->shortTrace(); $vk->setTracePathFilter('C:\\your\\path'); // shorten paths in the report // callable variant: handle errors yourself $vk->setUserLogError(fn($type, $message, $code, $e) => my_logger($type, $message)); ``` -------------------------------- ### Opening a store with Store::load Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Store.md Loads a store instance by filename. The filename is used without extension and stored at Store::$path / .php. This is equivalent to new Store('counters'). ```php use DigitalStars\SimpleVK\Store; $store = Store::load('counters'); // equals new Store('counters') ``` -------------------------------- ### handle() method signature Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/EventDispatcher.md Main entry point for the dispatcher. An empty array argument triggers an E_USER_NOTICE and returns; without a user_id in debug mode, it emits a notice and returns. It injects the event into the VK instance, normalizes it, resolves the route, creates a Context, and runs the action through middleware. ```php public function handle(?array $externalEvent = null): void ``` -------------------------------- ### Configuration and Utility Methods Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Methods for redirects, default settings, and message/button utilities. ```APIDOC ## redirect($id, $to_id) ### Description Aliases action `$id` to `$to_id` by reference. ### Method `redirect($id, $to_id)` ### Parameters - `$id` (string) - Required - Action id to alias. - `$to_id` (string) - Required - Target action id. ### Returns - `$this` - The current bot instance for chaining. --- ## setDefaultColor($color) ### Description Sets the default button color. Valid colors: `white`, `green`, `red`, `blue`. Throws `SimpleVkException` on invalid color. ### Method `setDefaultColor($color)` ### Parameters - `$color` (string) - Required - Button color name. ### Returns - `$this` - The current bot instance for chaining. --- ## setCaseDefault($case = true) ### Description Sets the default case sensitivity for `cmd()`. ### Method `setCaseDefault($case = true)` ### Parameters - `$case` (bool) - Optional - Default case sensitivity. ### Returns - `$this` - The current bot instance for chaining. --- ## isTextBtnTriggered($status = true) ### Description Enables or disables auto-registration of text commands for all text buttons. ### Method `isTextBtnTriggered($status = true)` ### Parameters - `$status` (bool) - Optional - Enable or disable. ### Returns - `$this` - The current bot instance for chaining. --- ## isAllBtnCallback($is = true) ### Description Inverts the callback/text default for `btn()`. ### Method `isAllBtnCallback($is = true)` ### Parameters - `$is` (bool) - Optional - Enable or disable. ### Returns - `$this` - The current bot instance for chaining. --- ## msg($text = null) ### Description Creates a `MessageBot` with the given text. ### Method `msg($text = null)` ### Parameters - `$text` (string) - Optional - Message text. ### Returns - `MessageBot` - A new message bot instance. --- ## editBtn($id, $is_save = false) ### Description Edits a button by id. Throws `SimpleVkException` if the button id does not exist. ### Method `editBtn($id, $is_save = false)` ### Parameters - `$id` (string) - Required - Button id. - `$is_save` (bool) - Optional - Whether to save. ### Returns - `Button` - The created button instance. ``` -------------------------------- ### Attribute bag methods Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Methods to get and set attributes in the context's in-memory key-value store, scoped to one event. ```php public function getAttribute(string $name, $default = null) public function setAttribute(string $name, $value): self ``` -------------------------------- ### Catching SimpleVkException from VK request Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVkException.md Example of catching a SimpleVkException thrown by a VK API request. The catch block prints the error code and message. ```php use DigitalStars\SimpleVK\SimpleVkException; try { $vk->request('messages.send', [...]); } catch (SimpleVkException $e) { echo $e->getCode() . ': ' . $e->getMessage(); } ``` -------------------------------- ### Button constructor and create() Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Constructor and static factory for the Button wrapper. $is_save = true keeps a reference so mutations affect the bot's stored button; false copies. ```php public function __construct(&$config, $is_save, $id) static function create(&$config, $is_save, $id) ``` -------------------------------- ### GET https://oauth.vk.com/authorize Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SiteAuth.md Builds the authorization URL that redirects the user to VK for login and consent. This is the first step of the OAuth 2.0 authorization-code flow. ```APIDOC ## GET https://oauth.vk.com/authorize ### Description Builds and returns the authorization URL that redirects the user to VK for login and consent. This is the first step of the OAuth 2.0 authorization-code flow. ### Method GET ### Endpoint https://oauth.vk.com/authorize ### Parameters #### Query Parameters - **client_id** (int) - Required - VK application id - **redirect_uri** (string) - Required - OAuth redirect URI - **response_type** (string) - Required - Must be `code` - **scope** (string) - Optional - Permission scope - **group_ids** (string) - Optional - Comma-separated group IDs to enable group tokens - **display** (string) - Optional - Display mode: `page`, `popup`, `mobile` (default: `page`) ### Response #### Success Response (302) Redirects to the `redirect_uri` with a `code` query parameter. ``` -------------------------------- ### getRules method Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Streaming.md Returns the current streaming rules as an array. It requests the rules endpoint using HTTP GET and retrieves the 'rules' key from the response. ```php public function getRules(): array ``` -------------------------------- ### Public helper method signatures Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Diagnostics.md Declares the public static helper methods for patching php.ini, checking modules, formatting text, and getting the end-of-line string. ```php public static function php_iniPatch() public static function checkModules() public static function formatText($text, $color, $separator = PHP_EOL, $need_dot = true) public static function EOL() public static function finish() ``` -------------------------------- ### Post::load Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Post.md Loads configuration from an array or another Post instance. ```APIDOC ## Post::load ### Description Loads configuration from an array or another Post instance, copying the VK instance and config. ### Method load ### Signature ```php public function load($cfg = []) ``` ### Parameters - **$cfg** (array|Post) - Required - Configuration array or another Post instance ### Return Value void ``` -------------------------------- ### SimpleVK configuration with error logging and trace filter Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/configuration.md Use to initialize SimpleVK with a token and API version, enable error logging to a VK user with a short trace, and filter trace paths. Requires a valid TOKEN and YOUR_VK_ID. The path filter uses double backslashes. ```php // Configuration summary — see README "Конфиги" $vk = SimpleVK::create(TOKEN, '5.238'); $vk->setUserLogError(YOUR_VK_ID)->shortTrace(); $vk->setTracePathFilter('C:\\your\\path'); ``` -------------------------------- ### Handling invalid JSON response from requestCore Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Request.md Example of calling requestCore() directly and catching SimpleVkException with code 77778 to handle malformed JSON responses. The error message can be inspected via $e->getMessage(). ```php try { $result = $this->requestCore('https://api.vk.ru/method/users.get', ['user_ids' => 1, 'v' => '5.199', 'access_token' => $t]); } catch (SimpleVkException $e) { if ($e->getCode() === 77778) { // VK returned malformed JSON — inspect $e->getMessage() } } ``` -------------------------------- ### EventDispatcher instantiation Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/configuration.md Creates an EventDispatcher with a SimpleVK instance and DispatcherConfig. DispatcherConfig options include actionsPaths (required), debug, cache, withFactory, withContainer, and withMiddleware. ```php new EventDispatcher(SimpleVK $vk, DispatcherConfig $config) ``` -------------------------------- ### Action with automatic argument injection Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/ArgumentResolver.md Example action with automatic argument injection. The handle method receives Context, a DI-resolved UserAdmin, and parameters resolved from named/positional args or defaults. The reply uses the resolved $name. ```php // Action with automatic injection class GreetCommand extends BaseCommand { public function handle( Context $ctx, // priority 1 UserAdmin $admin, // priority 3 (DI via factory) int $userId = 0, // priority 2 (named) / 5 (default) string $name = 'anon' // priority 4 (positional from regex) ): void { $ctx->reply("Привет, $name!"); } } ``` -------------------------------- ### Instance Access Methods Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Methods to access the underlying SimpleVK instance and configure confirmation and secret keys. ```APIDOC ## vk() ### Description Returns the underlying `SimpleVK` instance. ### Method `vk()` ### Parameters None ### Returns - `SimpleVK` - The underlying SimpleVK instance. --- ## setConfirm($str) ### Description Delegates to `$this->vk->setConfirm()` and returns `$this` for chaining. ### Method `setConfirm($str)` ### Parameters - `$str` (string) - Required - The confirmation string. ### Returns - `$this` - The current bot instance for chaining. --- ## setSecret($str) ### Description Delegates to `$this->vk->setSecret()` and returns `$this` for chaining. ### Method `setSecret($str)` ### Parameters - `$str` (string) - Required - The secret key. ### Returns - `$this` - The current bot instance for chaining. ``` -------------------------------- ### Static factory and enableInWeb methods Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/LongPoll.md Static factory method create() and enableInWeb() method. enableInWeb() lifts the CLI-only guard to allow running in web requests, but the loop can only be stopped by killing the process. ```php public static function create($token, $version, $also_version = null, $data = null) public static function enableInWeb($bool = true) ``` -------------------------------- ### Sending shortcuts methods Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Context.md Methods to create a message or reply to the current peer. ```php public function msg(string $text = ''): Message public function reply(string $text = '') ``` -------------------------------- ### Proxy and error suppression usage example Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Request.md Shows how to set a SOCKS5 proxy with credentials and enable error suppression. After setProxy(), all network requests go through the proxy. With errorSuppression(), API errors are returned as data instead of thrown. ```php use DigitalStars\SimpleVK\Request; Request::setProxy('socks5://174.77.111.198:49547', 'user:pass'); // all network requests through proxy Request::errorSuppression(); // API errors returned as data instead of thrown ``` -------------------------------- ### Bot::create Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Static factory method that creates and returns a new Bot instance. ```APIDOC ## Bot::create ### Creates a new Bot instance using the static factory pattern. ### Signature public static function create($token_or_vk, $version = null, $also_version = null) ### Parameters - **$token_or_vk** (string|SimpleVK) - Required. Existing `SimpleVK`/`LongPoll` instance, or a token - **$version** (string) - Optional. API version string - **$also_version** (string) - Optional. Login-based flow API version ### Returns - New Bot instance ``` -------------------------------- ### Edit button with payload and text Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Bot.md Usage example: edit a registered button by reference, set its payload and text. The payload must not contain a 'name' key (reserved); text is allowed only for types text, callback, open_link, open_app. ```php $btn = $bot->editBtn('fish', true); // by-reference $btn->payload(['count' => 2])->text('Рыбка x2'); ``` -------------------------------- ### Post::create Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/Post.md Factory method to create a new Post instance, optionally bound to a VK instance and pre-seeded config. ```APIDOC ## Post::create ### Description Creates a new Post instance for building wall posts. Optionally binds a VK instance and pre-seeds the configuration. ### Method create ### Signature ```php public static function create($vk = null, &$cfg = null) ``` ### Parameters - **$vk** (SimpleVK) - Optional - Bound VK instance - **$cfg** (array, by reference) - Optional - Pre-seeded config ### Return Value Post instance ### Example ```php use DigitalStars\SimpleVK\Post; $post = Post::create($vk)->text('Новость дня')->img('news.png'); ``` ``` -------------------------------- ### Callback chain method signatures (__call, a_*, b_*) Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/BaseConstructor.md Lists the public methods that implement callback chains. Any method named a_ or b_ appends an entry to the func_after_chain or func_before_chain respectively. Only callable functions are accepted; otherwise SimpleVkException(0, 'Функция ... недоступна') is thrown, and non-prefixed names throw SimpleVkException(0, 'Неверно задан префикс функции'). The run and edit chain entries require a bound Bot and dispatch to Bot::run() or Bot::editRun(). ```php public function __call($name, $arguments) public function a_sleep($time) public function b_sleep($time) public function clearChainAfter() public function clearChainBefore() ``` -------------------------------- ### buttonApp($text, $app_id, $owner_id = null, $hash = null, $payload = null) Source: https://github.com/digitalstars/simplevk-php/blob/master/_autodocs/api-reference/SimpleVK.md Creates an open-app button array for keyboard construction. ```APIDOC ## buttonApp($text, $app_id, $owner_id = null, $hash = null, $payload = null) ### Description Creates a flat button array for an open-app button, which can be used in keyboard construction via `Message::kbd()`. ### Method PHP method ### Signature `public function buttonApp($text, $app_id, $owner_id = null, $hash = null, $payload = null)` ### Parameters - **$text** (string) - Required - The button label. - **$app_id** (integer) - Required - The ID of the app to open. - **$owner_id** (integer) - Optional - The owner ID of the app. - **$hash** (string) - Optional - A hash parameter for the app. - **$payload** (mixed) - Optional - Payload data to be sent with the button. ### Returns Returns an array in the format `['open_app', $payload, $text, $app_id, $owner_id, $hash]`. ### Example ```php $button = $vk->buttonApp('Open App', 6123456, -123456, 'hash'); ``` ```