暑い日が続いています、夕立になった後のアスファルトの匂いを嗅ぐと夏だなぁって思うのは自分だけでしょうか?
さてLINE messaging apiでブログの配信通知するプログラムコードを書きましたのでお裾分けします?、コードはいつもの通りコメントなんてものはありません。この2つのコードは何をしているのかだけ、解説しますね。
1つ目のコードは私のLINEチャンネルを友だち追加してくれたら、データベースにuseridを登録するコードです。解除したらuseridの削除もちゃんとしています。
2つ目のコードは私のLINEチャンネルに登録してくれた方々に最新の記事を送信しています。自分は毎日、9時に最新の記事を送信するようにcron登録しました。
一部、defineを設定している部分がありますのでコードに追加してください、よろしくお願いします?
※LINEチャンネル登録よろしくお願いします。
<?php
class line{
function webhook($webhook_object=null){
if(!$webhook_object)return false;
$obj = json_decode($webhook_object);
$type = $obj->events[0]->type;
$userId = $obj->events[0]->source->userId;
$replyToken = $obj->events[0]->replyToken;
if($type==="follow"){
$pdo = self::db();
if($pdo){
$sql = "insert into user (userid)values(:userid)";
$sth = $pdo->prepare($sql);
$sth->bindValue(":userid",$userId,PDO::PARAM_STR);
$sth->execute();
}
}
if($type==="unfollow"){
$pdo = self::db();
if($pdo){
$sql = "delete from user where userid = :userid";
$sth = $pdo->prepare($sql);
$sth->bindValue(":userid",$userId,PDO::PARAM_STR);
$sth->execute();
}
}
if($type==="message"){
}
}
function db(){
try {
$pdo = new PDO(DSN,USERNAME,PASSWORD);
return $pdo;
} catch (\Throwable $th) {
//throw $th;
return false;
}
}
}
if($data = file_get_contents('php://input')){
print line::webhook($data);
}
<?php
class blog_post_msg_line{
function db(){
try {
//code...
return new PDO(DSN,USERNAME,PASSWORD);
} catch (\Throwable $th) {
//throw $th;
return false;
}
}
function rss(){
$obj = simplexml_load_file("https://zip358.com/feed");
$post_message[2] = $obj->channel->item[0]->title ."\n". $obj->channel->item[0]->link;
$post_message[1] = $obj->channel->item[1]->title ."\n". $obj->channel->item[1]->link;
$post_message[0] = $obj->channel->item[2]->title ."\n". $obj->channel->item[2]->link;
return $post_message;
}
function main(){
$pdo = self::db();
if($pdo){
$post_message = self::rss();
$sql = "select userid from user;";
$sth = $pdo->query($sql);
$res = $sth->fetchAll(PDO::FETCH_ASSOC);
if($res){
foreach($res as $key=>$val){
$user_id = $val["userid"];
self::line_post($user_id,$post_message);
}
}
}
}
function line_post($user_id ='',$post_message=null){
$text = [
[
'type' => 'text',
'text' =>"最新の記事をお届けします"
],
[
'type' => 'text',
'text' =>$post_message[0]
],
[
'type' => 'text',
'text' =>$post_message[1]
],
[
'type' => 'text',
'text' =>$post_message[2]
]
];
$message = [
'to' => $user_id,
'messages' => $text
];
$message = json_encode($message);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . ACCESS_TOKEN, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/push');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
}
}
if($argv[0]){
blog_post_msg_line::main();
}