-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
304 lines (266 loc) · 8.08 KB
/
app.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
const { App } = require('@slack/bolt');
const { WebClient } = require('@slack/web-api');
require("dotenv").config()
const CourseRepository = require('./CourseRepository');
const ProgressionRepository = require('./ProgressionRepository');
const UserRepository = require('./UserRepository');
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET
});
const client = new WebClient(process.env.SLACK_BOT_TOKEN);
function sleep() {
const randomMs = Math.floor(Math.random() * (1000 - 500 + 1)) + 500;
return new Promise(resolve => setTimeout(resolve, randomMs));
}
async function syncSlackUsers() {
let allUsers = [];
let cursor;
do {
const response = await client.users.list({
limit: 200,
cursor: cursor
});
if (response.ok) {
allUsers = allUsers.concat(response.members);
cursor = response.response_metadata && response.response_metadata.next_cursor;
} else {
throw new Error(`Erreur lors de la récupération des utilisateurs : ${response.error}`);
}
} while (cursor);
const filteredUsers = allUsers
.filter(u => !u.is_bot && !u.deleted)
.map(u => ({
slack_user_id: u.id,
name: u.name
}));
await UserRepository.bulkInsertOrUpdateUsers(filteredUsers);
}
async function sendNextSteps(slackUserId) {
const users = await UserRepository.getAllUsers();
const user = users.find(u => u.slack_user_id === slackUserId);
if (!user) {
console.log(`Utilisateur ${slackUserId} non trouvé`);
return;
}
let progression = await ProgressionRepository.getUserProgression(user.id);
let courseId;
let currentStep;
if (!progression) {
courseId = 1;
currentStep = 0;
await ProgressionRepository.upsertProgression(user.id, courseId, currentStep);
} else {
courseId = progression.course_id;
currentStep = progression.current_step;
}
const course = await CourseRepository.getCourse(courseId);
if (!course) {
await client.chat.postMessage({
channel: user.slack_user_id,
text: "Ce cours n'existe plus."
});
return;
}
const steps = await CourseRepository.getCourseSteps(courseId);
if (courseId > 1 && currentStep === 0) {
await client.chat.postMessage({
channel: user.slack_user_id,
text: `Démarrons le cours : *${course.title}*`
});
await sleep();
}
for (let i = currentStep; i < steps.length; i++) {
const step = steps[i];
if (step.type === 'message') {
await client.chat.postMessage({
channel: user.slack_user_id,
text: step.content
});
} else if (step.type === 'question') {
let possibleAnswers = [];
if (step.answers) {
try {
possibleAnswers = JSON.parse(step.answers);
} catch (e) {
console.error('Erreur de parsing JSON answers :', e);
possibleAnswers = [];
}
}
if (possibleAnswers.length === 0) {
await client.chat.postMessage({
channel: slackUserId,
text: `Question: ${step.content}\n(Pas de réponses disponibles)`
});
} else {
const blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `${step.content}`
}
},
{
"type": "actions",
"elements": possibleAnswers.map(answer => ({
"type": "button",
"text": {
"type": "plain_text",
"text": answer
},
"action_id": `answer_${courseId}_${step.id}_${answer}`
}))
}
];
await client.chat.postMessage({
channel: slackUserId,
blocks: blocks,
text: step.content
});
await ProgressionRepository.upsertProgression(user.id, courseId, i);
return;
}
}
await ProgressionRepository.upsertProgression(user.id, courseId, i + 1);
await sleep();
}
if (courseId > 1) {
await client.chat.postMessage({
channel: user.slack_user_id,
text: `Le cours *${course.title}* est terminé !`
});
}
await sleep();
const nextCourse = await CourseRepository.getNextCourse(courseId);
if (nextCourse) {
const blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": `On attaque le prochain cours : *${nextCourse.title}* ?`
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Oui 👍"
},
"action_id": `next_${nextCourse.id}_1`
},
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Non 👎"
},
"action_id": `next_${nextCourse.id}_0`
}
]
}
];
await client.chat.postMessage({
channel: user.slack_user_id,
blocks: blocks,
text: `On attaque le prochain cours : *${nextCourse.title}* ?`
});
}
}
app.action(/answer_\d+_\d+_.+/, async ({ body, ack, say }) => {
await ack();
const slackUserId = body.user.id;
const action = body.actions[0];
const actionValue = action.action_id;
const [_, courseIdStr, stepIdStr, ...answerParts] = actionValue.split('_');
const courseId = parseInt(courseIdStr, 10);
const stepId = parseInt(stepIdStr, 10);
const userAnswer = answerParts.join('_');
const users = await UserRepository.getAllUsers();
const user = users.find(u => u.slack_user_id === slackUserId);
if (!user) return;
const steps = await CourseRepository.getCourseSteps(courseId);
const step = steps.find(s => s.id === stepId);
if (!step) return;
const correctAnswer = step.correct_answer || '';
if (userAnswer.toLowerCase() === correctAnswer.toLowerCase()) {
await say("Bonne réponse !");
} else {
await say(`Mauvaise réponse. La bonne réponse était : ${correctAnswer}`);
}
const progression = await ProgressionRepository.getUserProgression(user.id);
await ProgressionRepository.upsertProgression(user.id, courseId, progression.current_step + 1);
await sleep();
await sendNextSteps(slackUserId);
});
app.action(/next_\d+_\d+/, async ({ body, ack, say }) => {
await ack();
const slackUserId = body.user.id;
const action = body.actions[0];
const actionValue = action.action_id;
const [_, nextCourseIdStr, answerStr] = actionValue.split('_');
const nextCourseId = parseInt(nextCourseIdStr, 10);
const answer = parseInt(answerStr, 10);
const users = await UserRepository.getAllUsers();
const user = users.find(u => u.slack_user_id === slackUserId);
if (!user) return;
if(answer == 1) {
await ProgressionRepository.upsertProgression(user.id, nextCourseId, 0);
await sendNextSteps(slackUserId);
} else {
const blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Ok quand tu seras pret clique juste ici"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Go 🚀"
},
"action_id": `next_${nextCourseId}_1`
},
]
}
];
await client.chat.postMessage({
channel: slackUserId,
blocks: blocks,
text: "Ok quand tu seras pret clique juste ici"
});
}
});
app.command('/marcel-sync', async ({ command, ack, say }) => {
await ack();
await syncSlackUsers();
await say("Users synchronisés en base !");
});
app.command('/marcel-start', async ({ command, ack }) => {
await ack();
var users = await UserRepository.getAllUsers();
users.forEach(async (user) => {
await sendNextSteps(user.slack_user_id);
})
});
app.message(async ({ message, say }) => {
if (message.text === "quoi ?") {
await say("feur");
return;
}
});
(async () => {
const port = process.env.PORT || 3000;
await app.start(port);
console.log(`⚡️ L’application Slack est en cours d’exécution sur le port ${port}`);
})();