semako/php-slack-bot

用PHP编写的Slack机器人用户

1.0.0 2017-03-15 09:42 UTC

This package is auto-updated.

Last update: 2024-09-07 22:09:56 UTC


README

一个使用Slack实时消息API(https://api.slack.com/rtm)编写的简单机器人用户

安装

使用Composer

创建一个新的composer.json文件,并添加以下内容

{
    "minimum-stability" : "dev",
    "require": {
        "jclg/php-slack-bot": "dev-master"
    }
}

然后运行

composer install

用法

创建一个名为bot.php的PHP文件,内容如下

require 'vendor/autoload.php';
use PhpSlackBot\Bot;

// Custom command
class MyCommand extends \PhpSlackBot\Command\BaseCommand {

    protected function configure() {
        $this->setName('mycommand');
    }

    protected function execute($message, $context) {
        $this->send($this->getCurrentChannel(), null, 'Hello !');
    }

}

$bot = new Bot();
$bot->setToken('TOKEN'); // Get your token here https://my.slack.com/services/new/bot
$bot->loadCommand(new MyCommand());
$bot->loadInternalCommands(); // This loads example commands
$bot->run();

然后在命令行(终端)中运行php bot.php

示例命令

示例命令位于src/PhpSlackBot/Command/,可以使用$bot->loadInternalCommands();加载

Ping Pong命令

在频道中输入ping,机器人应该回答"Pong"给你。

计数命令

在频道中多次输入count,机器人应该回答1然后2...

日期命令

在频道中输入date,显示当前日期。

规划扑克命令

https://en.wikipedia.org/wiki/Planning_poker

在公共频道中输入pokerp start与您的团队一起开始规划扑克会议。

通过pokerp vote number直接向机器人发送消息。机器人将记录您的投票。

输入pokerp status以查看会议的当前状态(谁已经投票)。

在公共频道中输入pokerp end,机器人将输出每个投票。

加载自己的命令

您可以通过实现\PhpSlackBot\Command\BaseCommand来加载自己的命令。

然后为每个要加载的命令调用PhpSlackBot\Bot::loadCommand方法。

"捕获所有"命令

如果需要在事件发生时执行命令,您可以设置一个"捕获所有"命令。

这个特殊命令将在所有事件上触发。

require 'vendor/autoload.php';
use PhpSlackBot\Bot;

// This special command executes on all events
class SuperCommand extends \PhpSlackBot\Command\BaseCommand {

    protected function configure() {
        // We don't have to configure a command name in this case
    }

    protected function execute($data, $context) {
        if ($data['type'] == 'message') {
            $channel = $this->getChannelNameFromChannelId($data['channel']);
            $username = $this->getUserNameFromUserId($data['user']);
            echo $username.' from '.($channel ? $channel : 'DIRECT MESSAGE').' : '.$data['text'].PHP_EOL;
        }
    }

}

$bot = new Bot();
$bot->setToken('TOKEN'); // Get your token here https://my.slack.com/services/new/bot
$bot->loadCatchAllCommand(new SuperCommand());
$bot->run();

传入的webhooks

机器人还可以监听传入的webhooks。

命令由Slack中的用户消息触发,而webhooks则由web帖子请求触发。

可以使用PhpSlackBot\Bot::loadWebhook方法加载自定义webhooks。

如果您需要从外部服务控制机器人,这很有用。例如,使用IFTTT https://ifttt.com/maker

要启用webhooks,请在run方法之前使用enableWebserver方法。

您还可以设置一个密钥令牌以防止未经授权的请求。

$bot->loadInternalWebhooks(); // Load the internal "output" webhook
$bot->enableWebserver(8080, 'secret'); // This will listen on port 8080
$bot->run();

然后,使用参数"名称"触发相应的webhook

curl -X POST --data-urlencode 'auth=secret' --data-urlencode 'name=output' --data-urlencode 'payload={"type" : "message", "text": "This is a message", "channel": "#general"}' http://localhost:8080