botman-sk/driver-vk-for-sk-taxi

为 botman.io 框架的 VK 社区回调司机

dev-master / 1.7.x-dev 2022-04-14 04:54 UTC

This package is auto-updated.

Last update: 2024-09-14 10:18:12 UTC


README

BotMan 驱动程序,通过回调 API 连接 VK 社区与 BotMan

License: MIT Packagist

贡献

欢迎贡献,我很乐意通过 Pull Requests 接受贡献。😊 更多详情请见 贡献者 标签。

支持

驱动程序功能表

* - 使用用户令牌上传功能正在建设中

设置

获取社区 API 密钥

从社区页面,转到 管理 -> 设置标签 -> API 使用 -> 访问令牌标签。点击 创建令牌 按钮。

API usage

然后在对话框中勾选所有权限。

Dialog box with permissions

通过点击 显示 链接来复制您创建的令牌。

Firstly added API token

安装驱动程序

通过 composer 需求驱动程序

composer require yageorgiy/botman-vk-community-callback-driver

如果您使用 BotMan Studio,应在 .env 文件中定义以下属性

VK_ACCESS_TOKEN="REPLACE_ME"                    # User or community token for sending messages (from Access tokens tab, see above)
VK_SECRET_KEY="REPLACE_ME"                      # Secret phrase for validating the request sender (from Callback API tab, see above)
VK_API_VERSION=5.103                            # API version to be used for sending an receiving messages (should be 5.103 and higher) (not recommended to change)
VK_MESSAGES_ENDPOINT=https://api.vk.com/method/ # VK API endpoint (don't change it if unnecessary)
VK_CONFIRM=                                     # DEPRECATED SINCE v.1.4.2, LEAVE BLANK (EMPTY STRING) - see 'Mounting & confirming the bot' section. Confirmation phrase for VK
VK_GROUP_ID="REPLACE_ME"                        # Community or group ID
VK_USER_FIELDS=                                 # Extra user fields (see https://vk.com/dev/fields for custom fields) (leave blank for no extra fields) (note: screen_name is already included!)

如果您不使用 BotMan Studio,则应手动应用驱动程序

// ...

// Applying driver
DriverManager::loadDriver(\BotMan\Drivers\VK\VkCommunityCallbackDriver::class);

// Applying settings for driver
BotManFactory::create([
    "vk" => [
        "token" => "REPLACE_ME",                    // User or community token for sending messages (from Access tokens tab, see above)
        "secret" => "REPLACE_ME",                   // Secret phrase for validating the request sender (from Callback API tab, see above)
        "version" => "5.103",                       // API version to be used for sending an receiving messages (should be 5.103 and higher) (not recommended to change)
        "endpoint" => "https://api.vk.com/method/", // VK API endpoint (don't change it if unnecessary)
        "confirm" => "",                            // DEPRECATED SINCE v.1.4.2, LEAVE BLANK (EMPTY STRING) - see 'Mounting & confirming the bot' section. Confirmation phrase for VK
        "group_id" => "REPLACE_ME",                 // Community or group ID
        "user_fields" => ""                         // Extra user fields (see https://vk.com/dev/fields for custom fields) (leave blank for no extra fields) (note: screen_name is already included!)
    ]
]);

// ...

安装和确认机器人

⚠ [从 v.1.4.1 和更早版本迁移] 自驱动程序版本 1.4.2 以来,确认机器人的方法已更改:验证应由事件监听器管理,VK_SECRET_KEY(或 $botmanSettings["vk"]["confirm"])应为空白(空字符串)。

从社区页面,转到 管理 -> 设置标签 -> API 使用 -> 回调 API 标签

Callback API tab

  • 要返回的字符串 部分找到字符串(验证码)

Callback API tab

  • 将以下代码添加到 routes/botman.php 文件中,将 REPLACE_ME 替换为验证码(例如 1a2b3c4d5e
$botman->on("confirmation", function($payload, $bot){
    // Use $payload["group_id"] to get group ID if required for computing the passphrase.
    echo("REPLACE_ME");
});
  • 点击 确认 按钮。

快速指南及示例

在用法示例中,使用的文件是 routes/botman.php

发送简单消息

如果机器人收到 Hello 消息,它将回答 Hi, <First Name>

$botman->hears('Hello', function ($bot) {
    $bot->reply('Hi, '.$bot->getUser()->getFirstName());
});

Example image

键入活动

机器人将在回答问题前等待 10 秒

$botman->hears("What\'s your favourite colour\?", function ($bot) {
    $bot->reply('Let me think...');
    $bot->typesAndWaits(10);
    $bot->reply("I guess it's orange! 😄");
});

Example image

最后,它将回答

Example image

附加图像

如果机器人收到 Gimme some image 消息,它将带有一个附加的图像回答 Here it is!

use BotMan\BotMan\Messages\Attachments\Image;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;

$botman->hears('Gimme some image', function ($bot) {
    // Create attachment
    $attachment = new Image('https://botman.io/img/logo.png');
    // $attachment->addExtras("vk_photo", "photo123456_123456"); // Or send an already uploaded photo (driver will ignore image url)    

    // Build message object
    $message = OutgoingMessage::create('Here it is!')
        ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);
});

Example image

附加视频

发送已上传视频的示例

注意:当前驱动程序不支持将视频上传到 VK。

use BotMan\BotMan\Messages\Attachments\Video;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;

$botman->hears('Gimme some video', function ($bot) {
    // Create attachment
    $attachment = new Video('http://unused-video-url');
    // Attaching already uploaded videos is the ONLY way to send them (as for now):
    $attachment->addExtras("vk_video", "video-2000416976_41416976"); // Send an already uploaded video (driver will ignore video url)

    // Build message object
    $message = OutgoingMessage::create('Here it is!')
        ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);
});

Example image

附加音频

发送已上传音频的示例

注意:平台限制上传音频。

use BotMan\BotMan\Messages\Attachments\Audio;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;

$botman->hears('Gimme some audio', function ($bot) {
    // Create attachment
                            // URL can be uploaded ONLY as voice message (due to restrictions of VK)
    $attachment = new Audio('https://unused-audio-url');
    $attachment->addExtras("vk_audio", "audio371745438_456268888"); // Send an already uploaded audio (driver will ignore audio url and vk_as_voice parameter)

    // Build message object
    $message = OutgoingMessage::create('Here it is!')
        ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);
});

发送语音消息

可以使用具有额外参数 vk_as_voice = trueAudio 发送语音消息。

发送带文本消息的语音消息的示例

注意:最好上传 *.ogg 文件而不是 *.mp3、*.wav 等。有关更多信息,请参阅 上传语音消息

use BotMan\BotMan\Messages\Attachments\Audio;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;

$botman->hears('Sing me a song', function ($bot) {
    // Create attachment
                            // URL can be uploaded ONLY as voice message (due to restrictions of VK)
    $attachment = new Audio('https://url-to-ogg-file');
//  $attachment->addExtras("vk_audio", "audio371745438_456268888"); // Send an already uploaded audio (driver will ignore audio url and vk_as_voice parameter)
    $attachment->addExtras("vk_as_voice", true);                    // Send as voice message (better to use *.ogg file)

    // Build message object
    $message = OutgoingMessage::create('Well...')
        ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);
});

Example image

附加文档(文件)

发送文件的示例

注意:并非所有文件都可以上传。有关更多信息,请参阅 上传文档

use BotMan\BotMan\Messages\Attachments\File;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;

$botman->hears("Any files\?", function ($bot) {
    $attachment = new File('https://url-to-file');
//  $attachment->addExtras("vk_doc", "doc123456_123456"); // Send an already uploaded document (driver will ignore audio url and vk_doc_title, vk_doc_tags parameters)
    $attachment->addExtras("vk_doc_title", "Cool guy.gif"); // Title
    $attachment->addExtras("vk_doc_tags", "cool, guy"); // Document tags

    // Build message object
    $message = OutgoingMessage::create('Yep!')
        ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);
});

Example image

附加位置

发送位置的示例(来自 BotMan 文档)

use BotMan\BotMan\Messages\Attachments\Location;
use BotMan\BotMan\Messages\Outgoing\OutgoingMessage;

$botman->hears('send location', function($bot) {
    // Create attachment
    $attachment = new Location(61.766130, -6.822510, [
        'custom_payload' => true,
    ]);

    // Build message object
    $message = OutgoingMessage::create('This is my text')
        ->withAttachment($attachment);

    // Reply message object
    $bot->reply($message);
});

附加参数

附加参数用于追加或替换消息请求参数。

注意: vaccess_token 字段将被忽略以替换。请在 .env 文件或配置数组中更改它们的参数。

替换消息文本的示例

$botman->hears('Show me the replaced message', function($bot) {
    $bot->reply("This string will be ignored", [
        "message" => "This message string will be sent"
    ]);
});

The result

有关更多信息,请参阅 messages.send 方法

发送问题按钮(简单键盘)

发送简单键盘的示例。通过向问题添加按钮,键盘将显示为 one_time = true(仅显示一次)和 inline = false(默认非内联键盘),一行一个按钮。有关更深入的设置,请参阅 发送完全支持键盘 部分。

use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use BotMan\BotMan\Messages\Outgoing\Question;
$botman->hears("List of functions\?", function ($bot) {
    $question = Question::create('My list of functions:')
        ->addButtons([
            Button::create('Function 1')->value('f1'),
            Button::create('Function 2')->value('f2'),
            Button::create('Function 3')->value('f3'),
            Button::create('Function 4')->value('f4'),
            Button::create('Function 5')->value('f5')
        ]);

    $bot->ask($question, function ($answer) {
        // Detect if button was clicked:
        if ($answer->isInteractiveMessageReply()) {
            $selectedValue = $answer->getValue(); // Contains button value e.g. 'f1', 'f2', ...
            $selectedText = $answer->getText(); // Contains title e.g. 'Function 1', 'Function 2', ...
        }
    });
});

Example image

注意: 不要使用 $answer->getText() 进行验证,因为它可以被客户端(用户)更改。请改用 $answer->getValue()

注意: 更好地在 Conversation 类中发送键盘,用按钮询问问题。更多信息请参见 这里

自定义问题按钮(简单键盘)

⚠ [从 v.1.4.x 及更早版本迁移] 驱动器现在忽略了 __x__y 字段。请使用 VKKeyboard 序列化类来构建键盘,并将其添加到您的输出消息的 $additionalParameters 中。

您还可以通过附加参数(如颜色)更改按钮的属性。

//...
$botman->hears("List of functions\?", function ($bot) {
    $question = Question::create('My list of functions:')
        ->addButtons([
            Button::create('Function 1')->value('f1')->additionalParameters([
                "color" => "secondary" // Colour (see available colours here - https://vk.com/dev/bots_docs_3)
            ]),
            Button::create('Function 2')->value('f2')->additionalParameters([
                "color" => "negative"
            ]),
            Button::create('Function 3')->value('f3')->additionalParameters([
                "color" => "primary"
            ]),
            Button::create('Function 4')->value('f4')->additionalParameters([
                "color" => "primary"
            ]),
            Button::create('Function 5')->value('f5')->additionalParameters([
                "color" => "primary"
            ])
        ]);

    $bot->ask($question, function ($answer) {
        //...
    });
});

Example image

请参阅 VK 文档页面 了解可用的颜色、类型和其他功能。只需在附加参数数组中添加新字段,就像上面的示例中所示。

发送本地键盘

本地键盘可以作为附加参数发送 (仅适用于 VK!)

use BotMan\Drivers\VK\Extensions\VKKeyboard;
use BotMan\Drivers\VK\Extensions\VKKeyboardButton;
use BotMan\Drivers\VK\Extensions\VKKeyboardRow;

$botman->hears('keyboard', function(BotMan $bot) {
    $keyboard = new VKKeyboard();
    $keyboard->setInline(false);    // Setting the inline mode ("inline" parameter)
    $keyboard->setOneTime(false);   // Setting "one_time" parameter
    
    $keyboard->addRows(
        // Top row
        new VKKeyboardRow([
            // Text example
            ( new VKKeyboardButton() )->setColor("primary")->setText("Sample text")->setValue("button1"),
            // UTF-8 text example
            ( new VKKeyboardButton() )->setColor("primary")->setText("Текст для примера")->setValue("button2"),
        ]),
        // Middle row
        new VKKeyboardRow([
            // Long text trim example
            ( new VKKeyboardButton() )
                // Colour (see available colours here - https://vk.com/dev/bots_docs_3)                
                ->setColor("default")
                
                // Long text will be trimed with ellipsis at the end of the label
                ->setText("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam nec ultrices purus, ut sollicitudin arcu.")

                // Set button value
                ->setValue("button3"), 
        ]),
        // Bottom row
        new VKKeyboardRow([
            // Emoji example
            ( new VKKeyboardButton() )->setColor("negative")->setText("")->setValue("button4"),
            ( new VKKeyboardButton() )->setColor("primary")->setText("")->setValue("button5"),
            ( new VKKeyboardButton() )->setColor("positive")->setText("")->setValue("button6"),
        ])
    );

    $bot->reply("Native keyboard:", [
        "keyboard" => $keyboard->toJSON()
    ]);
});

Example image

您还可以发送带有键盘的附加参数问题。

// ...
$bot->ask($question, function ($answer) {
    // Detect if button was clicked:
    if ($answer->isInteractiveMessageReply()) {
        $selectedValue = $answer->getValue(); // Contains button value e.g. 'f1', 'f2', ...
        $selectedText = $answer->getText(); // Contains title e.g. 'Function 1', 'Function 2', ...
    }
}, [
    "keyboard" => $keyboard->toJSON()
]);
// ...

监听图片

接收图片的本地方式。

注意: 通过 receivesImages() 方法不会提供消息文本。

$botman->receivesImages(function($bot, $images) {
    foreach ($images as $image) {
        $url = $image->getUrl(); // The direct url
        $title = $image->getTitle(); // The title (empty string as titles are not supported by VK)
        $payload = $image->getPayload(); // The original payload

        $bot->reply("Detected image: {$url}");
    }
});

Example image

监听视频

接收视频的本地方式。

注意: 通过 receivesVideos() 方法不会提供消息文本。

$botman->receivesVideos(function($bot, $videos) {
    foreach ($videos as $video) {
        $url = $video->getUrl(); // The direct url
        $payload = $video->getPayload(); // The original payload

        // For YouTube videos title can be accessed in the following way:
        $bot->reply("Detected video: {$payload["title"]}");
    }
});

Example image

监听音频

接收音频的本地方式。

注意: 通过 receivesAudio() 方法不会提供消息文本。

$botman->receivesAudio(function($bot, $audios) {
    foreach ($audios as $audio) {
        $url = $audio->getUrl(); // The direct url
        $payload = $audio->getPayload(); // The original payload

        $bot->reply("Detected audio: {$url}");
    }
});

Example image

监听文档(文件)

接收文件的本地方式。

注意: 通过 receivesFiles() 方法不会提供消息文本。

$botman->receivesFiles(function($bot, $files) {
    foreach ($files as $file) {
        $url = $file->getUrl(); // The direct url
        $payload = $file->getPayload(); // The original payload

        $bot->reply("Detected file (document): {$url}");
    }
});

Example image

监听位置

接收位置的本地方式。

注意: 通过 receivesLocation() 方法不会提供消息文本。

$botman->receivesLocation(function($bot, $location) {
    $lat = $location->getLatitude();
    $lng = $location->getLongitude();

    $bot->reply("Detected location: $lat $lng");
});

Example image

接收混合附件的消息

可以通过 hears()ask()fallback() 方法(带有消息文本和所有支持类型附件的 IncomingMessage)询问带有混合附件的消息。

带有视频和图片附件的示例

$botman->hears('I have both image and video for you.', function ($bot) {
    $bot->reply("Cool!");

    // Scanning for images
    $images = $bot->getMessage()->getImages() ?? [];
    foreach ($images as $image) {

        $url = $image->getUrl();

        $bot->reply("Image found: {$url}");
    }

    // Scanning for videos
    $videos = $bot->getMessage()->getVideos() ?? [];
    foreach ($videos as $video) {
        $payload = $video->getPayload();

        $bot->reply("Video found: {$payload["title"]}");
    }
});

Example image

检索额外用户数据

应在 .env 文件中定义额外的用户字段,并且可以通过 getUser()->getInfo() 方法访问。

⚠ [从 v.1.5.x 及更早版本迁移] 驱动器现在也使用 screen_name。请从 user_fields 参数中删除 screen_name 值,以防止发送两次 screen_name。请使用 $bot->getUser()->getUsername() 来获取用户名。

.env 文件的示例内容

# ...
VK_USER_FIELDS="photo_200_orig"
# ...

示例路由

$botman->hears('Gimme my photo_200_orig', function ($bot) {
    $bot->reply('Here it is: '.$bot->getUser()->getInfo()["photo_200_orig"]);
});

Example image

多个字段应以逗号分隔

# ...
VK_USER_FIELDS="photo_200_orig, photo_50"
# ...

请参阅 用户对象 了解可用的字段。

检索额外客户端信息

有关用户 VK 客户端支持的功能的信息可以通过 $bot->getMessage()->getExtras("client_info") 访问。

注意: 此功能仅适用于新消息(message_new 事件)。

$botman->hears('my info', function(BotMan $bot) {
    // Prints raw "client_info" array
    $bot->reply(print_r($bot->getMessage()->getExtras("client_info"), true));
});

The reply

请参阅用户可用的功能信息以获取更多详情。

标记已读示例

即使没有对消息的响应,每条消息也会被标记为已读

$botman->hears("Don\'t answer me", function ($bot) {
    // Do nothing
});

Example image

监听事件

支持的事件列表

  • 确认
  • 消息允许
  • 消息拒绝
  • 消息输入状态 *
  • 消息事件 *
  • 照片新
  • 照片评论新
  • 照片评论编辑
  • 照片评论恢复
  • 照片评论删除
  • 音频新
  • 视频新
  • 视频评论新
  • 视频评论编辑
  • 视频评论恢复
  • 视频评论删除
  • 墙贴新
  • 墙贴转发
  • 墙贴回复新
  • 墙贴回复编辑
  • 墙贴回复恢复
  • 墙贴回复删除
  • 版块帖子新
  • 版块帖子编辑
  • 版块帖子恢复
  • 版块帖子删除
  • 市场评论新
  • 市场评论编辑
  • 市场评论恢复
  • 市场评论删除
  • 市场订单新 *
  • 市场订单编辑 *
  • 群组离开
  • 群组加入
  • 用户封禁
  • 用户解封
  • 投票新
  • 群组官员编辑
  • 群组更改设置
  • 群组更改照片
  • vkpay交易 *
  • 应用有效载荷 *
  • 点赞添加 *
  • 点赞移除 *

* - 在VK文档中缺少英文版本,但功能存在(截至2020年8月14日)

** - 在VK文档中不存在,但功能存在(截至2020年8月14日)

注意: message_newmessage_replymessage_edit事件可以通过监听消息的功能进行访问(例如$botman->hear())。

事件完整列表(VK文档)

当输入状态更改时发送消息的示例

$botman->on("message_typing_state", function($payload, $bot){
    // $payload is an array of the event object ("Object field format"),
    // excepting Confirmation event, where $payload contains full root JSON schema.
    // See https://vk.com/dev/groups_events for more info
    $bot->say("Hey! You're typing something!", $payload["from_id"]);
});

注意: 不支持使用$bot->reply(),请使用$bot->say("...", $peer_id_from_data)代替。

结果

The result image

发送低级别API请求

通过$bot->sendRequest()发送贴纸的示例

注意: 还可以通过附加参数发送贴纸。

$botman->hears('sticker', function($bot) {
    // API method
    $endpoint = "messages.send";
    
    // Arguments ("v" and "access_token" are set by driver, no need to define)
    $arguments = [
         "peer_id" => $bot->getUser()->getId(), // User ID
         "sticker_id" => 12, // Sticker ID
         "random_id" => rand(10000,100000) // Random ID (required by VK API, to prevent doubling messages)
    ];

    $test = $bot->sendRequest($endpoint, $arguments);
    // $test now equals to ["response" => 1234];
});

结果

The result of sticker sending

另请参阅

许可证

VK社区回调驱动程序是在MIT许可条款下制作的。BotMan是免费软件,根据MIT许可条款分发。