LINE Bot流行ってますね
ビジネスアカウントの機能制限版なのに、みなさん嬉しそうでなによりです
ということで流行に便乗してLINE Bot作ってみた
Botに話しかけた内容を保存しておいて、他人の発言内容をランダムにチラ見せ
ほぼ拾ったコードのツギハギ
発言の保存するのにDB使ったけど、SSL証明書用意する手間に比べたら楽だよね
ソース
<?php
$json_string = file_get_contents('php://input');
$jsonObj = json_decode($json_string);
$to = $jsonObj->{"result"}[0]->{"content"}->{"from"};
$text = $jsonObj->{"result"}[0]->{"content"}->{"text"};
$url = "https://trialbot-api.line.me/v1/profiles?mids={$to}";
$headers = array(
'X-Line-ChannelID: xxxx',
'X-Line-ChannelSecret: xxxx',
'X-Line-Trusted-User-With-ACL: xxxx'
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$profileJson = curl_exec($curl);
//スタンプとか無視するためにtextに値があることをチェック
if($text != ""){
$profile = json_decode($profileJson);
$name = $profile->{"contacts"}[0]->{"displayName"};
$mid = $profile->{"contacts"}[0]->{"mid"};
$pdo = new PDO();// DB接続的な何か
$sql = 'select * from log_line_bot order by id desc limit 50';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$arr_res = array();
while($row = $stmt -> fetch(PDO::FETCH_ASSOC)) {
if($row['mid'] != $mid){//自分以外 SQLで絞り込まないのはインデックス面倒だから
$arr_res[] = $row;
}
}
$sql = 'insert into log_line_bot (mid,name,msg) values (?, ?, ?)';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($mid,$name, $text));
if(count($arr_res) > 0){
$res = $arr_res[array_rand($arr_res,1)];
$res_text = "{$res['name']}がさっき「{$res['msg']}」って言ってましたよ";
$response_format_text = array('contentType'=>1,"toType"=>1,"text"=>$res_text);
$post_data = array("to"=>array($to),"toChannel"=>"1383378250","eventType"=>"138311608800106203","content"=>$response_format_text);
$ch = curl_init("https://trialbot-api.line.me/v1/events");
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; charser=UTF-8',
'X-Line-ChannelID: xxx',
'X-Line-ChannelSecret: xxx',
'X-Line-Trusted-User-With-ACL: xxx'
));
$result = curl_exec($ch);
curl_close($ch);
}
}
テーブル定義
create table log_line_bot( id INT NOT NULL AUTO_INCREMENT, mid CHAR(64) NOT NULL, name VARCHAR(255) NOT NULL, msg VARCHAR(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB;




