30min
aihara
  1. 1. 概要
    1. 1.1. 材料
    2. 1.2. 機能
  2. 2. アプリの作成
    1. 2.1. Frontend
    2. 2.2. Backend
  3. 3. アプリのカスタマイズ
    1. 3.1. Frontend
    2. 3.2. Backend
  4. 4. アプリのデプロイ
    1. 4.1. Backend
    2. 4.2. Frontend
  5. 5. ダウンロード
  6. 6. Version

Facebookでは製品/団体/イベント等のための「Facebookページ」を作成することができます。ここではK5 Playgroundで、Facebookページ来訪者とチャットを行うアプリを作ります。チャットの内容は全てデータベースに保存され、後から分析もできます。

概要

材料

  • テンプレート: Chat
  • APIロジック: MongoDB, Facebook Messenger, HTTP
  • データベース: MongoDB

機能

  • 来訪者とチャットするためのUI
  • チャット内容のMongoDBへの格納

アプリの作成

K5 Playgroundにアクセスします。

Frontend

  1. Chatテンプレートを選択します。

Backend

  1. 左メニューのWebAPIsからwebhookという名称のWebAPIを新規追加して、GETPOSTを有効化します。

  2. POST messageエンドポイントを選択します。

    1. 右メニューのMessagingからFacebook Messenger Platform Send Messageを、Stream Send Message APIロジックの下に追加して次のように修正します。

      1
      id: req.body.stream_id,
      1
      text: req.body.message,
  3. GET webhookエンドポイントのAPIロジックを選択します。

    1. 右メニューのMessagingからFacebook Messenger Platform Verify Webhook Tokenを追加します。
  4. POST webhookエンドポイントを選択します。

    1. 右メニューのMessagingからFacebook Messenger Platform Receive Messageを追加します。

    2. 右メニューのCustomからRequest HTTP Client: GETを追加して、次のように修正します。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      var accessToken = '[ACCESS_TOKEN]';

      function getProfile(senderId) {
      var options = {
      url: 'https://graph.facebook.com/v2.6/'+senderId+'?access_token='+ accessToken,
      json: true,
      };
      return new Promise(function(resolve, reject) {
      Request.get(options, function(error, response, body) {
      if (!error && response.statusCode == 200) {
      resolve(body);
      }
      });
      });
      }

      var promises = [];
      results.entry.forEach(function(entry) {
      if (entry.messaging) {
      entry.messaging.forEach(function(messaging) {
      if (messaging.message && !messaging.message.is_echo) {
      promises.push(getProfile(messaging.sender.id).then(function(profile) {
      return Object.assign(messaging, { profile: profile });
      }));
      }
      });
      }
      });
      Promise.all(promises).then(function(profiles) {
      next(profiles);
      });
    3. 右ペインのDatabaseメニューからMongoDB Save Documentを追加して、次のように修正します。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      results.forEach(function(messaging) {
      var collectionName = 'sample_stream';
      var url = 'mongodb://' + config.datasource.user + ':' + config.datasource.password + '@' + config.datasource.host + ':' + config.datasource.port + '/' + config.datasource.database;

      MongoClient.connect(url, function(err, db) {
      if (err) {
      throw err;
      }
      db.collection(collectionName).updateOne(
      { stream_id: document.stream_id },
      {
      stream_id: messaging.sender.id,
      name: messaging.profile.first_name + ' ' + messaging.profile.last_name,
      image: messaging.profile.profile_pic,
      },
      { upsert: true },
      function(err, result) {
      db.close();
      if (err) {
      throw err;
      }
      return;
      }
      );
      });
      });

      next(results);
    4. 右ペインのDatabaseメニューからMongoDB Save Documentを追加して、次のように修正します。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      function saveMessage(document) {
      var collectionName = 'sample_message';
      var url = 'mongodb://' + config.datasource.user + ':' + config.datasource.password + '@' + config.datasource.host + ':' + config.datasource.port + '/' + config.datasource.database;

      MongoClient.connect(url, function(err, db) {
      if (err) {
      throw err;
      }
      db.collection(collectionName).save(document, function(err, result) {
      db.close();
      if (err) {
      throw err;
      }
      return;
      });
      });
      }

      results.forEach(function(messaging) {
      saveMessage({
      stream_id: messaging.sender.id,
      user_id: messaging.profile.first_name + ' ' + messaging.profile.last_name,
      message: messaging.message.text,
      });
      });

      next({});
  5. アプリケーションをダウンロードします。

アプリのカスタマイズ

Frontend

  1. app\components\StreamList\StreamList.jsstream._idstream.stream_idに置換します。

  2. app\components\StreamContent\StreamContent.jscurrentStream._idcurrentStream.stream_idに置換します。

  3. プロフィール画像を画面に表示させます。

    app\components\StreamContent\StreamContent.js<img>タグの行を追加

    1
    2
    3
    4
    <VerticalLayout style={styles.streamTitle}>
    {currentStream.name}
    <img src={currentStream.image} alt={currentStream.user_id} style={{ width: 100 }} />
    </VerticalLayout>

Backend

  1. Swagger定義ファイルapi/swagger.jsonを次のように修正します。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    "/webhook": {
    // 略
    "post": {
    "description": "",
    "parameters": [{
    "name": "data",
    "in": "body",
    "schema": {
    "type": "string"
    }
    }],
  2. config.jsに必要な接続情報を記入します。

アプリのデプロイ

Backend

1
2
cd backend
cf push [APP_NAME]

Frontend

1
2
3
4
5
6
cd frontend
npm install
set API_URL=[Backend URL] # for Windows
export API_URL=[Backend URL] # for Mac/Linux
npm run build
cf push [APP_NAME] -p public

ダウンロード

Version

  • Chat テンプレート: v1.0.0