tudor2004/google-bot-laravel

Laravel 的 Google Chat Bot

v0.1.0 2017-12-15 21:02 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:01:40 UTC


README

本包允许您处理通过新的 Google Chat Web 客户端触发的 Google Chat Bot 命令。您可以为每个机器人注册多个自定义命令。

要求

Laravel 5

安装

使用 Composer 包管理器安装此包。在项目根目录中运行以下命令

composer require tudor2004/google-bot-laravel

之后,在为每个已注册的机器人创建新的 Google Chat Web 客户端的出站 webhook。

Laravel 5

如果您允许包发现,则无需执行任何操作。此包会注册自己的服务提供者和 GoogleBot 外观。

否则,首先将服务提供者添加到 config/app.php 中的 providers 数组中

'providers' => [
  Tudorica\GoogleBot\GoogleBotServiceProvider::class,
],

然后添加外观到您的 aliases 数组

'aliases' => [
  ...
  'GoogleBot' => Tudorica\GoogleBot\Facades\GoogleBotFacade::class,
],

使用方法

在您成功创建出站 webhook 后,创建一个控制器来响应 webhook 调用。Google Chat 会推送事件,然后由注册的机器人处理。

请注意,如果您在命名空间中使用外观(例如 Laravel 5 中的 App\Http\Controllers),则需要在上面的类中 use GoogleBot 来导入它,或者在使用方法时直接访问根命名空间,例如 \GoogleBot::run($botClass, $data)

// Handle commands for a custom 'audio' bot. We pass all the request data that the Google Chat event sends us.
namespace App\Http\Controllers;

class WebhookController extends Controller
{
    public function webhook(Request $request)
    {
        try {        
            
            return GoogleBot::run(AudioBot::class, $request->all());
            
        } catch(BotException $ex) {
            return [
                'text' => 'Something wrong happend';
            ];
        }             
    }
}

注册机器人

每个机器人必须实现此包中提供的 BotContract 接口。该接口要求您定义 name()commands() 方法。

namespace App\Bots;
 
use Tudorica\GoogleBot\Contracts\BotContract;
 
class AudioBot extends BotContract
{
     public function name(): string
     {
         return 'Radio';
     }
 
     public function commands(): array
     {
         return [             
             AudioVolume::class             
         ];
     }
}

注册命令

如前例所示,每个机器人可以注册多个命令。每个命令都必须实现 CommandContract 接口,该接口要求您定义 allowedUsers()name()description()handle() 方法。

namespace App\Commands;
 
use Tudorica\GoogleBot\Contracts\CommandContract;
 
class AudioVolume implements CommandContract
{
    /**
     * You can here define a list of users that can perform this command. Use [*] to allow everyone.
     */ 
    public function allowedUsers(): array
    {
        return ['*'];
    }

    /**
     * Define here the command name. You can also use here regular expressions.
     */
    public function name(): string
    {
        return '!audio volume (.+)';
    }

    /**
     * This description message will be used for the help.
     */
    public function description(): string
    {
        return 'Set volume.';
    }

    /**
     * The handler the executes the command. This has to respond with a string, that will be in the end be returned in the chat room.
     */
    public function handle(string $command): string
    {
        // Some logic for turning the volume of your speakers up or down...

        return 'Ok, volume is now ' . $volume . '.';
    }
}