-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1466 lines (1222 loc) · 54.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
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//"use strict" // Causes memory issues in Heroku free plan
const numCPUs = require('os').cpus().length
console.log(`Number of CPUs is: ${numCPUs}`)
function toBoolean(x) {
if (typeof x === 'object') {
for (var i in x) return true
return false
}
return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())
}
const telegramToken = process.env.telegramToken ?? 0
const inst = process.env.inst ?? 0
const host = process.env.host ?? "Host"
const totalInst = process.env.totalInst ?? 0
const activeInst = process.env.activeInst ?? "0@Host" //unused for now
const instActivetUntil = process.env.instActiveUntil ?? "🤷"
const branch = process.env.branch ?? "staging"
const debugging = toBoolean(process.env.debugging)
const devChatId = process.env.devChatId ?? 0 // the group ID of development team on Telegram
const codeVer = process.env.npm_package_version ?? "1970.1.1-0"
// Use log(x) instead of log(x) to control debugging mode from env variables
// Use log(x, e) for errors
function log(x, e){
return new Promise ((resolve, reject) =>{
switch(log.arguments.length){
case 1:
if(debugging) console.log(x)
resolve()
break
case 2:
console.error(x, e)
if(bot) {
bot.telegram.sendMessage(devChatId, (x+(JSON.stringify(e))).substring(0, 4096))
.then(resolve())
.catch(er => {
console.error(`Error while sending log to devChat: `, er)
resolve()
})
}
break
default:
console.error('Invalid log argument count.')
resolve()
break
}
})
}
function instStateMsg(){
return `DailyAyaTelegram ${branch} instance ${inst}@${host} (of total ${totalInst}) is active in ${
debugging ? 'debugging' : 'normal'} mode of version ${codeVer} until ${instActivetUntil}.\n
Memory Used: ${Math.floor(process.memoryUsage().rss / (1024 * 1024))} MB\n
Uptime: ${+(process.uptime()/3600).toFixed(2)} hours`
}
// just for web to manage sleep and balance between multiple instances
const express = require('express')
const expressApp = express()
const port = process.env.PORT ?? 3000
// main route will respond instStateMsg when requested.
// we call it every 15 minutes using a google app script to prevent the app from sleeping.
expressApp.get('/', (req, res) => {
res.send(instStateMsg())
})
expressApp.listen(port, () => {
log(`Listening on port ${port}`)
})
// MongoDB is a pool and always open
var dbConn
const { MongoClient, ServerApiVersion } = require('mongodb')
const mongoDbCredentials = process.env.mongoDbCredentials
const mongoSubdomain = process.env.mongoSubdomain
const uri = `mongodb+srv://${mongoDbCredentials}@cluster0.${mongoSubdomain}.mongodb.net/?retryWrites=true&w=majority&maxPoolSize=50&keepAlive=true`
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 })
log('Connecting to MongoDB...')
client.connect((err, db) => {
if (err) log('MongoDbConn ERROR: ', err)
else {
log('MongoDbConn Connected!')
dbConn = db
timerSend()
.catch(e => {
log(`Error while calling timerSend inside dbConn: `, e)
})
}
})
// Records the last time an aya was sent to a chat so we can send again periodically (daily, for example)
function lastAyaTime(chatId, status, chatName, chatType, lang, trigger){
var setObj = {}
status = status ?? "success" // Function can be called with chatId only if not blocked
setObj.since = {$cond: [{$not: ["$since"]}, new Date(), "$since"]} // Add "Since" date only once
setObj.lastAyaTime = Date.now()
setObj.blocked = status.toLowerCase().includes('block')
if(chatName) setObj.name = { $literal: chatName } // Only update the name when it's known and don't interpert "$" as a field path
if(lang) setObj.language_code = lang // Only update the language_code when it's known
if(chatType) setObj.chatType = chatType // Only update the chatType when it's known
if(trigger){
setObj.lastTrigger = trigger
switch (trigger) {
case 'surprise':
setObj.surprises = {$cond: [{$not: ["$surprises"]}, 1, {$add: ["$surprises", 1]}]}
break;
case 'next':
setObj.nexts = {$cond: [{$not: ["$nexts"]}, 1, {$add: ["$nexts", 1]}]}
break;
case 'request':
setObj.requests = {$cond: [{$not: ["$requests"]}, 1, {$add: ["$requests", 1]}]}
break;
case 'timer':
setObj.timers = {$cond: [{$not: ["$timers"]}, 1, {$add: ["$timers", 1]}]}
break;
default:
log('Unknown trigger: ', trigger)
break;
}
}
dbConn.db('dailyAyaTelegram').collection('chats').updateOne(
{chatId: chatId},
[{$set: setObj}],
{upsert: true}
).then(log('Recorded Last Aya Time for chat '+chatId+' as '+ (setObj.blocked ? "blocked." : "successfuly sent.")))
.catch(e => log('Failed to record Last Aya Time for chat '+chatId+' and object '+JSON.stringify(setObj)+': ', e))
}
// Sets the favorit reciter for chatIds that request so
function setFavReciter(chatId, reciterIdentifier){
var setObj = {}
log(`Chat ${chatId} fav reciter request: ${reciterIdentifier}`)
// sets reciter to "surprise" if not provided or reciter is not valid
reciterIdentifier = (reciterIdentifier == "surprise" || isValidReciter(reciterIdentifier)) ? reciterIdentifier : "surprise"
log(`Chat ${chatId} fav reciter to be stored: ${reciterIdentifier}`)
setObj.favReciter = reciterIdentifier
dbConn.db('dailyAyaTelegram').collection('chats').updateOne(
{chatId: chatId},
[{$set: setObj}],
{upsert: true}
)
.then(() => {
log(`Favorit reciter "${reciterIdentifier}" has been set for chat ${chatId}.`)
var msg
if (reciterIdentifier == "surprise") {
msg =
`سيتم تغيير القارئ مع كل آية مفاجئة.
Reciter will be changed with each surprise Aya.`
} else {
var requestedFavReciterData = arReciters.filter(i => i.identifier == reciterIdentifier)
msg =
`القارئ المفضل الحالي: ${requestedFavReciterData[0].name}
Current Favorit Reciter: ${requestedFavReciterData[0].englishName}`
}
bot.telegram.sendMessage(chatId, msg, {
reply_markup: {
inline_keyboard:[
[{
text: "🎁",
callback_data: "surpriseAya"
}]
]
}
})
})
.catch(e => {
log(`Error while setting favorit reciter "${reciterIdentifier}" for chat ${chatId}:`, e)
msg =
`عذرا.. نواجه مشكلة أثناء حفظ القارئ المفضل ونأمل حلها قريبا.
Sorry.. There's an issue while setting favorite reciters and we hope it gets fixed soon.`
bot.telegram.sendMessage(chatId, msg, {
reply_markup: {
inline_keyboard:[
[{
text: "🎁",
callback_data: "surpriseAya"
}]
]
}
}).catch(er => log(`Error while sending sorry for failing to set fav reciter: `, er))
})
}
// Gets the favorit reciter for chatIds requesting surprise Aya
function getFavReciter(chatId){
return new Promise ((resolve, reject) => {
log(`Getting fav reciter for Chat ${chatId}`)
if (chatId){
dbConn.db('dailyAyaTelegram').collection('chats').find({chatId: chatId}).toArray((err, res) => {
if (err){
log(`Error while getting favReciter for chat ${chatId}: `, err)
reject(err)
} else {
resolve(res[0]?.favReciter ?? 0) // Resolve with favReciter if it exists, or 0 if not
}
})
} else {
resolve(0)
}
})
}
//timer to fetch database every 15 minutes to send aya every 24 hours to chats who didn't block the bot.
const checkMinutes = process.env.TimerCheckMinutes ?? 15 // That means checking database every 15 minutes
const sendHours = process.env.TimerSendHours ?? 24 // That means sending an Aya every 24 hours, for example
const checkMillis = checkMinutes * 60 * 1000
const sendMillis = (sendHours * 60 * 60 * 1000)-checkMillis // For example, (24 hours - 15 minutes) to keep each chat near the same hour, otherwise it will keep shifting
function timerSend(){
return new Promise((resolve, reject) =>{
try {
dbConn.db('dailyAyaTelegram').collection('chats').find({lastAyaTime: {$lte: Date.now()-sendMillis}, blocked: false}).toArray( (err, res) => {
if (err) {
log('Timer dbConn error: ', err)
reject(err)
} else {
log(`Used memory: ${Math.floor(process.memoryUsage().rss / (1024 * 1024))} MB`)
// removed this warning as we spread sending by putting a 50ms delay between each message (20 msg/sec)
// if(res.length > 20) log('Warning: Almost reaching Telegram sending limits. Max is 30 users/sec. Current: ', res.length)
log(`Timer will send to ${res.length} chats.`)
res.forEach((chat, index) => {
setTimeout(() => {
sendAya(chat.chatId, "", chat.favReciter, "", 'timer')
}, 50 * index) // 50ms delay between messages for 20 msg/sec
})
resolve()
}
})
} catch (e) {
if (!e.message.includes(`Cannot read property 'db'`)){
log('Timer unexpected error: ', e)
}
reject(e)
}
})
}
// Delay first timerSend until next quarter hour
const timerNow = new Date()
const timerFirstDelay = (15 - timerNow.getMinutes() % 15) * 60 * 1000 - timerNow.getSeconds() * 1000 - timerNow.getMilliseconds()
setTimeout(() => {
timerSend()
// Call timerSend every 15 minutes after the first execution
const dailyTimer = setInterval(timerSend, checkMillis)
}, timerFirstDelay)
// Using Telegraf NodeJS framework for Telegram bots
const {Telegraf} = require('telegraf')
const bot = new Telegraf(telegramToken)
bot.telegram.getMe().then((botInfo) => { // for handling group commands without calling "launch"
bot.options.username = botInfo.username
})
// Inform Dev group about the instance state
if(telegramToken){
bot.telegram.sendMessage(devChatId, instStateMsg())
.catch(er => log(`Error while sending instance state: `, er))
}
async function start(chatId){
var msg =
`دايلي آية يرسل آية واحدة يوميا في نفس موعد آخر آية تطلبوها في الدردشات الشخصية أو المجموعات والقنوات حتى لا ينقطع وردكم اليومي.
لمعرفة الأوامر المتاحة:
/commands
Daily Aya sends one Aya daily at the same time of the last Aya you request in private chats or groups and channels so your daily read doesn't stop.
For available commands:
/commands`
bot.telegram.sendMessage(chatId, msg, {
reply_markup: {
inline_keyboard:[
[{
text: "🎁",
callback_data: "surpriseAya"
}]
]
}
})
.then(c => successSend(c, 0, "", "request"))
.catch(e => log("Error while sending start: ", e))
.finally(f => summaryStats())
}
async function summaryStats(){
// Informing "DailyAya Dev" of total active and blocked chats when /start is called by any user
try {
var privateActiveChats = await dbConn.db('dailyAyaTelegram').collection('chats').countDocuments({blocked: false, chatType: "private"})
var otherActiveChats = await dbConn.db('dailyAyaTelegram').collection('chats').countDocuments({blocked: false, chatType: {$ne: "private"}})
var totalBlockedChats = await dbConn.db('dailyAyaTelegram').collection('chats').countDocuments({blocked: true})
var totalChatsMsg = `Total Active: ${privateActiveChats+otherActiveChats} Blocked: ${totalBlockedChats}\n`
+ `Private Active: ${privateActiveChats} Others: ${otherActiveChats}`
log(totalChatsMsg)
bot.telegram.sendMessage(devChatId, totalChatsMsg)
.catch(err => log(`Error while sending active stats: `, err))
} catch (e) {
log('Error while getting total chats: ', e)
}
}
// Returns a random number based on input
// if no input or input is "aya": a random aya number in the whole quran (1 to 6236)
// if input is "reciter": a random number representing one of the available reciters
function random(type){
var max = 6236 // default for aya number
if (type == "reciter"){
max = arReciters.length
return arReciters[Math.floor(Math.random() * Math.floor(max))].identifier
}
// +1 because the generated numbers are between 0 and max-1
else return Math.floor(Math.random() * Math.floor(max)) + 1
}
const axios = require('axios')
const arQuran = require('./quran-uthmani.json').data.surahs
const enQuran = require('./en.ahmedraza.json').data.surahs
const arReciters = require('./audio.json').data.filter(i => i.language == "ar")
function checkSource(){
var downloadStart = process.uptime()
// Cancelling checking Arabic source due to needed manual fixes in some Ayas in the JSON file directly
/*
axios("http://api.alquran.cloud/v1/quran/quran-uthmani")
.then(r =>{
if(JSON.stringify(r.data.data.surahs) != JSON.stringify(arQuran)){
bot.telegram.sendMessage(devChatId,
`Remote arQuran has changed. Please update the cached JSON file.`
).catch(er => log(`Error while sending arQuran change: `, er))
} else {
log(`Remote arQuran is the same as the cached JSON file. It took ${((process.uptime()-downloadStart)).toFixed(2)} seconds.`)
}
})
.catch(e => log('Error while comparing arQuran cached vs remote: ', e))
*/
axios("http://api.alquran.cloud/v1/quran/en.ahmedraza")
.then(r =>{
if(JSON.stringify(r.data.data.surahs) != JSON.stringify(enQuran)){
bot.telegram.sendMessage(devChatId,
`Remote enQuran has changed. Please update the cached JSON file.`
).catch(er => log(`Error while sending enQuran change: `, er))
} else {
log(`Remote enQuran is the same as the cached JSON file. It took ${((process.uptime()-downloadStart)).toFixed(2)} seconds.`)
}
})
.catch(e => log('Error while checking enQuran cached vs remote: ', e))
axios("http://api.alquran.cloud/edition/format/audio")
.then(r =>{
if(JSON.stringify(r.data.data.filter(i => i.language == "ar")) != JSON.stringify(arReciters)){
bot.telegram.sendMessage(devChatId,
`Remote arReciters has changed. Please update the cached JSON file.`
).catch(er => log(`Error while sending arReciters change: `, er))
} else {
log(`Remote arReciters is the same as the cached JSON file. It took ${((process.uptime()-downloadStart)).toFixed(2)} seconds.`)
}
})
.catch(e => log('Error while checking arReciters cached vs remote: ', e))
}
if(!debugging) {
checkSource()
}
function ayaId2suraAya(ayaId){
var sura = 0,
aya = 0
if(1 <= ayaId && ayaId <= 6236){
sura = enQuran.find(s => s.ayahs.find(a => a.number == ayaId)).number
aya = enQuran[sura-1].ayahs.find(a => a.number == ayaId).numberInSurah
}
return {sura: sura, aya: aya} // Returns {sura: 0, aya: 0} if not valid ayaId
}
function suraAya2ayaId(suraAya){ // suraAya = {sura: suraNum, aya: ayaNum}
var sura = suraAya.sura,
aya = suraAya.aya,
ayaId
if (1 <= sura && sura <= 114){
var ayaData = enQuran[sura-1].ayahs.find(a => a.numberInSurah == aya)
ayaId = ayaData ? ayaData.number : 0 // return 0 if valid Sura but invalid Aya
} else {
ayaId = -1 // return -1 if invalid Sura
}
return ayaId
}
// Prepare an Aya to be sent
function prepareAya(ayaId){
String.prototype.toArNum = function() {return this.replace(/\d/g, d => '٠١٢٣٤٥٦٧٨٩'[d])}
var ayaIndex = ayaId2suraAya(ayaId),
suraNum = ayaIndex.sura,
ayaNum = ayaIndex.aya,
arAya = arQuran[suraNum-1].ayahs[ayaNum-1].text,
enTranslatedAya = enQuran[suraNum-1].ayahs[ayaNum-1].text,
arName = enQuran[suraNum-1].name.substr(8), // substr(8) to remove the Arabic word "Sura".
enArName = enQuran[suraNum-1].englishName,
enTranslatedName = enQuran[suraNum-1].englishNameTranslation,
arIndex = `﴿<a href="t.me/${bot.options.username}?start=${suraNum}-${ayaNum}">${arName} ${ayaNum.toString().toArNum()}</a>﴾`,
enIndex = `<a href="t.me/${bot.options.username}?start=${suraNum}-${ayaNum}">"${enArName}: ${enTranslatedName}", Sura ${suraNum} Aya ${ayaNum}</a>`,
arText = `<b>${arAya}</b>\n${arIndex}`,
enText = `${enTranslatedAya}\n<i>{An interpretation of ${enIndex}}</i>`
return {arText: arText, enText: enText}
}
// For inline keyboard when setting favorite reciter
var recitersInlineButtons = []
function recitersButtons(reciters){
reciters.forEach(reciter => {
recitersInlineButtons.push([{
text: `${reciter.englishName} ${reciter.name}`,
callback_data: `{"setReciter": "${reciter.identifier}"}`
}])
})
}
recitersButtons(arReciters)
// returns a URL string for the audio file of the requested aya (is a must)
// if reciter is not requested or not supported, a random reciter will be provided
// Must be called with .then .catch
var recitationTries = [] // ['aya/reciter']
function recitation(aya, reciter){
return new Promise((resolve, reject) => {
reciter = isValidReciter(reciter) ? reciter : random('reciter')
axios(`http://api.alquran.cloud/ayah/${aya}/${reciter}`)
.then(res => {
recitationTries = recitationTries.filter(i => i != `${aya}/${reciter}`) // Remove from tries due to success
var allAudio = [res.data.data.audio].concat(res.data.data.audioSecondary)
audioPicker(allAudio, 0)
.then(pick => resolve(pick))
.catch(e => reject(e))
}).catch(e => {
log('Recitation Error: ', e)
recitationTries.push(`${aya}/${reciter}`)
if (recitationTries.filter(`${aya}/${reciter}`).length <= 3) {
setTimeout(
recitation(aya, reciter)
.then(r => resolve(r))
.catch(e => log("Recitattion Try Error: ", e)), // Don't reject inside loop
1000);
} else {
recitationTries = recitationTries.filter(i => i != `${aya}/${reciter}`) // Remove from tries due to max tries
reject(e)
}
})
})
}
function isValidReciter(reciter){
var validReciter = false
for (let i = 0; i < arReciters.length; i++) {
if(arReciters[i].identifier == reciter) {
validReciter = true
break
}
}
return validReciter
}
function audioPicker(audioUrlArray, i){
return new Promise((resolve, reject) =>{
audioUrlCheck(audioUrlArray[i])
.then(isAvailable =>{
if(isAvailable) resolve(audioUrlArray[i])
else if (i+1 < audioUrlArray.length){
audioPicker(audioUrlArray, i+1)
.then(pick => resolve(pick))
.catch(e => reject(e))
} else reject ('All audio files are not available.')
})
.catch(e => log("AuidoPicker Error: ", e)) // Don't reject inside the loop until it finishes
})
}
function audioUrlCheck(url){
return new Promise((resolve, reject) =>{
axios.head(url)
.then(r =>{
log('Fetched audio file URL headers.')
// log(`Audio URL header: ${JSON.stringify(r.headers)}`)
if(r.status >= 200 && r.status < 300) resolve(true)
else {
log(`Error in audio file "${url}" header: `, r.headers)
resolve(false)
}
})
.catch(e => resolve(false)) // No reject if URL request failed
})
}
// Send random Aya and random reciter if called with the userId argument only
function sendAya(chatId, ayaId, reciter, lang, trigger, withRecitation){
log(`Initiating sending an Aya to chat ${chatId} with requested reciter: ${reciter ? reciter : "None"}`)
ayaId = ayaId || random('aya')
withRecitation = withRecitation || false
sendAyaText(chatId, ayaId, reciter, lang, trigger)
.then((ctx) => {
if (withRecitation) {
sendAyaRecitation(ctx, ayaId, reciter)
}
})
.catch(e => {
log(`Error while sending Aya ${ayaId} text to chat ${chatId}: `, e)
let asBlocked = /blocked by the user|user is deactivated|need administrator rights|not enough rights|chat not found|TOPIC_CLOSED|bot was kicked|CHAT_SEND_PLAIN_FORBIDDEN/
if(asBlocked.test(JSON.stringify(e))){
lastAyaTime(chatId, 'blocked')
}
})
}
function sendAyaText(chatId, ayaId, reciter, lang, trigger){
return new Promise ((resolve, reject) => {
log(`Formatting Aya ${ayaId} for chat ${chatId}`)
reciter = reciter ? reciter : "None"
var preparedAya = prepareAya(ayaId), // Prepare Aya text
ayaDualText = `${preparedAya.arText}\n\n${preparedAya.enText}`, // Add an empty line between Arabic and English Aya text
buttons = aMenuButtons("t0", ayaId, reciter) // Prepare buttons to be sent with Aya text
// send aya text and inline buttons
bot.telegram.sendMessage(chatId, ayaDualText, {
disable_web_page_preview: true,
disable_notification: true,
parse_mode: 'HTML',
reply_markup: buttons
})
.then(c => {
successSend(c, ayaId, lang, trigger)
resolve(c)
})
.catch(e => {
if (e.response.description.includes('upgraded to a supergroup')){
sendAyaText(e.response.parameters.migrate_to_chat_id, ayaId, reciter, lang, trigger)
lastAyaTime(chatId, 'blocked')
} else {
reject(e)
}
})
})
}
function sendAyaRecitation(ctx, ayaId, reciter){
return new Promise ((resolve, reject) => {
var audioSuccess, favReciterReady, recitationReady, buttons, chatId = ctx.chat.id
getFavReciter(isValidReciter(reciter) ? 0 : chatId) // getFavReciter will resolve 0 if there's a valid reciter
.then(favReciter => {
favReciterReady = true
reciter = isValidReciter(favReciter || "None") ? favReciter : (isValidReciter(reciter) ? reciter : random('reciter'))
log(`Chat ${chatId} got reciter: ${reciter}`)
var suraAyaIndex = ayaId2suraAya(ayaId),
recitationCaption =
`<a href="t.me/${bot.options.username}?start=${suraAyaIndex.sura}-${suraAyaIndex.aya}">@${
bot.options.username} ➔ ${suraAyaIndex.sura}:${suraAyaIndex.aya}</a>`
buttons = aMenuButtons("r0", ayaId, reciter)
recitation(ayaId, reciter)
.then(recitationUrl => {
recitationReady = true
bot.telegram.sendAudio(chatId, recitationUrl, {caption: recitationCaption, parse_mode: 'HTML', disable_notification: true})
.then((c) =>{
audioSuccess = true
var message_id = ctx.message_id || ctx.update.callback_query.message.message_id
if (c.message_id != 1 + message_id){ // Refer/Reply to the text if the recitation is not sent right after it
audioSuccess = false
bot.telegram.deleteMessage(chatId, c.message_id)
.then (() => {
bot.telegram.sendAudio(chatId, recitationUrl, {
reply_to_message_id: message_id,
caption: recitationCaption, parse_mode: 'HTML', disable_notification: true
})
.then((r) => {
audioSuccess = true
bot.telegram.editMessageReplyMarkup(chatId, message_id, null, null)
.then (() => {
bot.telegram.editMessageReplyMarkup(chatId, r.message_id, null, aMenuButtons("r0", ayaId, reciter))
.then(() => resolve(r))
.catch(er => log(`Error while adding recitation reply buttons: `, er))
}).catch(er => log(`Error while deleting text buttons after reply: `, er))
}).catch(er => log(`Error while resending recitation: `, er))
})
} else {
bot.telegram.editMessageReplyMarkup(chatId, message_id, null, null)
.then (() => {
bot.telegram.editMessageReplyMarkup(chatId, c.message_id, null, aMenuButtons("r0", ayaId, reciter))
.then(() => resolve(c))
.catch(er => log(`Error while adding recitation buttons: `, er))
}).catch(er => log(`Error while deleting text buttons: `, er))
}
})
.catch(e => {
log(`Error while sending recitation for aya ${ayaId} by ${reciter} to chat ${chatId}: `, e)
if(JSON.stringify(e).includes('blocked by the user')) {
lastAyaTime(chatId, 'blocked')
} else if(!audioSuccess) {
sendSorry(chatId, 'audio')
}
reject(e)
})
})
.catch(e => {
log(`Error while getting recitation URL for aya ${ayaId} by ${reciter} for chat ${chatId}: `, e)
if(!recitationReady) {
sendSorry(chatId, 'audio')
}
reject(e)
})
})
.catch(e => {
log(`Error while calling getFavReciter for chat ${chatId}: `, e)
if (!favReciterReady){
sendAyaRecitation(ctx, ayaId, "random") // try again with a random reciter
}
})
})
}
function aMenuButtons(menuState, ayaId, reciter){
var buttons = {inline_keyboard: [[{
text: menuState.includes("0") ? "···" : "•••",
callback_data: `{"aMenu":"${menuState}","a":${ayaId},"r":"${reciter}"}`
}]]}
if (menuState.includes("1")){
var ayaIndex = ayaId2suraAya(ayaId)
buttons.inline_keyboard[0].push({
text: "⚠️",
url: `https://sherbeeny.t.me?text=%D8%A7%D9%84%D8%B3%D9%84%D8%A7%D9%85%20%D8%B9%D9%84%D9%8A%D9%83%D9%85%20%D9%8A%D8%A7%20%D9%85%D8%B7%D9%88%D8%B1%20%D8%AF%D8%A7%D9%8A%D9%84%D9%8A%20%D8%A2%D9%8A%D8%A9%0A%D8%B1%D8%AC%D8%A7%D8%A1%20%D9%85%D8%B1%D8%A7%D8%AC%D8%B9%D8%A9%20%D8%A7%D9%84%D8%A2%D9%8A%D8%A9%20${ayaIndex.sura}:${ayaIndex.aya}%0A%0APeace%20upon%20you%2C%20Daily%20Aya%20developer%0APlease%20revise%20Aya%20${ayaIndex.sura}:${ayaIndex.aya}`
//callback_data: `{"aReport":${ayaId},"r":"${reciter}"}`
})
if (menuState == "r1") { // Show setReciter button only when it's a menu of a recitation
buttons.inline_keyboard[0].push({
text: "🗣️",
callback_data: `{"setReciter":"${reciter}","a":${ayaId}}`
})
}
buttons.inline_keyboard[0].push({
text: "📖",
url: `https://quran.com/${ayaIndex.sura}:${ayaIndex.aya}/tafsirs/ar-tafsir-muyassar`
})
}
if (menuState.includes("t")) { // Show recitation button only when it's a menu of text
buttons.inline_keyboard[0].push({
text: "🔊",
callback_data: `{"recite":${ayaId},"r":"${reciter}"}`
})
}
buttons.inline_keyboard[0].push({
text: "▼",
callback_data: `{"currAya":${ayaId},"r":"${reciter}"}`
})
return buttons
}
function successSend(ctx, ayaId, lang, trigger){
var chatType = ctx.chat.type
var chatName = chatType == 'private' ? ctx.chat.first_name : ctx.chat.title
log(`Successfully sent Aya ${ayaId} has been sent to chat ${ctx.chat.id}`)
lastAyaTime(ctx.chat.id, 'success', chatName, chatType, lang, trigger)
}
function sendSorry(chatId, reason){
return new Promise((resolve, reject) =>{
var msg
switch (reason) {
case 'audio':
msg =
`عذرا.. نواجه مشكلة في الملفات الصوتية ونأمل إصلاحها قريبا.
Sorry.. There's an issue in audio files and we hope it gets fixed soon.`
break
case 'text':
msg =
`عذرا.. نواجه مشكلة في نصوص الآيات ونأمل إصلاحها قريبا.
Sorry.. There's an issue in Aya texts and we hope it gets fixed soon.`
break
default:
msg =
`عذرا.. حدثت مشكلة غير معروفة.
Sorry.. An unknown issue happened.`
break
}
bot.telegram.sendMessage(chatId, msg, {disable_notification: true})
.then(ctx => {
log(`Sorry message sent to ${chatId} due to ${reason}.`)
resolve(ctx)
})
.catch(e => {
log(`Failed to send sorry message to ${chatId}: `, e)
reject(e)
})
})
}
function nextAya(ayaId){
return ayaId == 6236 ? 1 : ayaId+1
}
// Sends an error message if unrecognized aya
function unrecognized(ctx, reason){
var chatId = ctx.chat.id
adminChecker(ctx)
.then(isAdmin =>{
if(isAdmin){
var msg
switch (reason) {
case 1:
msg =
`عذرا، لم نتعرف على اسم سورة باللغة العربية أو رقم سورة من 1 إلى 114.
Sorry, we couldn't recognize a Sura name in Arabic or Sura number from 1 to 114.`
break;
case 2:
msg =
`عذرا، رقم الآية ليس في السورة المطلوبة.
Sorry, Aya number is not in the requested Sura.`
break;
case 3:
msg =
`عذرا، حاليا نتعرف فقط على أسماء السور باللغة العربية أو أرقام السور والآيات في الرسائل النصية.
Sorry, we currently only recognize Sura names in Arabic or numbers of Sura and Aya in text messages.`
break;
default:
msg =
`خطأ غير معروف!
Unknown error!`
break;
}
bot.telegram.sendMessage(chatId, msg, {
reply_markup: {
inline_keyboard:[
[{
text: "🎁",
callback_data: "surpriseAya"
},{
text: "🤔",
callback_data: "instructions"
}]
]
}
})
.then(log('Sent reason of unrecognized request to chat '+chatId+'.'))
.catch(e=>log('Failed to send reason of unrecognized request to chat '+chatId+': ', e))
} else {
log(`Ignored message from non-admin user ${ctx.from.id} in chat ${ctx.chat.id}.`)
}
})
.catch(e => log('Error while checking admin: ', e))
}
// Sends instructions message with buttons to get random aya or contact support
function instructions(chatId){
var msg =
`يمكنك طلب آية محددة بإرسال اسم أو رقم السورة ورقم الآية.
مثل: البقرة ٢٥٥
أو مثل: ٢ ٢٥٥
أو آية الكرسي
وأيضا اسم أو رقم السورة فقط
مثل : البقرة
أو مثل : ٢
You can request a specific Aya by sending the numbers of Aya and Sura.
Example: 2 255
Or Sura number only: 2`
bot.telegram.sendMessage(chatId, msg)
.then(log('Sent instructions message to chat '+chatId+'.'))
.catch(e=>log('Failed to send instructions message to chat '+chatId+': ', e))
}
// Converting input arabic number into english one to easily find numbers in sent messages
function numArabicToEnglish(string) {
return string.replace(/[\u0660-\u0669]/g, function (c) {
return c.charCodeAt(0) - 0x0660
})
}
const rasmifize = require('rasmify.js')
const normalizedSurasArNames = enQuran.map(s => rasmifize(s.name.substr(8)))
log("surasArNames count: " + normalizedSurasArNames.length)
const ArMagicRegex = new RegExp(`[${rasmifize('المهوسصق')}]`) // All Arabic names of Suras include at least one character of these
// Responds to text messages to send the requested Aya or error message if unrecognized
function handleText(ctx){
var normalizedTxt = rasmifize(numArabicToEnglish(ctx.message.text)),
foundNums = normalizedTxt.match(/\d+/g) || [],
chatId = ctx.chat.id,
ayaId = -2 // Positive for valid ayaId, 0 for valid sura but invalid aya, -1 for invalid sura, -2 or any other negative for initialization.
foundArSuraNum = 0
log('Message from chat ' + chatId+ ': ' + ctx.message.text)
log('Normalized message from chat: ' + normalizedTxt)
if(ArMagicRegex.test(normalizedTxt)) {
if(normalizedTxt.includes(rasmifize("الكرسي"))){
ayaId = 262
} else {
for (let index = 0; index < normalizedSurasArNames.length; index++) {
let regex = new RegExp(
`(^${normalizedSurasArNames[index]}$)|(^${
normalizedSurasArNames[index]}([-: 0-9]+)(.*))|((.*)([-: ]+)${
normalizedSurasArNames[index]}([-: 0-9]+)(.*))|((.*)([-: ]+)${normalizedSurasArNames[index]}$)`
)
if(regex.test(normalizedTxt)){
foundArSuraNum = 1 + index
log("Found Arabic Sura number: " + foundArSuraNum)
break
}
}
if (foundArSuraNum){
ayaId = suraAya2ayaId({sura: foundArSuraNum, aya: foundNums.length ? foundNums[0] : 1})
}
}
}
if (foundNums.length && !foundArSuraNum){ // If no Sura Arabic names, look for numbers only
ayaId = suraAya2ayaId({sura: foundNums[0], aya: foundNums.length >= 2 ? foundNums[1] : 1})
}
if (ayaId > 0) {
sendAya(chatId, ayaId, "", ctx.from.language_code, 'request', ctx.startPayload ? ctx.startPayload.includes("r") : false)
} else if (ayaId < 0) {
// if no Arabic sura name and first number is not valid sura number, send UNRECOGNIZED for reason 2
unrecognized(ctx, 1)
} else if (ayaId == 0){
// if aya number is not valid aya in the requested Sura send UNRECOGNIZED for reason 2
unrecognized(ctx, 2)
}
}
function surpriseAya(ctx){
sendAya(ctx.chat.id, "", "", ctx.from.language_code, 'surprise')
}
function adminChecker(ctx){
return new Promise ((resolve, reject) => {
if (ctx.chat.type == "private"){
resolve(true)
} else {
bot.telegram.getChatMember(ctx.chat.id, ctx.from.id)
.then(r => {
if(r.status == "creator" || r.status == "administrator"){
resolve(true)
} else {
resolve(false)
}
})
.catch(e => {
log('isAdmin check error: ', e)
reject(e)
})
}
})
}
// set the bot menu
bot.telegram.setMyCommands([
{'command':'surpriseme', 'description': '🎁 Surprise Me فاجئني'},
{'command':'khatma', 'description': '💪 Group Khatma ختمة مجموعة'},
{'command':'help', 'description': '🤔 Instructions إرشادات'},
{'command':'support', 'description': '🤗 Support دعم'},
{'command':'reciters', 'description': '🗣️ Set Reciter اختيار القارئ'},
{'command':'channel', 'description': '📢 Daily Aya Channel قناة دايلي آية'}
])
// Invoking start command
bot.start(ctx => {
adminChecker(ctx)
.then(isAdmin =>{
if(isAdmin){
if(ctx.startPayload.length) handleText(ctx)
else start(ctx.chat.id)
} else {
log(`Ignored command from non-admin user ${ctx.from.id} in chat ${ctx.chat.id}.`)
}
})
.catch(e =>{
log('Error while checking admin: ', e)
})
})
// Invoking help command
bot.help(ctx => {
adminChecker(ctx)
.then(isAdmin =>{