-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
636 lines (542 loc) · 24.7 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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
const fs = require('fs');
const TelegramBot = require('node-telegram-bot-api');
const token = fs.readFileSync('token', 'utf8').trim();
const bot = new TelegramBot(token, { polling: true });
function sendMessageWithOptions(chatId, message, options) {
const inlineKeyboard = options.map(option => [{ text: option.text, callback_data: option.callback_data }]);
bot.sendMessage(chatId, message, {
reply_markup: {
inline_keyboard: inlineKeyboard
}
});
}
// Define a global metadata object
const metadata = {
users: {
columns: {
userId: 0, // Default initial values, will be updated by migration
userName: 1,
userLink: 2,
fullName: 3,
},
},
};
const chats = {};
const introductionMessage = `Как я могу к Вам обращаться?`;
const steps = {
"step.1": (chatId) => {
sendMessageWithOptions(chatId, 'Как я могу быть вам полезен?', [
{ text: 'Информация о курсах', callback_data: 'step.2' },
{ text: 'Оставить заявку для связи', callback_data: 'block.2' },
{ text: 'Хочу учиться бесплатно!', callback_data: 'step.3' }
]);
},
"step.2": (chatId) => {
sendMessageWithOptions(chatId, 'У нас есть следующие варианты обучения:', [
{ text: 'Платные программы', callback_data: 'step.2.paid-courses' },
{ text: 'Бесплатные программы', callback_data: 'step.3' },
{ text: 'Назад', callback_data: 'step.1' },
{ text: 'Бесплатные в рамках программы Содействие занятости', callback_data: 'step.4' },
]);
},
"step.2.paid-courses": (chatId) => {
sendMessageWithOptions(chatId, 'Выберите платный курс:', [
{ text: '1. НЕЙРОСЕТИ ДЛЯ ДИЗАЙНЕРОВ И СТИЛИСТОВ', callback_data: 'step.2.paid-courses.1' },
]);
},
"step.2.paid-courses.1": (chatId) => {
bot.sendMessage(chatId, `
Авторский курс Анны Клименкоди - это практика использования актуальных нейросетей в профессиональной деятельности дизайнеров и стилистов. Курс включает инструкции по работе с инструментами искусственного интеллекта с учетом последних обновлений, и доступен для обучения с “нуля”.
Профессия: контент менеджер, промпт инженер
Доступно полностью дистанционное (онлайн) обучение
Длительность: 12 недель, 72 академических часа
Полная стоимость курса: 50 тыс. рублей, доступна рассрочка
Подробнее: https://styleschool.ru/education/nn-for-designers-and-stylists
`);
sendMessageWithOptions(chatId, 'Хотите начать обучение по этой программе?', [
{ text: 'Да', callback_data: 'block.2' },
{ text: 'Нет', callback_data: 'step.1' },
{ text: 'Выбрать другой курс', callback_data: 'step.2.paid-courses' },
]);
},
"step.3": (chatId) => {
sendMessageWithOptions(chatId, 'Выберите бесплатный курс:', [
{ text: '1. КОНСУЛЬТАНТ ПО СТИЛЮ', callback_data: 'step.3.free-courses.1' },
]);
},
"step.3.free-courses.1": (chatId) => {
bot.sendMessage(chatId, `
Курс создан для обучения с “нуля”. Дает возможность реализовать мечту о творческой самореализации в области моды и сделать первые шаги в профессии стилиста. В курсе представлены базовые методики в области подбора комплектов одежды в соответствии с индивидуальными особенностями персон и модными тенденциями. Гибкий график изучения видео материалов в сочетании с живыми практическими занятиями и командной работой дает гарантированный результат.
Направления в профессии: имидж-консультант, консультант по стилю, персональный стилист, шопер, продавец-стилист.
Доступно полностью дистанционное (онлайн) обучение
Доступно комбинированное обучение с очными практиками
Длительность: 8 недель, 144 академических часов.
Полная стоимость курса:
онлайн формат - 40 тыс. рублей, доступна рассрочка
комбинированный формат (онлайн + очные практики) - 69 тыс. рублей, доступна рассрочка *
cтоимость обучения в рамках федерального проекта “Содействие занятости” - 0 рублей. **
* Очные практики доступны по региону: Москва, Новосибирск
** Данное обучение доступно для определенных категорий граждан РФ.
`);
sendMessageWithOptions(chatId, 'Хотите начать обучение по этой программе?', [
{ text: 'Да', callback_data: 'block.2' },
{ text: 'Нет', callback_data: 'step.1' },
{ text: 'Выбрать другой курс', callback_data: 'step.3' },
]);
},
"block.2": async (chatId, userId) => {
if (!userId) {
return;
}
const user = await getUserRow(userId);
console.log({ user });
if (user?.fullName) {
sendMessageWithOptions(chatId, `Вы ${user.fullName}?`, [
{ text: 'Да', callback_data: 'block.2.form-complete' },
{ text: 'Нет', callback_data: 'block.2.enter-name' },
]);
} else {
bot.sendMessage(chatId, `Как к вам обращаться?`);
chats[chatId] ??= {};
chats[chatId].state = 'entering-name';
}
},
"block.2.form-complete": (chatId) => {
bot.sendMessage(chatId, `Спасибо! В ближайшее время с Вами свяжутся`);
},
"block.2.enter-name": (chatId) => {
bot.sendMessage(chatId, `Как к вам обращаться?`);
chats[chatId] ??= {};
chats[chatId].state = 'entering-name';
},
};
// const welcomeMessage = `Здравствуйте. Я бот Высшей школы стилистики, дизайна и технологий! Я готов предоставить вам информацию о наших курсах и вариантах обучения. Также я могу перевести вас на другого бота, где вы можете бесплатно проходить обучение.`;
// const steps = {
// "step.1": (chatId) => {
// sendMessageWithOptions(chatId, 'Как я могу быть вам полезен?', [
// { text: 'Информация о курсах', callback_data: 'step.2' },
// { text: 'Оставить заявку для связи', callback_data: 'block.2' },
// { text: 'Хочу учиться бесплатно!', callback_data: 'step.3' }
// ]);
// },
// "step.2": (chatId) => {
// sendMessageWithOptions(chatId, 'У нас есть следующие варианты обучения:', [
// { text: 'Платные программы', callback_data: 'step.2.paid-courses' },
// { text: 'Бесплатные программы', callback_data: 'step.3' },
// { text: 'Назад', callback_data: 'step.1' },
// { text: 'Бесплатные в рамках программы Содействие занятости', callback_data: 'step.4' },
// ]);
// },
// "step.2.paid-courses": (chatId) => {
// sendMessageWithOptions(chatId, 'Выберите платный курс:', [
// { text: '1. НЕЙРОСЕТИ ДЛЯ ДИЗАЙНЕРОВ И СТИЛИСТОВ', callback_data: 'step.2.paid-courses.1' },
// ]);
// },
// "step.2.paid-courses.1": (chatId) => {
// bot.sendMessage(chatId, `
// Авторский курс Анны Клименкоди - это практика использования актуальных нейросетей в профессиональной деятельности дизайнеров и стилистов. Курс включает инструкции по работе с инструментами искусственного интеллекта с учетом последних обновлений, и доступен для обучения с “нуля”.
// Профессия: контент менеджер, промпт инженер
// Доступно полностью дистанционное (онлайн) обучение
// Длительность: 12 недель, 72 академических часа
// Полная стоимость курса: 50 тыс. рублей, доступна рассрочка
// Подробнее: https://styleschool.ru/education/nn-for-designers-and-stylists
// `);
// sendMessageWithOptions(chatId, 'Хотите начать обучение по этой программе?', [
// { text: 'Да', callback_data: 'block.2' },
// { text: 'Нет', callback_data: 'step.1' },
// { text: 'Выбрать другой курс', callback_data: 'step.2.paid-courses' },
// ]);
// },
// "step.3": (chatId) => {
// sendMessageWithOptions(chatId, 'Выберите бесплатный курс:', [
// { text: '1. КОНСУЛЬТАНТ ПО СТИЛЮ', callback_data: 'step.3.free-courses.1' },
// ]);
// },
// "step.3.free-courses.1": (chatId) => {
// bot.sendMessage(chatId, `
// Курс создан для обучения с “нуля”. Дает возможность реализовать мечту о творческой самореализации в области моды и сделать первые шаги в профессии стилиста. В курсе представлены базовые методики в области подбора комплектов одежды в соответствии с индивидуальными особенностями персон и модными тенденциями. Гибкий график изучения видео материалов в сочетании с живыми практическими занятиями и командной работой дает гарантированный результат.
// Направления в профессии: имидж-консультант, консультант по стилю, персональный стилист, шопер, продавец-стилист.
// Доступно полностью дистанционное (онлайн) обучение
// Доступно комбинированное обучение с очными практиками
// Длительность: 8 недель, 144 академических часов.
// Полная стоимость курса:
// онлайн формат - 40 тыс. рублей, доступна рассрочка
// комбинированный формат (онлайн + очные практики) - 69 тыс. рублей, доступна рассрочка *
// cтоимость обучения в рамках федерального проекта “Содействие занятости” - 0 рублей. **
// * Очные практики доступны по региону: Москва, Новосибирск
// ** Данное обучение доступно для определенных категорий граждан РФ.
// `);
// sendMessageWithOptions(chatId, 'Хотите начать обучение по этой программе?', [
// { text: 'Да', callback_data: 'block.2' },
// { text: 'Нет', callback_data: 'step.1' },
// { text: 'Выбрать другой курс', callback_data: 'step.3' },
// ]);
// },
// "block.2": async (chatId, userId) => {
// if (!userId) {
// return;
// }
// const user = await getUserRow(userId);
// console.log({ user });
// if (user?.fullName) {
// sendMessageWithOptions(chatId, `Вы ${user.fullName}?`, [
// { text: 'Да', callback_data: 'block.2.form-complete' },
// { text: 'Нет', callback_data: 'block.2.enter-name' },
// ]);
// } else {
// bot.sendMessage(chatId, `Как к вам обращаться?`);
// chats[chatId] ??= {};
// chats[chatId].state = 'entering-name';
// }
// },
// "block.2.form-complete": (chatId) => {
// bot.sendMessage(chatId, `Спасибо! В ближайшее время с Вами свяжутся`);
// },
// "block.2.enter-name": (chatId) => {
// bot.sendMessage(chatId, `Как к вам обращаться?`);
// chats[chatId] ??= {};
// chats[chatId].state = 'entering-name';
// },
// };
// Matches any message
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
const userId = msg.from.id;
const username = msg.from.username;
const text = msg.text;
if (chats?.[chatId]?.state === 'entering-name') {
await updateOrAddRow({ userId, fullName: text });
await bot.sendMessage(chatId, `Спасибо! В ближайшее время с Вами свяжутся`);
delete chats?.[chatId]?.state;
}
});
bot.onText(/\/start/, async (msg) => {
const chatId = msg.chat.id;
const username = msg.from.username;
console.log(username);
await bot.sendMessage(chatId, introductionMessage)
chats[chatId] ??= {};
chats[chatId].state = 'entering-name';
// .then(() => {
// // steps['step.1'](chatId);
// });
});
bot.on('callback_query', async (callbackQuery) => {
const message = callbackQuery.message;
const data = callbackQuery.data;
const username = callbackQuery.from.username;
// const handler = steps[data];
// if (handler) {
// await handler(message.chat.id, callbackQuery.from.id);
// }
});
console.log("Bot is running...");
const { google } = require('googleapis');
const spreadsheetId = '1_7bWQgcDmd0o6jr7rvYGSoedAmYJ7IbZFV4tOJXOB_I'; // Replace with your spreadsheet ID
let sheets; // Global variable for Google Sheets API client
// Function to insert a row using Google Sheets API
async function addRow(user) {
const range = 'Users!A:D'; // Adjust the range to include the entire columns needed
const valueInputOption = 'RAW';
const values = [
[user.userId, user.fullName]
];
const resource = {
values,
};
try {
const response = await sheets.spreadsheets.values.append({
spreadsheetId,
range,
valueInputOption,
resource,
});
console.log('Row added:', response.data);
} catch (error) {
console.error('Error adding row: ', error);
}
}
// Function to ensure the first two cells in the Users sheet are 'userId' and 'fullName'
async function ensureFirstRow() {
const range = 'Users!A1:B1';
try {
const response = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
const values = response.data.values;
if (!values || values.length === 0 || values[0].length < 2) {
await sheets.spreadsheets.values.update({
spreadsheetId,
range,
valueInputOption: 'RAW',
resource: {
values: [['userId', 'fullName']],
},
});
console.log('First row updated to "userId" and "fullName".');
} else if (values[0][0] !== 'userId' || values[0][1] !== 'fullName') {
throw new Error('First two cells in the first row do not match "userId" and "fullName".');
} else {
console.log('First row is already set to "userId" and "fullName".');
}
} catch (error) {
console.error('Error ensuring first row: ', error);
}
}
// Function to ensure the Users sheet exists
async function ensureUsersSheet() {
const sheetTitle = 'Users';
try {
const sheetExists = await sheets.spreadsheets.get({
spreadsheetId,
});
const documentSheets = sheetExists.data.sheets.map(sheet => sheet.properties.title);
if (!documentSheets.includes(sheetTitle)) {
await sheets.spreadsheets.batchUpdate({
spreadsheetId,
resource: {
requests: [{
addSheet: {
properties: {
title: sheetTitle,
},
},
}],
},
});
console.log(`Sheet "${sheetTitle}" created.`);
} else {
console.log(`Sheet "${sheetTitle}" already exists.`);
}
} catch (error) {
console.error('Error ensuring Users sheet exists: ', error);
}
}
// Function to apply migrations
async function applyMigrations() {
const range = 'Users!A1:C1';
try {
// Ensure the sheet exists first
await ensureUsersSheet();
const response = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
const values = response.data.values;
// Apply migration for version 1
if (!values || values.length === 0 || values[0].length < 2) {
await sheets.spreadsheets.values.update({
spreadsheetId,
range: 'Users!A1:B1',
valueInputOption: 'RAW',
resource: {
values: [['userId', 'fullName']],
},
});
console.log('First migration applied, set to "userId" and "fullName".');
} else if (values[0].length == 2 && (values[0][0] !== 'userId' || values[0][1] !== 'fullName')) {
console.warn('First row does not match "userId" and "fullName". Attempting to fix...');
await sheets.spreadsheets.values.update({
spreadsheetId,
range: 'Users!A1:B1',
valueInputOption: 'RAW',
resource: {
values: [['userId', 'fullName']],
},
});
console.log('First row updated to "userId" and "fullName".');
} else {
console.log('First migration is already set to "userId" and "fullName".');
}
// Apply migration for version 2 (adding userLink and userLink fields)
if (values[0].length < 4 || values[0][1] !== 'userName' || values[0][2] !== 'userLink' || values[0][3] !== 'fullName') {
const responseAll = await sheets.spreadsheets.values.get({
spreadsheetId,
range: 'Users!A1:B',
});
const allValues = responseAll.data.values;
const newValues = allValues.map((row, index) => [
row[0] || null, // userId
null, // userName (new field left empty)
null, // userLink (new field left empty)
row[1] || null, // fullName moved to the fourth column
]);
await sheets.spreadsheets.values.update({
spreadsheetId,
range: 'Users!A1:D',
valueInputOption: 'RAW',
resource: {
values: [['userId', 'userName', 'userLink', 'fullName']],
},
});
if (newValues.length > 1) { // Ensure there's data beyond the header row
await sheets.spreadsheets.values.update({
spreadsheetId,
range: 'Users!A2:D',
valueInputOption: 'RAW',
resource: {
values: newValues.slice(1), // exclude header row
},
});
// Clear the old "fullName" column (second column)
await sheets.spreadsheets.values.update({
spreadsheetId,
range: 'Users!B2:B',
valueInputOption: 'RAW',
resource: {
values: Array(newValues.length - 1).fill(['']),
},
});
}
// Update metadata
metadata.users.columns = {
userId: 0,
userName: 1,
userLink: 2,
fullName: 3,
};
console.log('Second migration applied, moved "fullName" to new position and added "userLink" field. Metadata updated.');
} else {
console.log('Second migration is already set to "userId", "userName", "userLink", and "fullName". Metadata updated.');
// Ensure metadata is up to date even if migration was not applied
metadata.users.columns = {
userId: 0,
userName: 1,
userLink: 2,
fullName: 3,
};
}
} catch (error) {
console.error('Error applying migrations: ', error);
}
}
// Function to ensure all migrations are applied
async function ensureMigrations() {
await applyMigrations();
}
// Function to get a user by userId
async function getUserRow(userId) {
const range = 'Users!A:D'; // Adjust range to include columns for user data
try {
const response = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
const rows = response.data.values;
if (rows.length === 0) {
console.log('No data found.');
return null;
}
console.log(rows);
const userRow = rows.find(row => row[metadata.users.columns.userId] == userId);
if (!userRow) {
console.log('User not found.');
return null;
}
return {
userId: userRow[metadata.users.columns.userId],
userName: userRow[metadata.users.columns.userName],
userLink: userRow[metadata.users.columns.userLink],
fullName: userRow[metadata.users.columns.fullName],
};
} catch (error) {
console.error('Error getting row: ', error);
}
}
// Function to update a user by userId
async function updateRow(user) {
const range = 'Users!A:D'; // Adjust range to include columns for user data
try {
const response = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
const rows = response.data.values;
if (rows.length === 0) {
console.log('No data found.');
return;
}
const rowIndex = rows.findIndex(row => row[0] === user.userId);
if (rowIndex === -1) {
console.log('User not found.');
return;
}
const targetRange = `Users!A${rowIndex + 1}:D${rowIndex + 1}`; // Calculate the range for the specific row
const values = [
[user.userId, user.fullName]
];
const resource = {
values,
};
const updateResponse = await sheets.spreadsheets.values.update({
spreadsheetId,
range: targetRange,
valueInputOption: 'RAW',
resource,
});
console.log('Row updated:', updateResponse.data);
} catch (error) {
console.error('Error updating row: ', error);
}
}
// Function to update or add a user by userId
async function updateOrAddRow(user) {
const range = 'Users!A:D'; // Adjust range to include columns for user data
try {
const response = await sheets.spreadsheets.values.get({
spreadsheetId,
range,
});
const rows = response.data.values;
if (rows.length === 0) {
console.log('No data found. Adding the first row.');
}
// Find the index of the row to update
const rowIndex = rows ? rows.findIndex(row => row[0] == user.userId) : -1;
if (rowIndex !== -1) {
// Update existing user
const targetRange = `Users!A${rowIndex + 1}:D${rowIndex + 1}`; // Calculate the range for the specific row
const values = [[user.userId, user.fullName]];
const resource = { values };
const updateResponse = await sheets.spreadsheets.values.update({
spreadsheetId,
range: targetRange,
valueInputOption: 'RAW',
resource,
});
console.log('Row updated:', updateResponse.data);
} else {
// Add new user if not found
const values = [
[user.userId, user.fullName]
];
const resource = { values };
const appendResponse = await sheets.spreadsheets.values.append({
spreadsheetId,
range,
valueInputOption: 'RAW',
resource,
});
console.log('Row added:', appendResponse.data);
}
} catch (error) {
console.error('Error updating or adding row: ', error);
}
}
// Authorize and call the functions
(async () => {
const auth = new google.auth.GoogleAuth({
keyFile: './google-api.json',
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
const authClient = await auth.getClient();
sheets = google.sheets({ version: 'v4', auth: authClient });
// await ensureFirstRow();
// Call ensureMigrations to ensure all migrations are applied
await ensureMigrations();
// const user = { userId: '123', fullName: 'John Doe' };
// await addRow(user);
// const retrievedUser = await getUserRow('123');
// console.log('Retrieved User:', retrievedUser);
})();