Skip to content

Instantly share code, notes, and snippets.

@kenzo0107
Last active April 27, 2016 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenzo0107/9cc3245b57308aeadff61d3c76413f6b to your computer and use it in GitHub Desktop.
Save kenzo0107/9cc3245b57308aeadff61d3c76413f6b to your computer and use it in GitHub Desktop.
<?php
class LineBotApi {
/* 設定箇所 start */
const CHANNEL_ID = 'xxxxxxxxxx';
const CHANNEL_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const MID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
/* 設定箇所 end */
private $requestContent;
public function __construct() {
$requestBodyString = file_get_contents('php://input');
$requestBodyObject = json_decode($requestBodyString);
$this->requestContent = $requestBodyObject->result{0}->content;
}
public function main() {
// Line上で入力した文字
$requestText = $this->requestContent->text;
// Line上で入力したコンテンツタイプ(1:テキスト)
$contentType = $this->requestContent->contentType;
$message = self::getMessage($requestText);
// Line Bot Api 実行.
self::executeLineBotApi($message);
}
private function getMessage($requestText) {
if (empty($requestText)) {
return;
}
$message = 'hello';
if ( $requestText == 'perfect' ) {
$message = 'human!';
}
return $message;
}
// LINE BOT API へのリクエストを作成して実行
private function executeLineBotApi($message) {
if (empty($message)) {
return;
}
$headers = self::getHeaders();
error_log('$headers:' . print_r($headers,true));
$requestFrom = $this->requestContent->from;
$responseMessage = <<< EOM
{
"to":["{$requestFrom}"],
"toChannel":1383378250,
"eventType":"138311608800106203",
"content":{
"contentType":1,
"toType":1,
"text":"{$message}"
}
}
EOM;
$curl = curl_init('https://trialbot-api.line.me/v1/events');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $responseMessage);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
}
// line bot api 送信用 headers
private function getHeaders() {
return array(
"Content-Type: application/json; charset=UTF-8",
"X-Line-ChannelID: ".self::CHANNEL_ID,
"X-Line-ChannelSecret: ".self::CHANNEL_SECRET,
"X-Line-Trusted-User-With-ACL: ".self::MID,
);
}
}
// api実行
$LineBotApi = new LineBotApi();
$LineBotApi->main();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment