LoginSignup
4
4

More than 3 years have passed since last update.

LINEBOTで湯婆婆を実装してみる

Posted at

はじめに

原作者(元ネタ)様の記事:Javaで湯婆婆を実装してみる - Qiita

何番煎じか分かりませんが、
執筆時点(2020/11/09)でLINEBOTで実装して記事にされている方がいなかったので、実装してみました。

コード

PHP7で実装しました。
**(コピペして試される方はアクセストークンが記述されたtoken.txtファイルを読み込んでいる点にご注意ください。)

<?php

// 湯婆婆関数
function yubaba($name, $token_reply) {

  // 贅沢なリプライメッセージ
  $hun = [
    'type' => 'text',
    'text' => "フン。".$name."というのかい。\n贅沢な名だねぇ。"
  ];

  // 湯婆婆が名前を1文字ずつ認識できる様にする
  $name_arr = preg_split("/\B/u", $name);
  // 抜き出す1文字の位置を求める
  $num = mt_rand(0,count($name_arr));
  // 新しい名
  $na = $name_arr[$num];

  // 君の名は。
  $kiminonaha = [
    'type' => 'text',
    'text' => "今からお前の名前は".$na."だ。\nいいかい、".$na."だよ。\n分かったら返事をするんだ、".$na."!!"
  ];

  $content = [
    'replyToken' => $token_reply,
    'messages' => [$hun,$kiminonaha]
  ];

  return $content;
}

function follow_reply($token_reply) {
  $keiyaku = [
    'type' => 'text',
    'text' => "契約書だよ。\nそこに名前を書きな。"
  ];

  $content = [
    'replyToken' => $token_reply,
    'messages' => [$keiyaku]
  ];

  return $content;
}

// リプライメッセージ送信関数
function send($content,$token) {
  $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($content));
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json; charser=UTF-8',
      'Authorization: Bearer ' . $token
  ));
  $result = curl_exec($ch);
  curl_close($ch);
}

// メイン関数
function main() {
  // アクセストークン
  $token_access = file_get_contents('token.txt');

  // リクエストjsonデータの処理
  $json_req = file_get_contents('php://input');
  $obj_req = json_decode($json_req);

  $event_type = $obj_req->{"events"}[0]->{"type"};
  if ($event_type === "message") { // メッセージの場合
    // メッセージデータ
    $msg = $obj_req->{"events"}[0]->{"message"}->{"text"};
    // 先頭及び末尾の空白などの余分な要素を削除
    $msg = trim($msg);
    // リプライトークン
    $token_reply = $obj_req->{"events"}[0]->{"replyToken"};
    // 湯婆婆
    $content_reply = yubaba($msg, $token_reply);
  } elseif ($event_type === "follow") { // 友達追加の場合
    // リプライトークン
    $token_reply = $obj_req->{"events"}[0]->{"replyToken"};
    // 友達追加メッセージ
    $content_reply = follow_reply($token_reply);
  } else {
    exit(0);
  }

  // 送信
  send($content_reply,$token_access);
}

main();

実行例

湯婆婆_実行例.PNG

湯婆婆の画像は、スタジオジブリ公式フリー素材ページから使用しています。

最後に

湯婆婆の実装意外とおもしろい。

LINEBOTの良い点はこの記事を読んだ人がすぐに試せる点ですね!
次の友だち追加ボタンもしくはQRコードから友達登録して使ってみてください!
友だち追加
M.png

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4