forked from mhsattarian/pvcc_telegram_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
675 lines (600 loc) · 26.6 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*
*
* PVCC Telegram Bot (@pvcc_bot)[https://telegram.me/pvcc_bot]
* Persian Voice Command Collector
*
* Written by:
* Mohammad Hassan Sattarian @MH_Sattarian
* Amir Mohammad Ghoreyshi @AM_Ghoreyshi
*
* Using:
* Nodejs + Telegraf (Telegram Bot API Wrapper)
*
* SRU University
* fall 2018
*
*
*/
// Reads the .env file and add each line in environment variables
// uses for telegram bot api token
require('dotenv').config();
const Telegraf = require('telegraf'), // Telegram Bot API wrapper
Extra = require('telegraf/extra'),
Markup = require('telegraf/markup'),
Composer = require('telegraf/composer'),
Stage = require('telegraf/stage'),
session = require('telegraf/session'),
WizardScene = require('telegraf/scenes/wizard'),
Scene = require('telegraf/scenes/base'),
LocalSession = require('telegraf-session-local'),
shell = require('shelljs'),
{ fork } = require('child_process'),
{ enter } = Stage,
persianJS = require('persianjs'),
rimraf = require('rimraf'),
f2f = require('f2f');
const http = require('http'),
https = require('https'),
fs = require('fs');
/** -------------------- Initilizations --------------- **/
// Adding the Logger
const winston = require('winston');
const { combine, timestamp, label, prettyPrint } = winston.format;
var logger;
handleLogger();
// Start voice files indexing script
const expressUserFiles = fork('./expressUserFiles.js');
// Initilizes and connects to Bot using the Token
const bot = new Telegraf(process.env.BOT_TOKEN);
// Persian Commands to Be spoken!
const commands = [
'روشن',
'خاموش',
'خاموش شو',
'ضبط کن',
'ماشین حساب',
'گرامافون',
'شروع کن',
'برخیز',
'دیتا',
'دوربین',
'سلفی',
'ساعت',
'قفل',
'روشن شو',
'وایفای',
'تماس',
'گالری',
'تنظیمات',
'موزیک',
'تلگرام',
'بالا',
'پایین',
'چپ',
'راست',
'کی ساختت؟',
'متفرقه',
'پس زمینه',
];
// Initilize the Finglish to Farsi Class
const F2F = new f2f();
// Assign an id to commands (id is command in finglish)
commandIds = {}
commands.forEach(command => commandIds[command] = F2F.simplef2f(command))
/** -------------------- on Using --------------- **/
// [*not using now*] A helper function to clear all messages from the bot in this scene
const sceneCleaner = () => async (ctx) => {
// Should store messages in message property of scene's state
ctx.scene.state.messages.forEach(({ message_id: id }) => {
try {
ctx.deleteMessage(id)
} catch (error) {
console.log(error)
}
})
}
// Show a Keyboard of Commands and their voice count
const chooseCommandKeyboard = (userSession) => Markup.keyboard(commands.map(
(item)=> `${item}${
((userSession.commandStatuses[item].voiceCount || 0) >= 3) ? ' ✅' : ''
}`).sort(function(a, b){
if (a.includes('✅') && !b.includes('✅')) return +1;
else if (! a.includes('✅') && b.includes('✅')) return -1;
else return 0;
}))
.oneTime().resize().extra()
// 3. FIRST SCENE : CHOSE YOUR COMMAND
const firstScene = new Scene('choose_command')
.enter(async (ctx) => {
ctx.userSession.lastStage = 'choose_command';
// [*not used now*] for storing messages to be cleared using `sceneCleaner`
// const messages = []
// show a keyboard to user to choose between commands
// messages.push()
// if commands has changed!
var commandsDoneCounter = 0
commands.forEach(command => {
var status = ctx.userSession.commandStatuses[command]
if (status.done)
commandsDoneCounter ++;
if (! status) {
ctx.userSession.commandStatuses[command] = {
voiceCount: 0,
done: false
}
}
});
if (commandsDoneCounter == commands.length) {
return await ctx.reply(`
از شما واقعا ممنونیم که تمامی دستورات را انجام دادید.
میتوانید به دستورات مربوط به خودتون با وارد کردن دستور زیر دسترسی داشته باشید:
/myvoices
یا لینک دانلود تمامی فایلهای صوتی را با وارد کردن دستور زیر دریافت کنید:
/allvoices
`);
}
await ctx.reply('یکی از دستورات را انتخاب کنید:', chooseCommandKeyboard(ctx.userSession))
// ctx.scene.state.messages = messages
})
.command('help', ctx => {
ctx.reply(`
نحوه کار ربات بدین صورت است که در هر مرتبه یک دستور (یک عبارت دستوری) به شما نمایش داده میشود و از شما خواسته میشود که صدای خود در حین خواندن آن دستور را حداقل سه مرتبه ضبط کرده و ارسال کنید.
در حین ضبط یک دستور، یعنی زمانی که هنوز برای بار سوم دستور را نخوانده و ارسال نکردهاید از ارسال متن و یا کامند به بات خودداری کنید.
با استفاده از کامند /myvoices میتوانید آدرسی که فایل صوتی دستورات مربوط به شما در آن ذخیره میشود را مشاهده کنید. همچنین پس از اتمام دستورات فایل شامل صوت تمامی دستورات را دریافت کنید.
`);
})
.command('info', ctx => {
ctx.reply(`
هدف این ربات جمعآوری دادههای صوتی مورد نیاز برای آموزش یک مدل یادگیری عمیق است که قادر به تشخیص دستورات فارسی باشد.
این ربات برای پروژه درس مباحث ویژه کارشناسی با موضوع یادگیری عمیق در دانشگاه شهید رجایی توسعه دادهشده و مورد استفاده قرار خواهد گرفت. البته دیتاست جمعآوری شده نیز به صورت عمومی در دسترس خواهد بود و میتوانید پس از اتمام تمامی دستورات لینک آنرا مشاهده کنید و یا با استفاده از کامند /myvoices آدرسی که فایل صوتی دستورات مربوط به شما در آن ذخیره میشود را مشاهده کنید.
`);
})
.command('credit', ctx => {
ctx.reply(`
لطفا انتقادات، بازخوردها و پیشنهادهای خود را به @MH_Sattarian و @AM_Ghoreyshi ارسال کنید.
`);
})
.command('myvoices', ctx => {
ctx.reply(`
شما میتوانید ویسهای مربوطه خود را در آدرس زیر مشاهده کنید:
http://dataset.class.vision/pvcc/voices/${getSessionKey(ctx).replace(':', '-')}
`);
})
.command('allvoices', ctx => {
ctx.reply(`
لطفا کمی صبر کنید ...
`);
const archiveScript = fork('./makeArchives.js');
archiveScript.send({ force: false});
archiveScript.on('message', (msg) => {
if (msg.status === 'ok') {
ctx.reply(`
برای دریافت تمامی ویسها از لینک زیر استفاده کنید:
http://dataset.class.vision/pvcc/archived/${msg.newZipName}
ممکن است آخرین فایلهای صوتی در فایل موجود نباشند. برای بروز رسانی فایل از دکمه زیر استفاده کنید:
`,
Markup.inlineKeyboard([
Markup.callbackButton('فشردهسازی دوباره', 'reArchive') // Adds a glassy button to start the process
]).extra());
}
else {
ctx.reply(`
مشکلی به وجود آمده. لطفا کمی دیگر دوباره امتحان کنید.
`);
}
});
})
.action('reArchive', (ctx, next) => {
const reArchiveScript = fork('./makeArchives.js');
reArchiveScript.send({ force: true});
reArchiveScript.on('message', (msg) => {
if (msg.status === 'ok') {
ctx.reply(`
آخرین تغییرات در فایل ذخیره شد:
http://dataset.class.vision/pvcc/archived/${msg.newZipName}
`);
}
else {
ctx.reply(`
مشکلی به وجود آمده. لطفا کمی دیگر دوباره امتحان کنید.
`);
}
});
})
// Calling /start on first scene (Do exactly as Bot.start)
.start((ctx) => {
// Chack if User has already initilized the bot and has account in sessions
if ('userName' in ctx.userSession) {
// Check if user wants to delete voices and restart
ctx.reply(`شما پیش از این ربات را فعال کردهاید.
اگر مایلید تا دستورات ثبتشده را پاک کرده و از ابتدا شروع کنید گزینه زیر را انتخاب کنید:`,
Markup.inlineKeyboard([
Markup.callbackButton('شروع مجدد', 'reStart') // Adds a glassy button to start the process
]).extra());
}
else {
// Initializes and Greetings
botInitilizer(ctx);
}
})
.on('text', async (ctx)=>{
// cuase command had become like: روشن شو ✅
command = ctx.message.text.split(' ').filter(word => word != '✅').join(' ');
console.log("Entered: ", command)
if (command === 'متفرقه') {
ctx.reply(`
برای این دستور هر کلمه دلخواهی را به غیر از کلمات لیست بالا میتوانید ضبط و ارسال کنید.
از این دستورات برای شناسایی کلمات بی اهمیت و یا نویزی استفاده میشوند.
`);
}
if (command === 'پس زمینه') {
ctx.reply(`
برای این دستور صداهای پس زمینهای که ممکن است وجود داشته باشند را ارسال کنید.
از این صداها برای تشخیص نویز محیطی استفاده خواهد شد.
`);
}
// Ask for another command if input text not in commands
if (!commands.includes(command)) {
return ctx.scene.reenter()
}
// Stores the command choosen to be pronounced
// (fills in first scene and uses in seconds)
else ctx.userSession.choosenCommand = command;
// If a command is spoken *less than* 3 times, go to second scene (pronouncing commands)
try{
console.log(ctx.userSession.commandStatuses[command]);
if (ctx.userSession.commandStatuses[command].voiceCount < 3) {
ctx.userSession.lastStage = 'get_voices';
ctx.scene.enter('get_voices');
}
// otherwise Error to choose another command
else {
ctx.reply(`
شما این دستور را به تعداد کافی ارسال کرده اید.
اگر میخواهید بازهم آن را ضبط کنید روی دکمه زیر کلیک کنید،
مگرنه یک دستور دیگر انتخاب کنید.
`,
Markup.inlineKeyboard([
Markup.callbackButton('ارسال بیشتر', 'add_more_voice')
]).extra());
}
}
catch(err){
console.log(err);
// Just to make sure no Error is occurred
if (! 'voiceCount' in ctx.userSession.commandStatuses[command])
ctx.userSession.commandStatuses[command].voiceCount = 0;
ctx.scene.reenter();
}
})
// On add_more_voice action (user wants to spoke the command again)
.action('add_more_voice', (ctx, next) => {
ctx.userSession.lastStage = 'get_voices';
ctx.scene.enter('get_voices');
})
// if user tryed to send a recoreded voice in this scene Error
.on('voice', (ctx)=>ctx.reply("لطفا اول یک دستور را انتخاب کنید"))
// What to happen when leaving this scene (including switching between scenes)
.leave(async (ctx)=> {
// ctx.reply("hey",
// {ReplyKeyboardRemove: { remove_keyboard : true }},
// );
console.log("Leaving 1st scene");
});
// SECOND SCENE : PRONOUNCE THE COMMAND
const secondScene = new Scene('get_voices')
.enter((ctx) => {
//TODO: add exit keyboard or command
// Set last stage on user Session
ctx.userSession.lastStage = 'get_voices';
// [*not used now*] for storing messages to be cleared using `sceneCleaner`
// const messages = []
// If the command is pronounced 3 times go back to scene one (choosing commands)
var voiceCount = ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].voiceCount;
// if command's voiceCount is 0 make it 1. cause the counter wont start at 0
if (voiceCount == 0) {
++ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].voiceCount;
voiceCount++;
}
if (voiceCount > 3) {
// User has spoken the command at least 3 times so setting .done to true
if (ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].done == false)
ctx.userSession.commandCounter++;
ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].done = true;
ctx.reply(`
مرتبه ${persianJs((voiceCount).toString()).digitsToWords().toString()}
صدای خود را ضبط کرده و ارسال کنید:
`,
Markup.inlineKeyboard([
Markup.callbackButton('انتخاب دستور دیگر', 'change_command') // Adds a glassy button to start the bot
]).extra());
}
else{
// Ask user to pronounce the command
ctx.reply(`
مرتبه ${persianJs((voiceCount).toString()).digitsToWords().toString()}
صدای خود را ضبط کرده و ارسال کنید:
`)
}
// We want to store the urls to a file called urls.txt
// on a directory named based on user ids
userId = getSessionKey(ctx).replace(':', '-');
addr = `./voices/${userId}/${F2F.simplef2f(ctx.userSession.choosenCommand)}`;
shell.mkdir('-p', addr);
// If urls.txt file not exist create it
if (!fs.existsSync(addr)) {
fs.writeFile(`${addr}/urls.txt`, '', function(err) {
if(err) {
return console.log(err);
}
});
}
// ctx.scene.state.messages = messages
})
.on('voice', (ctx)=>{
// Add command's voiceCount
++ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].voiceCount;
// Thank the user
ctx.reply("👌");
// Take voice file url to be download
userId = getSessionKey(ctx).replace(':', '-');
fileAddr = `./voices/${userId}/${F2F.simplef2f(ctx.userSession.choosenCommand)}/urls.txt`;
url = bot.telegram.getFileLink(ctx.message.voice.file_id).then(url=>{
fs.appendFile(fileAddr, url + '\n', function (err) {
if (err) throw err;
});
});
// ReEnter in current scene to ask for pronounciation again if needed
ctx.scene.reenter();
})
// if user tryed to type something in this scene Error
.on('text', (ctx)=>ctx.reply(`
شما در حال ارسال دستور ${ctx.userSession.choosenCommand} هستید،\
اگر میخواهید دستور دیگری را انتخاب کنید، ابتدا\
لطفا ${persianJs((3 + 1 - ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].voiceCount).toString()).digitsToWords().toString()} مرتبه دیگر همین دستور را ارسال کنید و سپس «انتخاب دستور دیگر» را انتخاب کنید.
`))
// On change_command action (user spoke the command at least 3 times and wants to choose another command)
.action('change_command', (ctx, next) => {
// Downlaodin voice files
const process = fork('./downloadVoices.js');
process.send({ userId: getSessionKey(ctx).replace(':', '-'),
voiceId: F2F.simplef2f(ctx.userSession.choosenCommand)
});
//Cause we added once on line above on enter
--ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].voiceCount;
ctx.reply(`دستور ${ctx.userSession.choosenCommand}، ${persianJs((ctx.userSession.commandStatuses[ctx.userSession.choosenCommand].voiceCount).toString()).digitsToWords().toString()} مرتبه ارسال شد.`);
ctx.userSession.lastStage = 'choose_command';
ctx.scene.enter('choose_command');
})
// What to happen when leaving this scene (including switching between scenes)
.leave(async (ctx) => { // TODO: Add the voice counter here!
console.log("Leaving 2nd scene");
});
// Initialize the session (from now on the session object of ctx can be accessed)
bot.use((new LocalSession({ database: 'sessions.json', property: 'userSession'})).middleware());
// Tell the bot to use these stages
bot.use(session())
// Define Bot stages (scenes)
const stage = new Stage([firstScene, secondScene], { ttl: 1000 })
bot.use(stage.middleware())
// for making sure no webhook is running
bot.telegram.deleteWebhook();
// Start listening for updates from the bot
bot.startPolling();
getSessionKey = (ctx) => {
if (ctx.from && ctx.chat) {
return `${ctx.from.id}:${ctx.chat.id}`
}
return null
}
/** -------------------- on START --------------- **/
// help command - shows usage instructions
bot.command('help', ctx => {
ctx.reply(`
نحوه کار ربات بدین صورت است که در هر مرتبه یک دستور (یک عبارت دستوری) به شما نمایش داده میشود و از شما خواسته میشود که صدای خود در حین خواندن آن دستور را حداقل سه مرتبه ضبط کرده و ارسال کنید.
در حین ضبط یک دستور، یعنی زمانی که هنوز برای بار سوم دستور را نخوانده و ارسال نکردهاید از ارسال متن و یا کامند به بات خودداری کنید.
با استفاده از کامند /myvoices میتوانید آدرسی که فایل صوتی دستورات مربوط به شما در آن ذخیره میشود را مشاهده کنید. همچنین پس از اتمام دستورات فایل شامل صوت تمامی دستورات را دریافت کنید.
`);
});
function botInitilizer (ctx) {
// choose active user's session from the session object
var userSession = ctx.userSession;
// Number of the command to get its voice
userSession.commandCounter = 0;
// Users last stage (for controling stages and when they expire)
userSession.lastStage = '';
// Status of each command (whether its spoken and how many times)
userSession.commandStatuses = {};
commands.map(command=>{
userSession.commandStatuses[command] = {
done: false, // each command should be sponek at least 3 times
voiceCount : 0, // how many times this command is spoken
}
})
// Save user's username , name
userSession.userName = ctx.from.username;
userSession.fullName = ctx.from.first_name || '' + ctx.from.last_name || '';
// Greetings
ctx.reply(`
سلام ${userSession.userName || '' + userSession.fullName || ''}، ممنونیم که وقت خودتون رو در اختیار ما گذاشته و به جمعآوری دیتاستی از دستورات فارسی کمک میکنید.
در ادامه پس از انتخاب گزینه شروع، در هر مرتبه یک دستور (یک عبارت دستوری) به شما نمایش داده میشود و از شما خواسته میشود که صدای خود در حین خواندن آن دستور را حداقل سه مرتبه ضبط کرده و ارسال کنید.
توجه کنید که اطلاعات نامعتبر پس از بررسی حذف خواهند شد.
برای شروع گزینه زیر را انتخاب کنید:
`,
Markup.inlineKeyboard([
Markup.callbackButton('شروع', 'start_confirmed') // Adds a glassy button to start the bot
]).extra());
}
// 1. Initializations and greetings
bot.start((ctx) => {
// Chack if User has already initilized the bot and has account in sessions
if ('userName' in ctx.userSession) {
// Check if user wants to delete voices and restart
ctx.reply(`شما پیش از این ربات را فعال کردهاید.
اگر مایلید تا دستورات ثبتشده را پاک کرده و از ابتدا شروع کنید گزینه زیر را انتخاب کنید:`,
Markup.inlineKeyboard([
Markup.callbackButton('شروع مجدد', 'reStart') // Adds a glassy button to start the process
]).extra());
}
else {
// Initializes and Greetings
botInitilizer(ctx);
}
});
// 2. When the شروع glassy button is pressed
bot.action('start_confirmed', (ctx, next) => {
// Tell user about the bot's commands
ctx.reply(`
- کامندهای ربات
/help - مشاهده روش استفاده از ربات
/info - مشاهده اطلاعات مربوط به ربات
/credit - مشاهده اطلاعات سازندگان ربات
/myvoices - مشاهده آدرسی که توسط آن به فایلهای صوتی خود دسترسی دارید
`);
// enter first scene (Choose command)
ctx.scene.enter('choose_command')
// store the last stage
ctx.userSession.lastStage = 'choose_command';
});
// When user chosed to restart the bot
bot.action('reStart', (ctx, next) => {
// Clear all User data
ctx.userSession = {}
// Remove user voices
rimraf(`./voices/${getSessionKey(ctx).replace(':', '-')}`, function () {
console.log('User data deleted.');
});
// Initilize the bot again
botInitilizer(ctx);
});
// Session command for debugging
bot.command('session', ctx => {
ctx.reply('session: \n' + JSON.stringify(ctx.session));
ctx.reply('UserSession: \n' + JSON.stringify(ctx.userSession));
});
// info command - shows information about the bot
bot.command('info', ctx => {
ctx.reply(`
هدف این ربات جمعآوری دادههای صوتی مورد نیاز برای آموزش یک مدل یادگیری عمیق است که قادر به تشخیص دستورات فارسی باشد.
این ربات برای پروژه درس مباحث ویژه کارشناسی با موضوع یادگیری عمیق در دانشگاه شهید رجایی توسعه دادهشده و مورد استفاده قرار خواهد گرفت. البته دیتاست جمعآوری شده نیز به صورت عمومی در دسترس خواهد بود و میتوانید پس از اتمام تمامی دستورات لینک آنرا مشاهده کنید و یا با استفاده از کامند /myvoices آدرسی که فایل صوتی دستورات مربوط به شما در آن ذخیره میشود را مشاهده کنید.
برنامه این ربات متنباز بوده و در آدرس زیر در دسترس است:
https://github.com/mhsattarian/pvcc_telegram_bot
`);
});
// credit command - shows developers credit
bot.command('credit', ctx => {
ctx.reply(`
لطفا انتقادات، بازخوردها و پیشنهادهای خود را به @MH_Sattarian و @AM_Ghoreyshi ارسال کنید.
`);
});
// myvoices command - shows myvoices address
bot.command('myvoices', ctx => {
ctx.reply(`
شما میتوانید ویسهای مربوطه خود را در آدرس زیر مشاهده کنید:
http://dataset.class.vision/pvcc/voices/${getSessionKey(ctx).replace(':', '-')}
`);
});
// allvoices command - shows link to download all voices
bot.command('allvoices', ctx => {
ctx.reply(`
لطفا کمی صبر کنید ...
`);
const archiveScript = fork('./makeArchives.js');
archiveScript.send({ force: false});
archiveScript.on('message', (msg) => {
if (msg.status === 'ok') {
ctx.reply(`
برای دریافت تمامی ویسها از لینک زیر استفاده کنید:
http://dataset.class.vision/pvcc/archived/${msg.newZipName}
ممکن است آخرین فایلهای صوتی در فایل موجود نباشند. برای بروز رسانی فایل از دکمه زیر استفاده کنید:
`,
Markup.inlineKeyboard([
Markup.callbackButton('فشردهسازی دوباره', 'reArchive') // Adds a glassy button to start the process
]).extra());
}
else {
ctx.reply(`
مشکلی به وجود آمده. لطفا کمی دیگر دوباره امتحان کنید.
`);
}
});
});
// When user chosed to restart the bot
bot.action('reArchive', (ctx, next) => {
const reArchiveScript = fork('./makeArchives.js');
reArchiveScript.send({ force: true});
reArchiveScript.on('message', (msg) => {
if (msg.status === 'ok') {
ctx.reply(`
آخرین تغییرات در فایل ذخیره شد:
http://dataset.class.vision/pvcc/archived/${msg.newZipName}
`);
}
else {
ctx.reply(`
مشکلی به وجود آمده. لطفا کمی دیگر دوباره امتحان کنید.
`);
}
});
});
// Handle out of stage voices and texts
// and enter the last stage that user used
bot.on(['text', 'voice'], (ctx) => {
console.log("[Bot] voice or text")
// Return if text is a unrecognized command
if ('text' in ctx.message && ctx.message.text.startsWith('/')) return
// prompt a message to let user know that ttl is expired
ctx.reply(`
ببخشید فراموش کردم کجا بودیم! دوباره امتحان کنید:
`);
// Try to go to last stage
if ('lastStage' in ctx.userSession) {
try {
var LS = ctx.userSession.lastStage;
var CC = ctx.userSession.choosenCommand;
console.log(LS, CC);
// if (LS && CC) ctx.userSession.commandStatuses[CC].voiceCount--;
ctx.scene.enter(LS)
}
catch (err){
console.log(err);
botInitilizer(ctx);
}
}
else {
// The session file has been removed so user should be initialized
botInitilizer(ctx);
}
})
function handleLogger() {
// Create log directory if dont exist
if (!fs.existsSync('logs')) {
fs.mkdirSync('./logs');
fs.writeFileSync(`./logs/combined.log`, '');
fs.writeFileSync(`./logs/error.log`, '');
}
// Initialize logger (Winston)
logger = winston.createLogger({
level: 'info',
format: combine(
timestamp(),
prettyPrint()
),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: './logs/error.log', level: 'error' }),
new winston.transports.File({ filename: './logs/combined.log' })
]
});
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
}