hampel / hipchat-notify
使用 Guzzle 实现 HipChat API v2 的 Room Notification 方法的包装器
Requires
- php: >=5.5.0
- guzzlehttp/guzzle: ~6.0
- hampel/json: ~2.0
Requires (Dev)
- mockery/mockery: ^0.9
- phpunit/phpunit: ~4.0
README
使用 Guzzle v6 实现的 HipChat API 包装器,它实现了一个简单的 room 通知接口,并设计用于与 room 授权令牌一起使用。
由 Simon Hampel 提供。
安装
推荐通过 Composer 安装 HipChat Notifier。
:::json
{
"require": {
"hampel/hipchat-notify": "~1.0"
}
}
配置
要使用 HipChat Notifier,您需要使用 HipChat Group 管理区域生成 room 授权令牌。
登录 HipChat 并转到 Group admin
。
接下来,转到 Rooms
区域,找到(或创建)一个将发送通知的房间。点击列表中的该房间以编辑设置。
在房间详情的右侧将有一个 Tokens
链接 - 点击此链接以查看为此房间定义的任何现有令牌的列表。
通过输入标签并点击 Create
创建新的令牌。
请注意,标签将显示为使用通知器发送消息的用户,因此请选择有意义的名称。如果需要,您可以创建多个标签为不同的通知源。
一旦您有了令牌,请记下令牌字符串 - 每次我们需要 <room_access_token>
时您都需要使用它。
您还需要在摘要页面上记下 room API ID,尽管您可以直接使用 API 获取它 - 但是将其存储在配置设置中可能更好,以避免不必要的 API 网络调用。
使用方法
消息
HipChat 消息由四个元素组成 - 消息内容、在 HipChat 客户端显示的关联背景颜色、一个布尔切换,指示是否通知用户关于该消息,以及指示消息内容格式的指示器(文本 vs html)。
要创建消息,请使用 HipChat\Message
类
:::php
<?php
use HipChat\Message;
$message = new Message('message to be posted', Message::COLOR_GREEN, true, Message::FORMAT_TEXT);
var_dump($message->toJson());
?>
使用此类创建的消息是不可变的 - 一旦创建,就不能更改,除非创建新的对象。
对于简单消息,已创建了两个静态辅助程序,它们使用默认设置(黄色背景颜色,不通知)。
:::php
<?php
use HipChat\Message;
$message = Message::createHtml('<strong>html</strong> message to be posted');
var_dump($message->toJson());
$message = Message::createText('text message to be posted - can use @mentions');
var_dump($message->toJson());
?>
消息上的 toJson()
调用的 JSON 输出将适合发送到 HipChat API 的格式。
通知器
通知器负责通过 Guzzle 与 API 进行通信的所有工作。
要使用通知器,您首先需要创建一个 Guzzle 客户端并将通知器配置传递给它,这设置了客户端的基本 URL。使用 Notifier::getConfig()
检索配置数组。
:::php
<?php
use GuzzleHttp\Client;
use HipChat\Message;
use HipChat\Notifier;
$client = new Client(Notifier::getConfig());
// use the room access token created in the HipChat admin area
$hipchat = new Notifier($client, '<room_access_token>');
$message = new Message('message to be posted', Message::COLOR_GREEN, true, Message::FORMAT_TEXT);
// send our message to the room with this ID
$hipchat->send($message, '123456');
?>
一些快捷方式和技巧
:::php
// static factory for creating a Notifier with client automatically
$hipchat = Notifier::make('<room_access_token>');
// get the room ID that this room access token is allowed to post to via the API
$roomid = $hipchat->getRoomId();
// get the full session details and use that to get the room id and room name with only a single API call
$session = $hipchat->getSession();
$roomid = $hipchat->getRoomId($session);
$roomname = $hipchat->getRoomName($session)
异常处理
:::php
try
{
$hipchat->send($message, '123456');
}
catch (HipChatException $e)
{
echo $e->getMessage();
$response = $e->getResponse();
if (!is_null($response))
{
// examine the response in more detail
}
}