polyskalov/botman-viber-driver

BotMan的Viber驱动程序

v1.1 2020-06-14 21:44 UTC

This package is auto-updated.

Last update: 2024-09-16 18:23:03 UTC


README

使用BotMan连接Viber

Latest Version on Packagist

安装与设置

首先,您需要引入Viber驱动程序。

composer require polyskalov/botman-viber-driver

然后,在创建BotMan实例之前加载驱动程序(仅当您不使用BotMan Studio时)

DriverManager::loadDriver(\TheArdent\Drivers\Viber\ViberDriver::class);

// Create BotMan instance
BotManFactory::create($config);

此驱动程序需要有效的安全URL来设置webhook并接收来自聊天用户的的事件和信息。这意味着您的应用程序应通过HTTPS URL访问。

要将BotMan与您的Viber机器人连接,您首先需要按照官方指南创建您的Viber机器人和访问令牌。

一旦您获得了访问令牌,将其放置在您的.env文件中,例如VIBER_TOKEN=YOUR-VIBER-TOKEN-HERE。然后它会自动加载到您的config/botman/viber.php文件中。

如果您不使用BotMan Studio,请将这些行添加到您从BotManFactory创建对象时传递的$config数组中。

'viber' => [
    'token' => 'YOUR-VIBER-TOKEN-HERE',
]

注册您的Webhook

为了让您的Viber机器人知道如何与您的BotMan机器人通信,您必须将BotMan运行时的URL在Viber上注册。

您可以通过向以下URL发送POST请求来实现此操作

https://chatapi.viber.com/pa/set_webhook

此POST请求需要一个名为url的参数,该参数指向您的BotMan逻辑/控制器所在的URL。如果您使用BotMan Studio,它将是:https://yourapp.domain/botman。出于安全原因,HTTPS是必需的。

{
   "url":"https://my.host.com",
   "event_types":[
      "delivered",
      "seen",
      "failed",
      "subscribed",
      "unsubscribed",
      "conversation_started"
   ],
   "send_name": true,
   "send_photo": true
}

您可以在官方文档中了解请求中的其他字段。

除了手动向Viber发送请求外,您还可以使用控制台命令来注册您的Webhook。

php artisan botman:viber:register

示例

<?php

/** @var \BotMan\BotMan\BotMan $botman */
$botman = resolve('botman');

$botman->on(
    'conversation_started',
    static function (array $payload, BotMan $bot) {
        $bot->reply('Hi, ' . $bot->getUser()->getUsername());
    }
);

$botman->hears('hi', static function (BotMan $bot) {
    $bot->reply('👋');
});

$botman->fallback(static function (BotMan $bot) {
    $bot->reply('I do not understand');
});

$botman->listen();