-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·221 lines (202 loc) · 7.83 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
'use strict';
const { WebhookClient, Card } = require('dialogflow-fulfillment');
const { WebClient } = require('@slack/web-api');
const awsServerlessExpress = require('aws-serverless-express')
const aws = require('aws-sdk');
const express = require('express');
const bodyParser = require('body-parser');
const uuidv1 = require('uuid/v1');
const app = express();
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
const ENVIRONMENT = process.env.ENVIRONMENT;
const AWS_REGION = process.env.AWS_REGION;
const AWS_ACCESS_KEY_ID = process.env.AWS_ACCESS_KEY_ID;
const AWS_SECRET_ACCESS_KEY = process.env.AWS_SECRET_ACCESS_KEY;
const DYNAMO_DB_API_VERSION = process.env.DYNAMO_DB_API_VERSION;
const COLLECTION_NAME = process.env.DYNAMO_DB_TABLE;
const SLACK_TOKEN = process.env.SLACK_TOKEN;
if (ENVIRONMENT === 'development') {
aws.config.update({ region: AWS_REGION, accessKeyId: AWS_ACCESS_KEY_ID, secretAccessKey: AWS_SECRET_ACCESS_KEY });
} else {
aws.config.update({ region: AWS_REGION });
}
const dynamodb = new aws.DynamoDB({ apiVersion: DYNAMO_DB_API_VERSION });
const slack = new WebClient(SLACK_TOKEN);
app.use('/', (request, response) => {
const agent = new WebhookClient({ request, response });
const { data } = request.body.originalDetectIntentRequest.payload;
const botUserId = data.authed_users;
const { event } = data;
const { channel, channel_type } = event;
const getMemberInfo = async user => {
return await slack.users.info({ user });
};
const persistPlayers = (players, channel) => {
return new Promise(async (resolve, reject) => {
const items = players.map(player => {
return {
PutRequest: {
Item: {
"id": { S: uuidv1() },
"channel": { S: channel },
"player": { S: player },
"score": { N: '0' }
}
}
}
});
const params = {
RequestItems: { [COLLECTION_NAME]: items }
};
try {
await dynamodb.batchWriteItem(params).promise();
resolve();
} catch (err) {
console.log("DynamoDBerror", err);
reject();
}
});
}
const findAll = () => {
return new Promise(async (resolve, reject) => {
const params = {
ExpressionAttributeValues: { ':channel': { S: channel } },
FilterExpression: 'channel = :channel',
ProjectionExpression: 'id, channel, player, score',
TableName: COLLECTION_NAME
};
try {
const response = await dynamodb.scan(params).promise();
const players = response.Items.map(p => {
return { id: p.id.S, score: Number.parseInt(p.score.N), player: p.player.S, channel: p.channel.S };
});
const sorted = players.sort((a, b) => (b.score - a.score));
resolve(sorted);
} catch (err) {
console.log("DynamoDBerror", err);
reject();
}
});
}
const updateScore = async (points, playerName) => {
const players = await findAll();
const matches = players.filter(p => {
const name = p.player.toLowerCase().trim();
const criteria = playerName.toLowerCase().trim();
return name.includes(criteria) && p.channel === channel;
}
);
if (matches.length > 0) {
const selected = matches[0];
var params = {
TableName: COLLECTION_NAME,
Item: {
'score': { N: (selected.score + points).toString() },
'id': { S: selected.id },
'player': { S: selected.player },
'channel': { S: selected.channel }
}
};
try {
await dynamodb.putItem(params).promise();
return selected;
} catch (err) {
console.log("DynamoDBerror", err);
return null;
}
} else {
return null;
}
}
const formatPlayersScore = players => {
let playersInline = '';
players.forEach(p => {
playersInline += `${p.player}: ${p.score} \n`;
});
return playersInline;
};
const getChannelInfo = channel => {
if (channel_type === 'group') {
return slack.groups.info({ channel })
.then(res => res.group);
} else {
return slack.channels.info({ channel })
.then(res => res.channel);
}
};
const showLeaderboard = (players, channelName) => {
agent.add(new Card({
title: `Leaderboard [${channelName}]`,
text: players.length ? formatPlayersScore(players) : 'No score yet'
}));
};
const setScore = async agent => {
const { Points, Player } = agent.parameters;
const updated = await updateScore(Points, Player);
if (updated) {
const { name } = await getChannelInfo(channel);
agent.add(`${Points} points to ${updated.player}`);
const players = await findAll();
showLeaderboard(players, name);
} else {
agent.add(':no:');
}
}
const getScore = async () => {
const players = await findAll();
const { name } = await getChannelInfo(channel);
showLeaderboard(players, name);
}
const setPlayers = async agent => {
const { name, members } = await getChannelInfo(channel);
const membersData = await Promise.all(members.map(user => getMemberInfo(user)));
const membersName = membersData.filter(p => p.user.id != botUserId).map(p => p.user.real_name);
const alreadyPlayers = await findAll();
const newPlayers = membersName.filter(name => !alreadyPlayers.find(p => p.player == name));
await persistPlayers(newPlayers, channel);
const allPlayers = await findAll();
agent.add('Done, players have been set');
showLeaderboard(allPlayers, name);
}
const resetLeaderboard = async agent => {
const { name } = await getChannelInfo(channel);
const players = await findAll();
const items = players.map(p => {
return {
PutRequest: {
Item: {
"id": { S: p.id },
"channel": { S: p.channel },
"player": { S: p.player },
"score": { N: '0' }
}
}
}
});
const params = {
RequestItems: { [COLLECTION_NAME]: items }
};
try {
await dynamodb.batchWriteItem(params).promise();
const updatedPlayes = players.map(p => Object.assign({ ...p, score: 0 }, {}));
agent.add('Well... as you whish. Done!');
showLeaderboard(updatedPlayes, name);
} catch (err) {
console.log("DynamoDBerror", err);
agent.add(':no:');
}
};
const intentMap = new Map();
intentMap.set('Set Score Intent', setScore);
intentMap.set('Get Score Intent', getScore);
intentMap.set('Set Players Intent', setPlayers);
intentMap.set('Reset Leaderboard - yes', resetLeaderboard);
agent.handleRequest(intentMap);
});
if (ENVIRONMENT === 'development') {
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => console.log(`App listening on port ${PORT}`));
}
const server = awsServerlessExpress.createServer(app);
exports.handler = (event, context) => { awsServerlessExpress.proxy(server, event, context) }