-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
107 lines (85 loc) · 2.65 KB
/
index.js
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
console.log('Loading function');
// API Gatewayの設定
const HOST = 'wjz7li7gmj.execute-api.ap-northeast-1.amazonaws.com';
const PATH = '/prod/statuses/update';
const X_API_KEY = '';
// S3の設定
const BUCKET = 'jaws2016lambda';
const KEY = 'tweetList.txt';
const TEXT_DELIMITER = '\r\n';
var aws = require('aws-sdk');
var s3 = new aws.S3({ apiVersion: '2006-03-01' });
var https = require('https');
// デリミタで指定された文字で文字列を分割し、ランダムの値を返却
function getRandomMessage(data, delimiter) {
var lines = data.split(delimiter);
var message = lines[Math.floor(Math.random() * (lines.length -1))];
return message;
}
// messageで指定された文字列をAPI Gateway経由でツイートする
function tweet(message, cb) {
var body = JSON.stringify({
status: message
})
var options = {
host: HOST,
port: 443,
path: PATH,
method: 'POST',
headers: {
'x-api-key': X_API_KEY,
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(body)
}
};
var req = https.request(options, function(res) {
console.log("response code = " + res.statusCode)
var body = '';
res.setEncoding('utf-8');
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
if(res.statusCode !== 200) {
cb(new Error('Error. status code = ' + res.statusCode
+ '. Error message = ' + JSON.parse(body).errorMessage));
} else {
console.log(body);
cb(null);
}
});
});
req.write(body);
req.end();
req.on('error', function(err) {
cb(err);
});
}
// メイン
exports.handler = function(event, context) {
var params = {
Bucket: BUCKET,
Key: KEY
};
var data = "";
var s3 = new aws.S3();
// S3からテキストデータの取得
var s3stream = s3.getObject(params).createReadStream();
s3stream.setEncoding('utf-8');
s3stream.on('error', function(err) {
context.fail(err);
});
s3stream.on('data', function(chunk) {
data += chunk;
});
s3stream.on('end', function() {
console.log("S3 data = " + data);
// いずれかのメッセージを取得
var message = getRandomMessage(data, TEXT_DELIMITER);
// ツイート
tweet(message, function(err) {
if(err) context.fail(err);
else context.succeed(message);
});
});
};