Skip to content

Instantly share code, notes, and snippets.

@kiuyas
Created January 8, 2017 05:19
Show Gist options
  • Save kiuyas/dfb0fd52a7f78e9ae6f3e282c90e7735 to your computer and use it in GitHub Desktop.
Save kiuyas/dfb0fd52a7f78e9ae6f3e282c90e7735 to your computer and use it in GitHub Desktop.
LINEのBotに応答させるためのPHPスクリプト
<?php
$json_string = file_get_contents('php://input');
$jsonObj = json_decode($json_string);
$userId = $jsonObj->{"events"}[0]->{"source"}->{"userId"};
$replyToken = $jsonObj->{"events"}[0]->{"replyToken"};
$message = $jsonObj->{"events"}[0]->{"message"}->{"text"};
error_log("-------------------------------------------------- hello, this is a test!");
error_log(print_r($jsonObj, true));
error_log("userId: " . $userId);
error_log("replyToken: " . $replyToken);
error_log("message: " . $message);
$post_data = array(
"replyToken" => $replyToken,
"messages" => array ( array("type" => "text", "text" => "Hello, World!"))
);
error_log("*** Following content will be posted. ***");
error_log(print_r(json_decode(json_encode($post_data)), true));
$ch = curl_init("https://api.line.me/v2/bot/message/reply");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: Bearer [チャンネルアクセストークン※LINE Developerのページで確認]'
));
$result = curl_exec($ch);
curl_close($ch);
error_log("*** Result ***");
error_log($result);
@kiuyas
Copy link
Author

kiuyas commented Jan 8, 2017

LINEのボットの Webhook URLで指定したURLで動作させるサービスのためのスクリプトです。
メッセージを受け取り、「Hello, World」という反応を返します。

16行目でセットする文言を変えれば応答変えられます。

ちゃんとしたボットに作りあげるには、相手のメッセージ($message)を解析してHello, World!の代わりに何か適切な応答メッセージを入れることになるでしょう。

@kiuyas
Copy link
Author

kiuyas commented Jan 8, 2017

参考にさせていただいたページ

■わずか5分。新LINE Messaging APIでbotを作ってみた手順全公開
https://bita.jp/dml/line-messaging-api-exp

■LINE BOT APIを利用した地獄のミサワBOTの作り方
http://qiita.com/srea/items/58ba0f7d870a6ee3da2a

■LINE Messaging API が BOT API から変わったところ。
http://qiita.com/TetsuyaImagawa/items/7517b287e68efe21c0cc

@kiuyas
Copy link
Author

kiuyas commented Jan 8, 2017

流れとしては次のような感じなんだと思います。

(1) POSTリクエストでJSONを受け取る
(2) 返答内容をJSONで作る
(3) CURLなどを利用して(2)を https://api.line.me/v2/bot/message/reply へ送りつける。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment