jonthewayne / php-slack-bot
用PHP编写的Slack机器人用户
Requires
- devristo/phpws: dev-master
- react/http: dev-master
This package is not auto-updated.
Last update: 2024-09-20 18:44:02 UTC
README
使用Slack实时消息API编写的简单机器人用户 https://api.slack.com/rtm
安装
使用Composer
创建一个新的composer.json文件并添加以下内容
{
"minimum-stability" : "dev",
"require": {
"jonthewayne/php-slack-bot": "dev-master"
}
}
然后运行
composer install
用法
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()); // pass the bot an optional custom function after which the bot exits $bot->run( function () { echo "double rainbows!"; });
示例命令
示例命令位于 src/PhpSlackBot/Command/
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 POST请求触发。
可以使用PhpSlackBot\Bot::loadWebhook方法加载自定义webhooks。
如果你需要从外部服务控制机器人,这很有用。例如,使用IFTTT https://ifttt.com/maker
要启用webhooks,请在run方法之前使用enableWebserver方法。
你还可以设置一个秘密令牌以防止未经授权的请求。
$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"}' https://:8080