cedricziel/mattermost-php

Mattermost 的 PHP 绑定


README

用于构建 Mattermost 应用和集成。

安装

composer require cedricziel/mattermost-php

使用

API 客户端

API 客户端是 Mattermost API 的简单包装。它提供了一个流畅的接口来与 API 交互。

<?php

use CedricZiel\MattermostPhp\Client;
use CedricZiel\MattermostPhp\Client\Model\CreatePostRequest;

// create a client instance
$client = new Client(getenv('MATTERMOST_SITE_URL'));
// provide a token and authenticate
$client->setToken(getenv('MATTERMOST_TOKEN'));
$yourUser = $client->authenticate();

// OR authenticate with username and password
$client->authenticate($loginId, $password);

// get the team and a specific channel
$team = $client->teams()->getTeamByName(getenv('MATTERMOST_TEAM_NAME'));
$client->channels()->getAllChannels(per_page: 100);
$channel = $client->channels()->getChannelByName($team->id, 'town-square');

// create a post in the channel
$post = $client->posts()->createPost(new CreatePostRequest($channel->id, 'Hello World!'));
var_dump($post);

斜杠命令

斜杠命令是集成 Mattermost 最常见的方式之一。它们通过在 Mattermost 的消息框中输入一个斜杠后跟命令名和任何参数来调用(例如 /weather New York)。

要实现一个响应特定城市天气的斜杠命令,你可以这样做

注意: 此库建议使用 PSR-15 兼容的中间件栈来处理请求和响应。此库提供了一个 AbstractSlashCommand 类,可以扩展来实现一个处理请求所需所有功能的斜杠命令。

<?php

// your PSR-15 ServerRequestInterface implementation
$serverRequest = '...';

$slashCommand = new class('weather') extends \CedricZiel\Mattermost\SlashCommands\AbstractSlashCommand {
    public function execute(SlashCommandInput $input): SlashCommandOutput
    {
        $city = $input->getParameters();
        /**
         * Your business logic here
         */
        $weather = $this->getWeatherForCity($city);

        return SlashCommandOutput::create()
            ->setText(sprintf('The weather in %s is %s', $city, $weather));
    }
};

// handle the request. this will invoke the slash command and return a PSR-7 compatible response
$slashCommand->handle($serverRequest);

请查看测试以获取更多示例。

许可证

MIT