-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.mjs
More file actions
2105 lines (1399 loc) · 60.6 KB
/
app.mjs
File metadata and controls
2105 lines (1399 loc) · 60.6 KB
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
import Archethic, { Utils, Crypto } from "@archethicjs/sdk"
import fetch from "cross-fetch";
import { Telegraf, Markup, Scenes } from "telegraf";
import LocalSession from 'telegraf-session-local'
import QRCode from "qrcode";
import * as bip39 from "bip39"
import fs from "fs"
import {getRemainingTime, getCurrentTimeFormatted} from "./utils.mjs"
// custom modules
import db from "./lib/src/services/database.mjs"
import { UsersDao } from "./lib/src/services/users_dao.mjs"
// logger
import logger from "./lib/src/services/logger.mjs";
//import { WizardContextWizard } from "telegraf/typings/scenes/index.js";
//import { Stage, WizardScene } from "telegraf/typings/scenes/index.js";
// telegraf bot instance
const token = process.env.BOT_TOKEN
if (token === undefined) {
throw new Error('BOT_TOKEN must be provided!')
}
const bot = new Telegraf(token)
const contractPath = "./contract.exs"
// Archethic global variables
const archethicEndpoint = "https://testnet.archethic.net";
const originPrivateKey = Utils.originPrivateKey
const BATTLECHAIN_ADDRESS = "0000193bf60609d0ac7974e4f57cee4ca4caddc3488036292d9d179e7e44bd1582db"
const curveType = "ed25519";
const archethic = new Archethic(archethicEndpoint);
await archethic.connect();
// functionnals global variables
const WALLET_BUTTON_TEXT = "👛 Wallet";
const GENERATE_WALLET_BUTTON_TEXT = "👛 Generate Wallet";
const GENERATE_BATTLECHAIN_BUTTON_TEXT = "⚔️ Generate Battlechain"
const CALLBACK_DATA_SEND = "send"
const CALLBACK_DATA_RECEIVE = "receive"
const CALLBACK_DATA_BACKUP = "seed"
const CALLBACK_DATA_FEED = "feed"
const CALLBACK_DATA_HEAL = "heal"
const CALLBACK_DATA_REFRESH = "refresh"
const CALLBACK_DATA_RESURRECT = "resurrect"
const CALLBACK_DATA_SEND_CANCEL = "cancel"
const SEND_WIZARD_SCENE_ID = "SEND_WIZARD"
const KEYBOARD_BATTLECHAIN_BUTTON_TEXT = "⚔️ Battlechain"
const INLINE_KEYBOARD_OPEN = [
[{ text: "💸 Send", callback_data: CALLBACK_DATA_SEND }, { text: "📨 Receive", callback_data: CALLBACK_DATA_RECEIVE }],
[{ text: "🔑 Backup recovery phrase", callback_data: CALLBACK_DATA_BACKUP }]
]
const INLINE_KEYBOARD_PLAY = [
[{ text: "🥐 Feed", callback_data: CALLBACK_DATA_FEED }, { text: "💗 Heal", callback_data: CALLBACK_DATA_HEAL }],
[{ text: "💤 Sleep (refresh actions)", callback_data: CALLBACK_DATA_REFRESH }],
[{ text: "⚕️ Resurrect", callback_data: CALLBACK_DATA_RESURRECT }]
]
const Actions = Object.freeze({
PLAY: 'play',
FEED: 'feed',
HEAL: 'heal',
SLEEP: 'sleep',
RESURRECT: 'resurrect'
});
const archmon_inline_text_idle =
`<pre>
/\\_/\\
(o^.^o)
/: :\\
( : : )
/_| |_\\
</pre>`
const archmon_inline_text_feed =
`<pre>
/\\_/\\
( ^_^ )
/: :\\ ♥
( : : )
/_| |_\\
</pre>`
const archmon_inline_text_heal =
`<pre>
/\\_/\\
( >.< )
/: :\\ ✚
( : : )
/_| |_\\
</pre>`
const archmon_inline_text_sleep =
`<pre>
/\\_/\\ Z
( -.- ) Z
/: :\\ Z
( : : )
/_| |_\\
</pre>`
const archmon_inline_text_ko =
`<pre>
/\\_/\\
( x.x )
/: :\\
( : : )
/_| |_\\
</pre>`
function generatePemText(seed, publicAddress) {
const { privateKey } = Crypto.deriveKeyPair(seed, 0);
var pemText = "-----BEGIN PRIVATE KEY for " + publicAddress + "-----" + "\n";
pemText += Buffer.from(privateKey).toString('base64').replace(/.{64}/g, '$&\n') + "\n";
pemText += "-----END PRIVATE KEY for " + publicAddress + "-----";
return Buffer.from(pemText);
}
function getTimeText(){
const remainingTime = getRemainingTime()
var timeText = `⏳ : Next <b>Day</b> in : ${remainingTime.nextDay}`
timeText += `\n⏳ : Next <b>Round</b> in ${remainingTime.nextRound}`
timeText += `\n⏳ : Next <b>Turn</b> in ${remainingTime.nextTurn}`
return timeText
}
function seedStringToUint8Array(seed) {
var seedUint8Array = new Uint8Array(seed.split(",").map(i => parseInt(i)));
return seedUint8Array;
}
// Function to convert Uint8Array seed to mnemonic phrase
function uint8ArrayToMnemonic(uint8ArraySeed) {
// Convert Uint8Array to Buffer
const seedBuffer = Buffer.from(uint8ArraySeed);
// Convert Buffer to mnemonic phrase
const mnemonic = bip39.entropyToMnemonic(seedBuffer.toString('hex'));
return mnemonic.split(' ');
}
// base text for the open inlineKeyboard
async function getBaseTextOpenKB(user) {
var seedUint8Array = seedStringToUint8Array(user.seed)
var text = "💰 Wallet balance : ";
try {
var index = await archethic.transaction.getTransactionIndex(user.wallet)
var lastAddress = Crypto.deriveAddress(seedUint8Array, index)
const balance = await archethic.network.getBalance(lastAddress)
text += balance.uco / 10 ** 8 + " UCO"
} catch (error) {
text += "Unavailable"
logger.error(error);
}
return text
}
async function getBaseTextPlayKB(user, actionCode) {
var seedUint8Array = seedStringToUint8Array(user.seed)
var text = " "
try {
const playerInfo = await archethic.network.callFunction(BATTLECHAIN_ADDRESS, "get_player_info", [user.wallet])
if(playerInfo == null){
text = "Unavailable"
}else{
switch(actionCode){
case Actions.PLAY:
if(playerInfo.archmon.is_ko){
text += archmon_inline_text_ko
}else{
text += archmon_inline_text_idle
}
break;
case Actions.FEED:
text += archmon_inline_text_feed
break;
case Actions.HEAL:
text += archmon_inline_text_heal
break;
case Actions.SLEEP:
text += archmon_inline_text_sleep
break;
default:
text += archmon_inline_text_idle
}
text += `\n⚔️ Power : ${playerInfo.archmon.power} ❤️ Health : ${playerInfo.archmon.health}\n📖 XP : ${playerInfo.archmon.xp} 🏆 Level : ${playerInfo.archmon.level}`
text += `\n🎬 actions : ${playerInfo.action_points}`;
}
} catch (error) {
text = "Unavailable"
logger.error(error);
}
return text
}
const COOLDOWN_PERIOD = 5000; // 5000 ms = 5 seconds
const activeUsers = new Map();
function rateLimiter(ctx, next) {
const userId = ctx.from.id;
const now = Date.now();
// List of commands, hears patterns, and actions to apply rate limiting
const rateLimitedCommands = ['/tip','/attack'];
const rateLimitedHears = ['🔓 Open', '▶️ Play'];
const rateLimitedActions = [CALLBACK_DATA_FEED,CALLBACK_DATA_HEAL,CALLBACK_DATA_REFRESH,CALLBACK_DATA_RESURRECT];
// Check the type of update and apply rate limiting conditionally
const text = ctx.message?.text;
const callbackData = ctx.callbackQuery?.data;
const isRateLimitedCommand = text && rateLimitedCommands.includes(text);
const isRateLimitedHears = text && rateLimitedHears.some(pattern => text.includes(pattern));
const isRateLimitedAction = callbackData && rateLimitedActions.includes(callbackData);
if (isRateLimitedCommand || isRateLimitedHears || isRateLimitedAction) {
if (activeUsers.has(userId)) {
const lastRequestTime = activeUsers.get(userId);
const elapsedTime = now - lastRequestTime;
const waitTime = Math.ceil((COOLDOWN_PERIOD - elapsedTime) / 1000);
if (elapsedTime < COOLDOWN_PERIOD) {
return ctx.reply(`Please wait ${waitTime} seconds before making another request.`);
}
}
// Update the timestamp for the user
activeUsers.set(userId, now);
return next().finally(() => {
setTimeout(() => {
activeUsers.delete(userId);
}, COOLDOWN_PERIOD);
});
} else {
return next();
}
}
bot.use(rateLimiter);
bot.command('quit', (ctx) => {
// Explicit usage
ctx.telegram.leaveChat(ctx.message.chat.id)
.catch(error => logger.error(error))
// Using context shortcut
// ctx.leaveChat()
})
// start - Let's begin your transactionchain journey !
bot.command('start', ctx => {
if (ctx.message.chat.type !== "private" && !ctx.message.text.includes(ctx.botInfo.username)) {
return;
}
if (ctx.message.chat.type !== "private" && ctx.message.text.includes(ctx.botInfo.username)) {
// return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: We should take a private room to do this.\n Open a private chat with @${ctx.botInfo.username} to start interacting with him.`)
return ctx.reply(`🤖: We should take a private room to do this.\n Open a private chat with @${ctx.botInfo.username} to start interacting with me.`, {
reply_to_message_id: ctx.message.message_id
})
.catch(error => logger.error(error));
}
const userId = ctx.message.from.id
const username = ctx.message.from.username
db.read()
if (!db.data.users.some(user => user.id === userId)) {
db.data.users.push({ id: userId, name: username })
db.write()
} else {
console.log("Welcome back:" + userId)
}
ctx.telegram.sendMessage(ctx.message.chat.id, "Home", Markup.keyboard([["👛 Wallet"], [KEYBOARD_BATTLECHAIN_BUTTON_TEXT], ["🦮 Help", "📖 About"]])
).catch(error => logger.error(error))
})
bot.hears("👛 Wallet", ctx => {
var userId = ctx.message.from.id
var user = UsersDao.getById(userId)
if (user === undefined) {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: You are not registered with me 🛑. Use /start command to begin your journey with me.`)
.catch(error => logger.error(error))
}
if (!user.hasOwnProperty('wallet')) {
return ctx.telegram.sendMessage(ctx.message.chat.id, "Wallet",
Markup.keyboard([[GENERATE_WALLET_BUTTON_TEXT], ["Back"]]))
.catch(error => logger.error(error))
}
// var walletTextToDraw = user.wallet.substring(0,4) + "..." + user.wallet.substring(user.wallet.length-4,user.wallet.length)
var keyboardObject = [
//["👛 Wallet : " + walletTextToDraw],
["🔓 Open"],
["🏠 Back"]
]
return ctx.telegram.sendMessage(ctx.message.chat.id, "Wallet find.",
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
})
bot.hears(GENERATE_WALLET_BUTTON_TEXT, ctx => {
var userId = ctx.message.from.id
var chatId = ctx.message.chat.id;
var seed = Crypto.randomSecretKey();
var index = 0;
var publicAddress = Crypto.deriveAddress(seed, index)
var user = UsersDao.getById(userId);
if (user === undefined) {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: Unknown life form : ${ctx.message.from.first_name}. 🛑`)
.catch(error => logger.error(error));
}
user.wallet = Utils.uint8ArrayToHex(publicAddress);
user.seed = seed.toString()
db.write()
//var pemTextBuffer = generatePemText(seed,publicAddress);
//ctx.replyWithDocument({source: pemTextBuffer , filename: publicAddress + ".pem" })
//.catch(error => logger.error(error))
// var walletTextToDraw = user.wallet.substring(0,4) + "..." + user.wallet.substring(user.wallet.length-4,user.wallet.length)
var keyboardObject = [
// ["👛 Wallet : " + walletTextToDraw],
["🔓 Open"],
["🏠 Back"]
]
ctx.telegram.sendMessage(ctx.message.chat.id, "Wallet generated :")
.catch(error => logger.error(error))
ctx.telegram.sendMessage(ctx.message.chat.id, user.wallet,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
})
bot.hears(KEYBOARD_BATTLECHAIN_BUTTON_TEXT, async ctx => {
var userId = ctx.message.from.id
var user = UsersDao.getById(userId)
var keyboardObject = [
["▶️ Play"],
["📋 Rules"],
["🏠 Back"]
]
if (user === undefined) {
try {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: You are not registered with me 🛑. Use /start command to begin your journey with me.`);
} catch (error) {
return logger.error(error);
}
}
if (user.wallet === undefined) {
try {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: You need to generate a wallet first.`);
} catch (error) {
return logger.error(error);
}
}
if (!user.hasOwnProperty('battlechain')) {
const index = await archethic.transaction.getTransactionIndex(user.wallet)
const seedUint8Array = seedStringToUint8Array(user.seed)
var isConfirmed = false
const tx = archethic.transaction.new()
.setType("transfer")
.addRecipient(BATTLECHAIN_ADDRESS, "add_player", [])
.build(seedUint8Array, index)
.originSign(originPrivateKey)
.on("confirmation", (nbConf, maxConf) => {
console.log(nbConf, maxConf)
if (nbConf == maxConf && !isConfirmed) {
isConfirmed = true
user.battlechain = true;
db.write()
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: Adding player ... Press ▶️ Play to check status.`,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
}
})
.on("error", (context, reason) => {
console.log("Context:", context)
console.log("Reason:", reason)
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: INVALID_TRANSACTION : ${reason}. 🔗`)
.catch(error => logger.error(error))
})
console.log(tx.toJSON())
try {
tx.send()
} catch (error) {
logger.error(error)
}
} else {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: Player ready !`,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
}
})
bot.hears(GENERATE_WALLET_BUTTON_TEXT, ctx => {
var userId = ctx.message.from.id
var chatId = ctx.message.chat.id;
var seed = Crypto.randomSecretKey();
var index = 0;
var publicAddress = Crypto.deriveAddress(seed, index)
var user = UsersDao.getById(userId);
if (user === undefined) {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: Unknown life form : ${ctx.message.from.first_name}. 🛑`)
.catch(error => logger.error(error));
}
user.wallet = Utils.uint8ArrayToHex(publicAddress);
user.seed = seed.toString()
db.write()
//var pemTextBuffer = generatePemText(seed,publicAddress);
//ctx.replyWithDocument({source: pemTextBuffer , filename: publicAddress + ".pem" })
//.catch(error => logger.error(error))
// var walletTextToDraw = user.wallet.substring(0,4) + "..." + user.wallet.substring(user.wallet.length-4,user.wallet.length)
var keyboardObject = [
// ["👛 Wallet : " + walletTextToDraw],
["🔓 Open"],
["🏠 Back"]
]
ctx.telegram.sendMessage(ctx.message.chat.id, "Wallet generated :")
.catch(error => logger.error(error))
ctx.telegram.sendMessage(ctx.message.chat.id, user.wallet,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
})
bot.hears(/mode (\w+)/, async ctx => {
var userId = ctx.message.from.id
var user = UsersDao.getById(userId)
const modeName = ctx.match[1]
const index = await archethic.transaction.getTransactionIndex(user.wallet)
const seedUint8Array = seedStringToUint8Array(user.seed)
var isConfirmed = false
const tx = archethic.transaction.new()
.setType("transfer")
.addRecipient(BATTLECHAIN_ADDRESS, "change_mode", [modeName])
.build(seedUint8Array, index)
.originSign(originPrivateKey)
.on("confirmation", (nbConf, maxConf) => {
console.log(nbConf, maxConf)
if (nbConf == maxConf && !isConfirmed) {
isConfirmed = true
user.battlechain = true;
db.write()
ctx.reply(`Mode changed to: ${modeName}`)
.catch(error => logger.error(error))
}
})
.on("error", (context, reason) => {
console.log("Context:", context)
console.log("Reason:", reason)
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: INVALID_TRANSACTION : ${reason}. 🔗`)
.catch(error => logger.error(error))
})
console.log(tx.toJSON())
try {
tx.send()
} catch (error) {
logger.error(error)
}
})
bot.hears("deploy", async ctx => {
var userId = ctx.message.from.id
var user = UsersDao.getById(userId)
var keyboardObject = [
["▶️ Play"],
["🏠 Back"]
]
if (user === undefined) {
try {
return await ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: You are not registered with me 🛑. Use /start command to begin your journey with me.`);
} catch (error) {
return logger.error(error);
}
}
if (user.wallet === undefined) {
try {
return await ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: You need to generate a wallet first.`);
} catch (error) {
return logger.error(error);
}
}
if (!user.hasOwnProperty('battlechain')) {
const index = await archethic.transaction.getTransactionIndex(user.wallet)
const seedUint8Array = seedStringToUint8Array(user.seed)
const storageNoncePK = await archethic.network.getStorageNoncePublicKey()
const aesKey = Crypto.randomSecretKey()
const encryptedSecret = Crypto.aesEncrypt(seedUint8Array, aesKey)
const encryptedAesKey = Crypto.ecEncrypt(aesKey, storageNoncePK)
const authorizedPublicKeys = [{
publicKey: storageNoncePK,
encryptedSecretKey: encryptedAesKey
}]
const battlechainCode = fs.readFileSync(contractPath, "utf8")
var isConfirmed = false
const tx = archethic.transaction.new()
.setType("contract")
.setCode(battlechainCode)
.addOwnership(encryptedSecret, authorizedPublicKeys)
.build(seedUint8Array, index)
.originSign(originPrivateKey)
.on("confirmation", (nbConf, maxConf) => {
console.log(nbConf, maxConf)
if (nbConf == maxConf && !isConfirmed) {
isConfirmed = true
// ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: ${ctx.message.from.first_name} sent ${tipValue[0]} to ${ctx.message.reply_to_message.from.first_name} ! 💸`)
user.battlechain = true;
db.write()
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: Battlechain ready !`,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
}
})
.on("error", (context, reason) => {
console.log("Context:", context)
console.log("Reason:", reason)
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: INVALID_TRANSACTION : ${reason}. 🔗`,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
})
console.log(tx.toJSON())
try {
tx.send()
} catch (error) {
logger.error(error)
}
}
else {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: Battlechain ready !`,
Markup.keyboard(keyboardObject))
.catch(error => logger.error(error))
}
})
bot.hears("🔓 Open", async ctx => {
var userId = ctx.message.from.id
var user = UsersDao.getById(userId)
var textReply = await getBaseTextOpenKB(user);
try {
return await ctx.telegram.sendMessage(ctx.message.chat.id, textReply,
Markup.inlineKeyboard(INLINE_KEYBOARD_OPEN));
} catch (error) {
logger.error(error);
return await ctx.telegram.sendMessage(ctx.message.chat.id, "Management keyboard not accessible.");
}
})
bot.hears("▶️ Play", async ctx => {
var userId = ctx.message.from.id
var user = UsersDao.getById(userId)
var textInline = await getBaseTextPlayKB(user,Actions.PLAY);
if (textInline == "Unavailable"){
return ctx.telegram.sendMessage(ctx.message.chat.id, "Player info not available yet. Try again in a few minutes.")
.catch(error => logger.error(error))
}
const text = getTimeText() + "\n" + textInline
return ctx.telegram.sendMessage(ctx.message.chat.id, text,
{ parse_mode: "HTML", ...Markup.inlineKeyboard(INLINE_KEYBOARD_PLAY) })
.catch(error => logger.error(error))
})
const RULES_TEXT = `
<b>Welcome to the first ever Battlechain on Archethic.</b>
The Battlechain acts as an <b>autonomous and decentralized game server</b>.
The main feature is a <b>turn-based battle game</b> where you charge into battle with your <b>archmon</b> 🐱.
You start the game with an <b>archmon 🐱 level 1</b> with <b>10 actions</b>.
The game lifecycle is managed by 3 temporal variables:
• <b>Day</b>: Counts each day that has passed since the deployment of the Battlechain.
• <b>Round</b>: 2 rounds per day, one at noon and the second at midnight.
• <b>Turn</b>: 1 turn every 30 minutes.
You can play 1 action per turn ( <b>🥐 Feed</b>, <b>💗 Heal</b>, or <b>⚔️ Attack</b> ) .
You can 💤 <b>refresh</b> your actions pool once a day.
You can ⚕️ <b>resurrect</b> your archmon one time each round.
Begin to interact with your archmon 🐱 by pressing <b>▶️ Play</b>.
( The Battlechain may take a few minutes to add the player the first time on testnet.)
<b>Available actions:</b>
• <b>⚔️ Attack</b>: Your archmon 🐱 deal damage to his target equal to his power.
• <b>🥐 Feed</b>: Your archmon 🐱 gain 20xp.
• <b>💗 Heal</b>: Your archmon 🐱 gain health equal to his power.
• <b>💤 Sleep</b>: Restore your actions pool.
• <b>⚕️ Resurrect</b>: Bring your archmon 🐱 back to life.
Finally, you can <b>⚔️ Attack</b> other players in group chat by using the <b>/attack</b> command as follows:
<code>/attack @username</code>.
<b>( More features coming soon...)</b>
Enough talk, let's <b>▶️ Play</b>!
`
bot.hears("📋 Rules", ctx => {
ctx.telegram.sendMessage(ctx.message.chat.id, RULES_TEXT, { parse_mode: "HTML" })
.catch(error => logger.error(error))
})
bot.hears("🏠 Back", ctx => {
ctx.telegram.sendMessage(ctx.message.chat.id, "Home", Markup.keyboard([["👛 Wallet"], ["⚔️ Battlechain"], ["🦮 Help", "📖 About"]]))
.catch(error => logger.error(error))
})
const HELP_TEXT = `I'm here to help you set your archethic wallet.
Begin with the <b>/start</b> command to register with me.
Then generate your wallet with the [👛 Wallet] button from the Home keyboard.
Finally invoke the open inline keyboard by clicking on the [🔓 Open] button to interact with your wallet.
You can also tips others users in group chat by using the <b>/tip</b> command as following :
/tip <b>@username</b> <b>10</b>.`
bot.command("help", ctx => {
if (ctx.message.chat.type !== "private" && !ctx.message.text.includes(ctx.botInfo.username)) {
return;
}
if (ctx.message.chat.type !== "private" && ctx.message.text.includes(ctx.botInfo.username)) {
return ctx.telegram.sendMessage(ctx.message.chat.id, `🤖: We should take a private room to do this.\n Open a private chat with @${ctx.botInfo.username} to start interacting with me.`)
.catch(error => logger.error(error));
}
ctx.telegram.sendMessage(ctx.message.chat.id, HELP_TEXT, { parse_mode: "HTML" })
.catch(error => logger.error(error))
})
bot.hears("🦮 Help", ctx => {
ctx.telegram.sendMessage(ctx.message.chat.id, HELP_TEXT, { parse_mode: "HTML" })
.catch(error => logger.error(error))
})
bot.hears("📖 About", ctx => {
ctx.telegram.sendMessage(ctx.message.chat.id, `Telegram bot done with Telegraf and Archethic javascript libraries.
⚠️ Disclaimer ⚠️
This bot is for recreational purposes only. Use it with caution. The creator is not responsible for any loss or damage resulting from the use of this bot.
`
, { parse_mode: "HTML" })
.catch(error => logger.error(error))
})
// send action scene
const sendWizard = new Scenes.WizardScene(SEND_WIZARD_SCENE_ID,
async (ctx) => {
var userID = ctx.callbackQuery.from.id
var user = UsersDao.getById(userID)
ctx.callbackQuery.message.reply_markup
var baseTextReply = await getBaseTextOpenKB(user)
var replyMarkup = {
inline_keyboard: [
[{ text: "🔙 Back ( Cancel transfert )", callback_data: CALLBACK_DATA_SEND_CANCEL }]
]
}
var textReply = baseTextReply + "\n🤖: Which is the recipient public address ❔"
ctx.editMessageText(textReply, { reply_markup: replyMarkup })
.catch(error => {
logger.error(error)
// return ctx.scene.leave()
})
ctx.wizard.state.sendData = {
reply_markup: replyMarkup,
callback_message_id: ctx.update.callback_query.message.message_id,
base_text: baseTextReply,
text_reply: textReply,
last_error: 0,
current_error: 0,
last_error_count: 0
}
return ctx.wizard.next();
},
(ctx) => {
try {
//Keep track of the message id in session
ctx.wizard.state.sendData.message_id = ctx.message.message_id
var hasError = false;
var errorTextReply = ""
// address validation
if (!typeof (ctx.message.text) == "string") {
ctx.wizard.state.sendData.current_error = 1
errorTextReply = ctx.wizard.state.sendData.base_text + `\n🤖: This address is not a string ! ❌`
hasError = true;
}
if (!hasError && !Utils.isHex(ctx.message.text)) {
ctx.wizard.state.sendData.current_error = 2
errorTextReply = ctx.wizard.state.sendData.base_text + `\n🤖: This address is not in hexadecimal format ! ❌`
hasError = true;
}
if (!hasError && ctx.message.text.length != 68) {
ctx.wizard.state.sendData.current_error = 3
errorTextReply = ctx.wizard.state.sendData.base_text + `\n🤖: Invalid address ! ❌`
hasError = true;
}
// if an error was raised
if (hasError) {
if (ctx.wizard.state.sendData.current_error != ctx.wizard.state.sendData.last_error) {
ctx.wizard.state.sendData.last_error = ctx.wizard.state.sendData.current_error
ctx.wizard.state.sendData.last_error_count = 1
} else {
ctx.wizard.state.sendData.last_error_count++
errorTextReply += `\n🤖: (Warnings ${ctx.wizard.state.sendData.last_error_count}) ⚠️`
}
return ctx.telegram.editMessageText(ctx.chat.id, ctx.wizard.state.sendData.callback_message_id, undefined, errorTextReply, { reply_markup: ctx.wizard.state.sendData.reply_markup })
.catch(error => logger.error(error));
}
ctx.wizard.state.sendData.to = ctx.message.text
var textReply = ctx.wizard.state.sendData.text_reply + "\n <i>" + ctx.message.text + "</i>"
textReply += "\n🤖: UCO amount to send ❔"
ctx.wizard.state.sendData.text_reply = textReply
ctx.telegram.editMessageText(ctx.chat.id, ctx.wizard.state.sendData.callback_message_id, undefined, textReply, { reply_markup: ctx.wizard.state.sendData.reply_markup, parse_mode: "HTML" })
.then(r => {
// reset error state
ctx.wizard.state.sendData.last_error = 0
ctx.wizard.state.sendData.last_error_count = 0
return ctx.wizard.next();
})
.catch(error => {
logger.error(error)
let errorTextReply = ctx.wizard.state.sendData.base_text + `\n🤖: Unhandled error : send function not available.❌`
ctx.telegram.editMessageText(ctx.chat.id, ctx.wizard.state.sendData.callback_message_id, undefined, errorTextReply, { reply_markup: ctx.wizard.state.sendData.reply_markup })
.catch(error => logger.error(error))
return ctx.scene.leave();
})
} catch (error) {
logger.error(error)
let errorTextReply = ctx.wizard.state.sendData.base_text + `\n🤖: Unhandled error : send function not available.❌`
ctx.telegram.editMessageText(ctx.chat.id, ctx.wizard.state.sendData.callback_message_id, undefined, errorTextReply, { reply_markup: ctx.wizard.state.sendData.reply_markup })
.catch(error => logger.error(error))
return ctx.scene.leave();
} finally {
if (ctx.wizard.state.sendData.message_id != undefined) {
// message consumed
ctx.deleteMessage(ctx.wizard.state.sendData.message_id)
.catch(error => {
logger.error(error)
})
}
}
},
async (ctx) => {
try {
//Keep track of the message id in session
ctx.wizard.state.sendData.message_id = ctx.message.message_id