-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbot.js
More file actions
397 lines (326 loc) · 10.5 KB
/
bot.js
File metadata and controls
397 lines (326 loc) · 10.5 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
const { Telegraf } = require('telegraf')
const session = require('telegraf/session')
const Stage = require('telegraf/stage')
const Scene = require('telegraf/scenes/base')
const stage = new Stage()
const QRcode = require('qrcode')
const fs = require('fs')
require('dotenv').config()
const { getWalletInfo, getBalance, createInvoice, decodeInvoice, decodeQRFromUrl, payInvoice, checkInvoice } = require('./lnbits_api')
const token = process.env.BOT_TOKEN || ""
if (!token) {
console.log("missing bot token")
return
}
console.log("bot token:", token)
const bot = new Telegraf(token)
// scan QR
const scanQR = new Scene('scanQR')
stage.register(scanQR)
// generate QR Code
const generate = new Scene('generate')
stage.register(generate)
// decode an invoice
const decode = new Scene('decode')
stage.register(decode)
// create an invoice (include make QR code)
const create_invoice = new Scene('createinvoice')
stage.register(create_invoice)
// pay an invoice (include scanning QR image)
const pay_invoice = new Scene('payinvoice')
stage.register(pay_invoice)
// check invoice
const check_invoice = new Scene('checkinv')
stage.register(check_invoice)
/////////////////
bot.use(session())
bot.use(stage.middleware())
bot.start((ctx) => {
ctx.reply('Welcome')
starter(ctx)
})
bot.hears('Get Balance', async ctx => {
const msg = await getWalletInfo()
return ctx.replyWithMarkdown(msg)
})
bot.hears('👓 Decode Invoice', async ctx => {
ctx.scene.enter('decode')
})
bot.hears('🖊 Generate QR Code', (ctx) => {
ctx.scene.enter('generate')
})
bot.hears('🔍 Scan QR Code', (ctx) => {
ctx.scene.enter('scanQR')
})
bot.hears('⚡️ Create Invoice', async ctx => {
ctx.scene.enter('createinvoice')
})
bot.hears('/invoice', async ctx => {
ctx.scene.enter('createinvoice')
})
bot.hears('✅ Check an Invoice', async ctx => {
ctx.scene.enter('checkinv')
})
bot.hears('📨 Pay Invoice', async ctx => {
ctx.scene.enter('payinvoice')
})
///////////////
pay_invoice.enter((ctx) => {
ctx.reply("Upload a QR or paste an invoice here ",
{ reply_markup: { keyboard: [['⬅️ Back']], resize_keyboard: true }})
})
pay_invoice.leave((ctx) => starter(ctx))
// this 'back' must preceed 'text' method or it will not execute
pay_invoice.hears('⬅️ Back', (ctx) => {
ctx.scene.leave('payinvoice')
starter(ctx)
})
function isString(e) {
return typeof e === "string" || e instanceof String;
}
pay_invoice.on('text', async(ctx) => {
try {
ctx.replyWithChatAction('typing')
let invoice = ctx.message.text
// check payment hash before trying to pay invoice, add your extra checks here.
const msg = await decodeInvoice(invoice)
if (isString(msg)) {
return ctx.reply(msg)
}
let hash = msg.payment_hash
await ctx.reply("Payment Hash: " + hash)
let amt_paid = msg.amount_msat/1000
let payresult = await payInvoice(invoice)
console.log(payresult)
if (payresult === undefined) {
let reply = "⚡️ Payment made. " + amt_paid + " sats \n"
let currBal = await getBalance();
reply += "Current Balance: " + currBal + "\n"
console.log(reply)
return ctx.reply(reply)
} else {
await ctx.reply("Payment response: " + payresult)
}
} catch (error) {
console.log(error)
await ctx.reply("Error fetching data. Try again?")
await ctx.reply('You can send another amount or tap "⬅️ Back"')
}
})
pay_invoice.on('photo', async (ctx) => {
ctx.replyWithChatAction('typing')
try {
const imageData = await bot.telegram.getFile(ctx.message.photo[ctx.message.photo.length - 1].file_id)
const path = `https://api.telegram.org/file/bot${token}/${imageData.file_path}`
console.log("uploaded image for invoice payment: ", path)
//await ctx.reply("uploaded image path: " + path)
let invoice = await decodeQRFromUrl(path)
console.log("result: " , invoice)
if (invoice === "error"){
return await ctx.reply('No QR Code data found on this picture.')
} else {
await ctx.reply('Scanned data:')
await ctx.reply(invoice)
}
// check payment hash before trying to pay invoice, add your extra checks here.
const msg = await decodeInvoice(invoice)
if (isString(msg)) {
return ctx.reply(msg)
}
let hash = msg.payment_hash
await ctx.reply("Payment Hash: " + hash)
let amt_paid = msg.amount_msat/1000
let payresult = await payInvoice(invoice)
console.log(payresult)
if (payresult === undefined) {
let reply = "⚡️ Payment made. " + amt_paid + " sats \n"
let currBal = await getBalance();
reply += "Current Balance: " + currBal + "\n"
console.log(reply)
return ctx.reply(reply)
} else {
await ctx.reply("Payment response: " + payresult)
}
} catch (error) {
console.log(error)
await ctx.reply("Error fetching data. Try again?")
await ctx.reply('You can send another amount or tap "⬅️ Back"')
}
})
///////////////
check_invoice.enter((ctx) => {
ctx.reply("Enter a payment hash to check: ",
{ reply_markup: { keyboard: [['⬅️ Back']], resize_keyboard: true }})
})
check_invoice.leave((ctx) => starter(ctx))
// this 'back' must preceed 'text' method or it will not execute
check_invoice.hears('⬅️ Back', (ctx) => {
ctx.scene.leave('checkinv')
starter(ctx)
})
check_invoice.on('text', async(ctx) => {
try {
let hash = ctx.message.text
let response = await checkInvoice(hash)
await ctx.reply(response)
await ctx.reply('You can send another amount or tap "⬅️ Back"')
} catch (error) {
console.log(error)
await ctx.reply("Error fetching data. Try again?")
await ctx.reply('You can send another amount or tap "⬅️ Back"')
}
})
///////////////
create_invoice.enter((ctx) => {
ctx.reply("How many sats for your invoice? ",
{ reply_markup: { keyboard: [['⬅️ Back']], resize_keyboard: true }})
})
create_invoice.leave((ctx) => starter(ctx))
// this 'back' must preceed 'text' method or it will not execute
create_invoice.hears('⬅️ Back', (ctx) => {
ctx.scene.leave('createinvoice')
starter(ctx)
})
function isNumeric(val) {
return /^-?\d+$/.test(val);
}
create_invoice.on('text', async(ctx) => {
try {
let amt = ctx.message.text
console.log(amt)
if (isNumeric(amt) === false) {
return ctx.reply("Please send a valid amount greater than 10")
}
if (ctx.message.text.length > 8) {
return ctx.reply('Too big of an invoice, try a smaller amount?')
}
ctx.replyWithChatAction('typing')
const bolt11 = await createInvoice(amt)
//console.log("generated bolt11 :", bolt11)
if (bolt11 === "Error") {
return ctx.reply("Error fetching data. Try again?")
}
const path = '/tmp/invoice.png'
await QRcode.toFile(path, bolt11, {
errorCorrectionLevel: 'H',
margin: 5,
color: {
dark:"#010599FF",
light:"#FFFFFFFF"
}
})
await ctx.replyWithPhoto({ source: path}, { caption: bolt11 })
await ctx.reply('You can send another amount or tap "⬅️ Back"')
fs.unlink(path, function (err) {
if (err) throw err;
console.log("\nDeleted file: ", path);
});
} catch(error) {
console.log(error)
await ctx.reply("Error generating Invoice.")
await ctx.reply('You can send another amount or tap "⬅️ Back"')
}
})
////////////
decode.enter((ctx) => {
ctx.reply("Send me a Invoice to Decode! ",
{ reply_markup: { keyboard: [['⬅️ Back']], resize_keyboard: true }})
})
decode.leave((ctx) => starter(ctx))
// this 'back' must preceed 'text' method or it will not execute
decode.hears('⬅️ Back', (ctx) => {
ctx.scene.leave('decode')
starter(ctx)
})
decode.on('text', async(ctx) => {
if (ctx.message.text.length > 900) {
return ctx.reply('Text too long, please send shorter text')
}
ctx.replyWithChatAction('typing')
let invoice = ctx.message.text
const msg = await decodeInvoice(invoice)
return ctx.reply(msg)
})
///// Generate QR Code /////
generate.enter((ctx) => {
ctx.reply(
'I`m ready. Send me text!',
{ reply_markup: { keyboard: [['⬅️ Back']], resize_keyboard: true } }
)
})
generate.hears('⬅️ Back', (ctx) => {
starter(ctx)
ctx.scene.leave('generate')
})
generate.on('text', async (ctx) => {
if (ctx.message.text.length > 900) {
return ctx.reply('Your text is too long. Please send text that contains not more than 900 symbols.')
}
ctx.replyWithChatAction('upload_photo')
try {
const path = '/tmp/qr_image.png'
await QRcode.toFile(path, ctx.message.text, {
errorCorrectionLevel: 'H'
})
await ctx.replyWithPhoto({source: path })
await ctx.reply('You can send me more text or tap "⬅️ Back"')
fs.unlink(path, function (err) {
if (err) throw err;
console.log("\nDeleted file: ", path);
});
} catch (err) {
console.log(err)
await ctx.reply("Error trying to generate QRCode.")
await ctx.reply('You can send me more text or tap "⬅️ Back"')
}
})
///////// Scan QR Code //////////
scanQR.enter((ctx) => {
ctx.reply(
'I`m ready. Send a picture!',
{ reply_markup: { keyboard: [['⬅️ Back']], resize_keyboard: true } }
)
})
scanQR.on('photo', async (ctx) => {
ctx.replyWithChatAction('typing')
try {
const imageData = await bot.telegram.getFile(ctx.message.photo[ctx.message.photo.length - 1].file_id)
const path = `https://api.telegram.org/file/bot${token}/${imageData.file_path}`
const result = await decodeQRFromUrl(path)
console.log("result: " , result)
if (result === "error"){
await ctx.reply('No QR Code data found on this picture.')
} else {
await ctx.reply('Scanned data:')
await ctx.reply(result)
ctx.reply('You can send me other pictures or tap "⬅️ Back"')
}
} catch (err) {
ctx.reply('No QR Code data found on this picture.')
}
})
scanQR.hears('⬅️ Back', (ctx) => {
starter(ctx)
ctx.scene.leave('scanQR')
})
///////// starter /////////
function starter (ctx) {
ctx.reply(
'Hi! What do you want to do?',
{ reply_markup: { keyboard: [['Get Balance'],
['📨 Pay Invoice', '⚡️ Create Invoice'],
['👓 Decode Invoice', '✅ Check an Invoice'],
// ['🔍 Scan QR Code', '🖊 Generate QR Code']
],
resize_keyboard: true } }
)
}
bot.on('message', async (ctx) => {
ctx.scene.leave('decode')
ctx.scene.leave('generate')
ctx.scene.leave('createinvoice')
ctx.scene.leave('checkinv')
ctx.scene.leave('payinvoice')
starter(ctx)
})
bot.launch()