Facebookでは製品/団体/イベント等のための「Facebookページ」を作成することができます。ここではK5 Playgroundで、Facebookページ来訪者とチャットを行うアプリを作ります。チャットの内容は全てデータベースに保存され、後から分析もできます。
概要
材料
- テンプレート: Chat
- APIロジック: MongoDB, Facebook Messenger, HTTP
- データベース: MongoDB
機能
- 来訪者とチャットするためのUI
- チャット内容のMongoDBへの格納
アプリの作成
K5 Playgroundにアクセスします。
Frontend
- Chatテンプレートを選択します。
Backend
左メニューのWebAPIsから
webhookという名称のWebAPIを新規追加して、GETとPOSTを有効化します。POST messageエンドポイントを選択します。右メニューのMessagingから
Facebook Messenger Platform Send Messageを、Stream Send MessageAPIロジックの下に追加して次のように修正します。1
id: req.body.stream_id,
1
text: req.body.message,
GET webhookエンドポイントのAPIロジックを選択します。- 右メニューのMessagingから
Facebook Messenger Platform Verify Webhook Tokenを追加します。
- 右メニューのMessagingから
POST webhookエンドポイントを選択します。右メニューのMessagingから
Facebook Messenger Platform Receive Messageを追加します。右メニューの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
31var 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);
});右ペインの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
28results.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);右ペインの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
27function 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({});
アプリケーションをダウンロードします。
アプリのカスタマイズ
Frontend
app\components\StreamList\StreamList.jsのstream._idをstream.stream_idに置換します。app\components\StreamContent\StreamContent.jsのcurrentStream._idをcurrentStream.stream_idに置換します。プロフィール画像を画面に表示させます。
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
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"
}
}],config.jsに必要な接続情報を記入します。
アプリのデプロイ
Backend
1 | cd backend |
Frontend
1 | cd frontend |
ダウンロード
Version
- Chat テンプレート: v1.0.0