-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
357 lines (300 loc) · 10.1 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
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
const {Client, LocalAuth, Poll} = require('whatsapp-web.js');
const {locateChrome} = require('locate-app');
const qrcode = require('qrcode-terminal');
const fs = require('fs');
const {addToWaitingList, addUser, getAllVolunteers, getAllWaitingList} = require('./sheets-manegment');
const groupsIds = JSON.parse(fs.readFileSync('./files/groupsIds.json', 'utf8')).groupIds;
let volunteersReminderMessage = fs.readFileSync('./files/volunteersReminderMessage.txt', 'utf8');
let volunteersAlertMessage = fs.readFileSync('./files/volunteersAlertMessage.txt', 'utf8');
let volunteerNewRequestMessage = fs.readFileSync('./files/informMessageNewRequest.txt', 'utf8');
const notRespondMessage = fs.readFileSync('./files/notRespondMessage.txt', 'utf8');
const approveMessage = fs.readFileSync('./files/approveMessage.txt', 'utf8');
let counter = 0;
let volunteers;
const PollOptions = {
'APPROVE': 'אשר',
'DENY': 'דחה',
'NOT_ANSWERED': 'לא ענה',
}
async function start() {
let browserPath;
try {
browserPath = await locateChrome();
} catch (err) {}
const client = new Client({
puppeteer: {
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
],
defaultViewport: null,
font: 'Arial, "Noto Sans Hebrew", "Noto Sans", sans-serif',
executablePath: browserPath
},
authStrategy: new LocalAuth(
{
clientId: '1',
}
),
authTimeoutMs: 0,
});
client.on('qr', (qr) => {
console.log('QR RECEIVED', qr);
qrcode.generate(qr, {small: true});
});
client.on('loading_screen', (progressValue, message) => {
console.log('Login progress:', progressValue, 'Message:', message);
});
client.on('authenticated', () => {
console.log('AUTHENTICATED');
});
client.on('dialog', async dialog => {
console.log("Refresh popup just dismissed")
await dialog.dismiss()
});
client.on('error', () => {
client.destroy().then(() => client.initialize());
console.log('Page error... Client is ready again!');
});
client.on('ready', () => {
console.log('READY');
handle_ready(client).then();
});
// client.on('message_create', async (message) => {
// handle_message(client, message).then();
// });
client.on('group_membership_request', async (request) => {
if (!groupsIds.includes(request.chatId)) {
return;
}
console.log('group_membership_request', request);
const {chatId, timestamp, author} = request;
handle_membership_request(client, chatId, timestamp, author).then();
});
client.on('group_join', async (request) => {
if (!groupsIds.includes(request.chatId)) {
return;
}
console.log('group_join', request);
const {chatId, timestamp, recipientIds} = request;
for (const recipient of recipientIds) {
handle_group_join(client, chatId, timestamp, recipient).then();
}
});
client.on('disconnected', (reason) => {
console.log('Client Disconnected', reason);
client.initialize();
});
client.on('vote_received', async (vote) => {
handle_poll_vote(client, vote).then();
});
client.initialize().then();
}
async function handle_ready(client) {
setTimeout(() => {
handle_ready(client).then();
console.log('run after 10 minutes')
}, 1000 * 60 * 10);
for (const chatId of groupsIds) {
const chat = await client.getChatById(chatId);
let [, fullData] = await getAllPendingFromSheet(chat.name);
const pendingRequests = await chat.getGroupMembershipRequests();
console.log('pendingRequests', pendingRequests);
fullData.forEach(({phone}) => {
let action;
if (chat.participants.find(p => p.id.user === phone)) {
action = 'הצטרפות';
}
else if(!pendingRequests.find((request) => request.id.user === phone)) {
action = 'הסרת בקשה';
}
if (action) {
handle_group_join(client, chatId, new Date(), phone, action).then();
}
});
for (const request of pendingRequests) {
await handle_membership_request(client, chatId, new Date(), request.id._serialized);
}
}
}
async function handle_membership_request(client, chatId, timestamp, requestedUserId) {
const chat = await client.getChatById(chatId);
const date = new Date(timestamp * 1000);
const requestedUserPhone = requestedUserId.replace(/\D/g, '');
volunteers = await getAllVolunteers();
const [allPendingFromSheet, fullData] = await getAllPendingFromSheet(chat.name);
if (allPendingFromSheet.includes(requestedUserPhone)) {
const rawData = fullData.find((data) => data.phone === requestedUserPhone);
const date = new Date();
if (rawData) {
let action;
if (rawData.date < (date - 15 * 60 * 1000)) {
action = 'רענון בקשה';
await client.sendMessage(rawData.volunteerPhone + '@c.us', volunteersAlertMessage);
}
else if (!volunteers.find((volunteer) => volunteer.phone === rawData.volunteerPhone)) {
action = 'רענון בקשה עקב החלפת משמרת';
}
if (action) {
await addUser({
date: new Date(),
chatName: chat.name,
phoneNumber: requestedUserPhone,
associatedVolunteer: {
name: rawData.volunteerName,
phone: rawData.volunteerNumber
},
action
});
}
else {
return;
}
}
}
let volunteer
while (!volunteer) {
volunteer = await getVolunteer(client);
if (!volunteer) {
await new Promise(resolve => setTimeout(resolve, 20 * 1000));
}
}
await addToWaitingList({
chatName: chat.name,
date,
phoneNumber: requestedUserPhone,
associatedVolunteer: volunteer
});
console.log('handle_membership_request', {
volunteerName: volunteer.name,
volunteerNumber: volunteer.phone,
chatName: chat.name,
date: date,
phoneNumber: requestedUserPhone
});
const message = fs.readFileSync('./files/message.txt', 'utf8')
.replace('MANAGER_NAME', volunteer.name)
.replace('PHONE_NUMBER', `+${volunteer.phone}`);
await client.sendMessage(requestedUserId, message);
const current_number_id = volunteer.phone.replace(/\D/g, '') + '@c.us';
const messageForNewRequest = volunteerNewRequestMessage
.replace('PHONE_NUMBER', `+${requestedUserPhone}`)
.replace('CHAT_NAME', chat.name)
.replace('chatId', chatId)
.replace('author', requestedUserId);
const poll = new Poll(messageForNewRequest, [PollOptions.APPROVE, PollOptions.DENY, PollOptions.NOT_ANSWERED], {allowMultipleAnswers: false});
await client.sendMessage(current_number_id, poll);
}
async function handle_group_join(client, chatId, timestamp, recipient, action='הצטרף') {
const date = new Date(timestamp * 1000);
const chat = await client.getChatById(chatId);
// await removeFromSheet(recipient, date.toLocaleDateString());
await addUser({
phoneNumber: recipient.replace(/\D/g, ''),
date,
action,
chatName: chat.name,
});
console.log('handle_group_join', recipient);
}
async function handle_poll_vote(client, vote) {
const {selectedOption, parentMessage, senderTimestampMs, voter} = vote;
const [chatId, userId] = getDataFromPoll(parentMessage)
if (!userId) {
return;
}
const volunteer = volunteers.find(volunteer => volunteer.phone === voter.replace(/\D/g, ''));
const date = new Date(senderTimestampMs * 1000);
const chat = await client.getChatById(chatId);
let replyMessage = 'הפעולה בוצעה בהצלחה';
if (selectedOption.name === PollOptions.APPROVE) {
// FIXME - check the response
await client.approveGroupMembershipRequests(chatId, { requesterIds: [userId] })
replyMessage = approveMessage;
}
else {
await client.rejectGroupMembershipRequests(chatId, {requesterIds: [userId]})
let action = 'נדחה';
if (selectedOption.name === PollOptions.NOT_ANSWERED) {
action = 'לא הגיב';
const link = 'https://chat.whatsapp.com/' + await chat.getInviteCode();
await client.sendMessage(userId, notRespondMessage + link);
}
await addUser({
phoneNumber: userId.replace(/\D/g, ''),
date,
action,
chatName: chat.name,
associatedVolunteer: volunteer
});
}
await parentMessage.reply(replyMessage.replace('PHONE_NUMBER', userId.replace(/\D/g, '')));
}
async function getVolunteer(client) {
let index = counter % volunteers.length;
counter++;
const volunteer = volunteers[index];
const chat = await client.getChatById(volunteer.phone + '@c.us');
const lastMessages = await chat.fetchMessages({limit: 5});
if (lastMessages.length === 0) {
return volunteer;
}
else {
lastMessages.reverse();
const lastPoll = lastMessages.find(message => message.type === 'poll_creation');
const [chatId, userId] = getDataFromPoll(lastPoll);
const lastMessage = lastMessages[0];
if (userId) {
if (!lastMessage.fromMe || await isPollAnswered(client, lastPoll.id._serialized)) {
return volunteer;
}
else if(lastMessage.body === volunteersAlertMessage) {
return;
}
else if (lastPoll.timestamp * 1000 < Date.now() - 1000 * 60 * 10 /* 10 minutes */) {
await client.sendMessage(volunteer.phone + '@c.us', volunteersAlertMessage)
// TODO Send Message to admin
const group = await client.getChatById(chatId);
const alreadyParticipant = group.participants.find(participant => participant.id._serialized === userId);
if (!alreadyParticipant) {
handle_membership_request(client, chatId, new Date(), userId).then();
}
}
else if (lastMessage.timestamp * 1000 < Date.now() - 1000 * 60 * 3 /* 3 minutes */) {
await client.sendMessage(volunteer.phone + '@c.us', volunteersReminderMessage);
}
} else {
return volunteer;
}
}
return undefined;
}
async function getAllPendingFromSheet(groupName) {
const data = await getAllWaitingList();
return [data.filter(row => row.groupName === groupName).map(row => row.phone), data];
}
async function isPollAnswered(client, msgId) {
return await client.pupPage.evaluate(async (msgId) => {
const getVotes = window.mR.findModule('getVotes')[0].getVotes;
const votes = await getVotes([msgId]);
if (!votes || votes.length === 0) {
return false;
}
return true;
}, msgId);
}
function getDataFromPoll(pollMessage) {
if (!pollMessage) {
return [];
}
const splitBody = pollMessage.body.split('➖➖➖➖➖➖➖➖➖➖➖');
if (splitBody.length !== 2) {
return [];
}
return splitBody[1].trim().split(' - ');
}
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at:', p, 'reason:', reason);
});
start().then();