Skip to content

Instantly share code, notes, and snippets.

@yokozawa

yokozawa/chatwork_api.php

Last active Aug 29, 2015
Embed
What would you like to do?
<?php
header('Content-type: application/json; charset=utf-8');
$api_token = "your chatwork api token";
$room_id = "your target room id";
$url = "https://api.chatwork.com/v1/rooms/$room_id/messages";
// committer name(on github) => chatwork id
$members = array(
'yokozawa' => '111111',
'foo' => '222222',
'var' => '333333',
);
// prepare upload images to target room
// http://takashabe.hatenablog.com/entry/2014/01/18/162533 @see
$success_img_id = 'success img id';
$failure_img_id = 'failure img id';
function draw_reviewer ($members, $expect_key) {
unset($members[$expect_key]);
$target_key = array_rand($members, 1);
return array($target_key, $members[$target_key]);
}
// travis payload format look this.
// https://gist.github.com/svenfuchs/1225015
function create_message($payload, $members) {
$title = $payload['status'] === 0 ? "にっこにこにー!" : "ヴェェェ";
$build_url = "https://magnum.travis-ci.com/" . $payload['repository']['owner_name']
. "/" . $payload['repository']['name'] . "/builds/" . $payload['id'];
$commit_url = $payload['repository']['url'] . "/commit/" . $payload['commit'];
$committer = $payload['committer_name'];
if ($payload['status'] === 0) {
list($name, $id) = draw_reviewer($members, $committer);
$message =<<<EOF
[info][title]{$title}[/title]
あなたのbuildに、にっこにっこにー!笑顔届ける矢澤にこにー!
レビューは[To:{$id}] {$name} にお願いしちゃおうかな!
[To:{$members[$committer]}] {$committer} はレビュー後にmergeとdeployを忘れないでね!
[preview id={$success_img_id} ht=150]
[/info]
EOF;
} else {
$message =<<<EOF
[info][title]{$title}[/title]
build失敗しちゃったじゃない!イミワカンナイ!
[To:{$members[$committer]}] {$committer} はちゃんと確認するのよ!ハヤクシナサイヨ!
build_url: {$build_url}
commit_url: {$commit_url}
[preview id={failure_img_id} ht=150]
[/info]
EOF;
}
return $message;
}
if ('POST' === $_SERVER['REQUEST_METHOD']) {
if (!isset($_POST['payload'])) {
header('HTTP/1.1 400 Bad Request');
exit;
}
$payload = json_decode($_POST['payload'], true);
$data = array('body' => create_message($payload, $members));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-ChatWorkToken: ' . $api_token));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.