alexkargin/msteams-bot-php

Microsoft Teams Bot API 的 PHP 封装

v1.0.1 2021-05-10 20:44 UTC

This package is auto-updated.

Last update: 2024-09-11 22:58:34 UTC


README

一个简单的 PHP 库,用于创建 Microsoft Teams 机器人

要求

  • PHP 7.4
  • 此包使用 Guzzle 客户端 进行 API 请求

入门

安装

使用 composer 安装

composer require alexkargin/msteams-bot-php

创建机器人

Teams App Studio 中创建一个新的机器人。

在此步骤中,您应该能够获得机器人 ID 和密码。

基本用法

include __DIR__ . '/vendor/autoload.php';

use TeamsBot\Bot;
use TeamsBot\Exception\TeamsBotException;
use TeamsBot\Exception\TeamsBotTokenException;

try {
    $bot = new TeamsBot\BotListener('bot_id', 'password');

    // Handled on any request
    $bot->onAny(static function (Bot $bot) {
        // Sends a simple text message
        if(!empty($bot->context->getText())) {
            $bot->reply('You send ' . $bot->context->getText());
        }                     
    });

    // Handled when user add bot
    $bot->onStartPersonalChat(static function (Bot $bot) {
        // Sends a simple text message
        $bot->reply('Hi, ' . $bot->context->getFromName());                    
    });

    // Handled when user sends 'test' to bot
    $bot->onText('test', function (Bot $bot) {
        // create Activity
        $message = $bot->createMessage();
        // add Hero Card
        $att = new TeamsBot\Card\HeroCard();
        $att->setContentFromJson('
{
"buttons": [
    {
        "type": "messageBack",
        "text": "Send request to bot",
        "value": "{\"property\": \"propertyValue\" }"
   }
]
}
        ');
        $message->addAttachment($att);
        // send new message
        $bot->postMessage($message);
    });

    // Handled when user send form to bot
    // for example, Hero Card from previous handler
    $bot->onSubmitForm(function (Bot $bot) {
        $message = $bot->createMessage();
        $message->setText('Received data: ' . json_encode($bot->context->getFormData(), JSON_THROW_ON_ERROR));
        // update Activity with form
        $bot->updateMessage($message);
    });

} catch (TeamsBotException $e) {
} catch (TeamsBotTokenException $e) {

}

重要!验证传入请求

此包不包含验证传入请求的方法。您可以根据 文档 实现此检查,或使用不同的检查方法。例如,将秘密值添加到处理器地址并检查它。

令牌缓存

默认情况下,每个机器人实例都会收到一个新的令牌来发送消息。为了加快消息发送速度,可以将令牌缓存 N 秒。例如,使用 Stash

安装包

composer require tedivm/stash

并使用它

    $bot = new TeamsBot\BotListener('bot_id', 'password');
    // use filesystem driver
    $pool = new Stash\Pool(new Stash\Driver\FileSystem([]));
    $item = $pool->getItem('token');
    $token = $item->get();
    if($item->isMiss())
    {
        // get new token
        $token = $bot->token->get();
        // Cache expires $token['expires_in']
        $expiration = new DateTime('@'.$token['expires_in']);
        $item->expiresAfter($expiration);
        $item->set($token);
        $pool->save($item);
    }

    // set token
    $bot->token->set($token);