fivesquared / advanced-php-slack-bot
基于PHP编写的高级Slack机器人用户,扩展自jclg/php-slack-bot
Requires
- devristo/phpws: dev-master
- react/http: dev-master
This package is not auto-updated.
Last update: 2024-09-18 19:23:24 UTC
README
使用Slack实时消息API https://api.slack.com/rtm 编写的简单机器人用户
安装
使用Composer
创建一个新的composer.json文件并添加以下内容
{
"minimum-stability" : "dev",
"require": {
"jclg/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()); $bot->run();
示例命令
示例命令位于 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();
然后,使用 "name" 参数来触发相应的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