Skip to content

Commit 8ce6cb8

Browse files
committed
better error handling and logging
1 parent 0a7da33 commit 8ce6cb8

File tree

6 files changed

+156
-101
lines changed

6 files changed

+156
-101
lines changed

.env.example

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
AUTH_TOKEN=
22
LNBITS_HOST=https://lightning.bot
33
LNBITS_ADMIN_USER_ID=
4-
LNBITS_ADMIN_API_KEY=
4+
LNBITS_ADMIN_API_KEY=
5+
LOG_TO_FILE=false

Commands/Balance.js

+29-20
Original file line numberDiff line numberDiff line change
@@ -17,27 +17,36 @@ class Balance extends Command {
1717
async execute(Interaction) {
1818
await Interaction.defer({ephemeral: true});
1919
const um = new UserManager();
20-
const userWallet = await um.getUserWallet(Interaction.user.id);
20+
try {
21+
const userWallet = await um.getUserWallet(Interaction.user.id);
2122

22-
if (userWallet.adminkey) {
23-
const uw = new UserWallet(userWallet.adminkey);
24-
const userWalletDetails = await uw.getWalletDetails();
25-
26-
const walletUrl = `${process.env.LNBITS_HOST}/wallet?usr=${userWallet.user}`;
27-
28-
const sats = userWalletDetails.balance/1000;
29-
const btc = (sats/100000000).toFixed(8).replace(/\.?0+$/,``);
30-
31-
Interaction.editReply({
32-
content:`Balance: ${sats} Satoshis / ฿${btc} \nAccess wallet here: ${walletUrl}`,
33-
ephemeral: true,
34-
});
35-
}
36-
else {
37-
Interaction.editReply({
38-
content:`You do not currently have a wallet you can use /create`,
39-
ephemeral: true,
40-
});
23+
if (userWallet.adminkey) {
24+
const uw = new UserWallet(userWallet.adminkey);
25+
try {
26+
const userWalletDetails = await uw.getWalletDetails();
27+
28+
const walletUrl = `${process.env.LNBITS_HOST}/wallet?usr=${userWallet.user}`;
29+
30+
const sats = userWalletDetails.balance/1000;
31+
const btc = (sats/100000000).toFixed(8).replace(/\.?0+$/,``);
32+
33+
Interaction.editReply({
34+
content:`Balance: ${sats} Satoshis / ฿${btc} \nAccess wallet here: ${walletUrl}`,
35+
ephemeral: true,
36+
});
37+
} catch (err) {
38+
console.log(err);
39+
}
40+
41+
}
42+
else {
43+
Interaction.editReply({
44+
content:`You do not currently have a wallet you can use /create`,
45+
ephemeral: true,
46+
});
47+
}
48+
} catch (err) {
49+
console.log(err);
4150
}
4251
}
4352
}

Commands/Create.js

+17-7
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,24 @@ class Create extends Command {
1414
}
1515

1616
async execute(Interaction) {
17-
const member = await Interaction.guild.members.fetch(Interaction.user.id);
18-
const um = new UserManager();
19-
const userWallet = await um.getOrCreateWallet(member.user.username, Interaction.user.id);
17+
let member;
18+
try {
19+
member = await Interaction.guild.members.fetch(Interaction.user.id);
20+
} catch (err) {
21+
console.log(err);
22+
}
23+
24+
try {
25+
const um = new UserManager();
26+
const userWallet = await um.getOrCreateWallet(member.user.username, Interaction.user.id);
2027

21-
Interaction.reply({
22-
content: `You can access the wallet at ${process.env.LNBITS_HOST}/wallet?usr=${userWallet.user}`,
23-
ephemeral: true
24-
});
28+
Interaction.reply({
29+
content: `You can access the wallet at ${process.env.LNBITS_HOST}/wallet?usr=${userWallet.user}`,
30+
ephemeral: true
31+
});
32+
} catch(err) {
33+
console.log(err);
34+
}
2535
}
2636
}
2737

Commands/PayMe.js

+43-32
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,7 @@ const QRCode = require(`qrcode`);
66

77
/*
88
This command will create an invoice for a user.
9-
Provides an embed for
10-
11-
TODO:
12-
- Currently you can specify an optional user to create an invoice under
9+
Provides an embed for QR scanning
1310
*/
1411

1512
class PayMe extends Command {
@@ -27,42 +24,56 @@ class PayMe extends Command {
2724
type: `STRING`,
2825
description: `The description of the invoice`,
2926
required: true,
30-
},{
31-
name: `user`,
32-
type: `USER`,
33-
description: `The user to show wallet balance of`,
34-
required: false,
3527
}];
3628
}
3729

3830
async execute(Interaction) {
39-
await Interaction.defer();
31+
4032
const amount = Interaction.options.get(`amount`);
4133
const description = Interaction.options.get(`description`);
42-
const member = await Interaction.guild.members.fetch(Interaction.user.id);
43-
44-
const um = new UserManager();
45-
const userWallet = await um.getUserWallet(member.user.id);
34+
let member;
35+
36+
if (amount.value <= 0) {
37+
Interaction.reply({
38+
content: `Negative balances are not permitted`,
39+
ephemeral: true
40+
});
41+
return
42+
}
4643

47-
const uw = new UserWallet(userWallet.adminkey);
48-
const invoiceDetails = await uw.createInvote(amount.value, description.value);
49-
50-
const qrData = await QRCode.toDataURL(invoiceDetails.payment_request);
51-
const buffer = new Buffer.from(qrData.split(`,`)[1], `base64`);
52-
const file = new Discord.MessageAttachment(buffer, `image.png`);
53-
const embed = new Discord.MessageEmbed().setImage(`attachment://image.png`).addField(`Payment Request`, `${invoiceDetails.payment_request}`, true);
44+
await Interaction.defer();
45+
try {
46+
member = await Interaction.guild.members.fetch(Interaction.user.id);
47+
} catch(err) {
48+
console.log(err);
49+
}
5450

55-
const row = new Discord.MessageActionRow()
56-
.addComponents([
57-
new Discord.MessageButton({
58-
custom_id: `pay`,
59-
label: `Pay Now!`,
60-
emoji: { name: `💸` },
61-
style: `SECONDARY`
62-
})
63-
]);
64-
65-
Interaction.editReply({ embeds: [embed], files: [file], components: [row]});
51+
try {
52+
const um = new UserManager();
53+
const userWallet = await um.getUserWallet(member.user.id);
54+
55+
const uw = new UserWallet(userWallet.adminkey);
56+
const invoiceDetails = await uw.createInvote(amount.value, description.value);
57+
58+
const qrData = await QRCode.toDataURL(invoiceDetails.payment_request);
59+
const buffer = new Buffer.from(qrData.split(`,`)[1], `base64`);
60+
const file = new Discord.MessageAttachment(buffer, `image.png`);
61+
const embed = new Discord.MessageEmbed().setImage(`attachment://image.png`).addField(`Payment Request`, `${invoiceDetails.payment_request}`, true);
62+
63+
// const row = new Discord.MessageActionRow()
64+
// .addComponents([
65+
// new Discord.MessageButton({
66+
// custom_id: `pay`,
67+
// label: `Pay Now!`,
68+
// emoji: { name: `💸` },
69+
// style: `SECONDARY`
70+
// })
71+
// ]);
72+
// Interaction.editReply({ embeds: [embed], files: [file], components: [row]});
73+
Interaction.editReply({ embeds: [embed], files: [file]});
74+
} catch(err) {
75+
console.log(err);
76+
}
6677
}
6778
}
6879

Commands/Tip.js

+35-14
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,18 @@ class Tip extends Command {
2626
}
2727

2828
async execute(Interaction) {
29-
await Interaction.defer();
3029
const sender = Interaction;
3130
const receiver = Interaction.options.get(`user`);
3231
const amount = Interaction.options.get(`amount`);
33-
const message = Interaction.options.get(`message`) ? Interaction.options.get(`message`) : `null`;
32+
const message = Interaction.options.get(`message`) ? Interaction.options.get(`message`) : {value: `null`};
33+
34+
if (amount.value <= 0) {
35+
Interaction.reply({
36+
content: `Negative balances are not permitted`,
37+
ephemeral: true
38+
});
39+
return
40+
}
3441

3542
const sats = amount.value;
3643
const btc = (sats/100000000).toFixed(8).replace(/\.?0+$/,``);
@@ -44,35 +51,49 @@ class Tip extends Command {
4451
const receiverWalletData = await _.getOrCreateWallet(receiverData.user.username, receiver.user.id);
4552

4653
if (!senderWalletData.id) {
47-
Interaction.editReply({
54+
Interaction.reply({
4855
content:`You do not currently have a wallet you can use /create`,
56+
ephemeral: true
4957
});
50-
} else if ((senderWalletData.balance/1000) - sats < 0) {
51-
Interaction.editReply({
58+
return
59+
}
60+
const senderWallet = new UserWallet(senderWalletData.adminkey);
61+
const senderWalletDetails = await senderWallet.getWalletDetails()
62+
const receiverWallet = new UserWallet(receiverWalletData.adminkey);
63+
64+
if ((senderWalletDetails.balance/1000) - sats < 0) {
65+
Interaction.reply({
5266
content:`You do not have the balance to do this.`,
67+
ephemeral: true
5368
});
54-
} else if (receiverWalletData.id) {
55-
56-
const senderWallet = new UserWallet(senderWalletData.adminkey);
57-
const receiverWallet = new UserWallet(receiverWalletData.adminkey);
58-
59-
const invoiceDetails = await receiverWallet.createInvote(amount.value, message);
69+
return
70+
}
71+
72+
if (receiverWalletData.id) {
73+
await Interaction.defer();
74+
const invoiceDetails = await receiverWallet.createInvote(amount.value, message.value);
6075
const invoicePaymentDetails = await senderWallet.payInvoice(invoiceDetails.payment_request);
61-
console.log(`invoice details`,invoicePaymentDetails);
76+
77+
console.log({
78+
sender: sender.user.id,
79+
receiver: receiver.user.id,
80+
amount: amount.value,
81+
message: message.value,
82+
invoiceDetails: invoicePaymentDetails
83+
});
6284

6385
await Interaction.editReply({
6486
content:`${senderData.toString()} sent ${valueString} to ${receiverData.toString()}`,
6587
});
6688
try {
6789
await receiverData.user.send(`${senderData.toString()} on ${receiverData.guild.toString()} sent you ${valueString}\nYou can access the wallet at ${process.env.LNBITS_HOST}/wallet?usr=${receiverWalletData.user}`);
6890
} catch (err) {
69-
console.log(err.status);
7091
console.log(`User was a bot or is blocking direct messages`);
7192
}
7293
}
7394
else {
7495
// This message should no longer fire as wallets are created as required
75-
Interaction.editReply({
96+
Interaction.reply({
7697
content:`${receiverData.toString()} has currently not set up a wallet. I have set one up please retry...`,
7798
});
7899
}

index.js

+30-27
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,36 @@
11
const Bot = require(`./Bot`);
22
const winston = require('winston');
33

4-
const logDate = new Date().toISOString();
5-
var fs = require( 'fs' );
6-
var logDir = 'logs';
7-
if ( !fs.existsSync( logDir ) ) {
8-
fs.mkdirSync( logDir );
9-
}
10-
const logger = winston.createLogger({
11-
level: 'info',
12-
format: winston.format.json(),
13-
transports: [
14-
new winston.transports.File({ filename: `./${logDir}/${logDate}_error.log`, level: 'error' }),
15-
new winston.transports.File({ filename: `./${logDir}/${logDate}_combined.log` }),
16-
],
17-
});
18-
19-
logger.add(new winston.transports.Console({
20-
format: winston.format.simple(),
21-
}));
22-
23-
console.log = function(){
24-
return logger.info.apply(logger, arguments)
25-
}
26-
console.error = function(){
27-
return logger.error.apply(logger, arguments)
28-
}
29-
console.info = function(){
30-
return logger.warn.apply(logger, arguments)
4+
if (process.env.LOG_TO_FILE == 'true'){
5+
const logDate = new Date().toISOString();
6+
var fs = require( 'fs' );
7+
var logDir = 'logs';
8+
if ( !fs.existsSync( logDir ) ) {
9+
fs.mkdirSync( logDir );
10+
}
11+
const logger = winston.createLogger({
12+
level: 'info',
13+
format: winston.format.json(),
14+
transports: [
15+
new winston.transports.File({ filename: `./${logDir}/${logDate}_error.log`, level: 'error' }),
16+
new winston.transports.File({ filename: `./${logDir}/${logDate}_combined.log` }),
17+
],
18+
});
19+
20+
logger.add(new winston.transports.Console({
21+
format: winston.format.simple(),
22+
}));
23+
24+
25+
console.log = function(){
26+
return logger.info.apply(logger, arguments)
27+
}
28+
console.error = function(){
29+
return logger.error.apply(logger, arguments)
30+
}
31+
console.info = function(){
32+
return logger.warn.apply(logger, arguments)
33+
}
3134
}
3235

3336
const DiscordBot = new Bot();

0 commit comments

Comments
 (0)