Joaco Remis
Joaco Remis

Reputation: 13

Parsing line by line in discord bot (node.js)

I'm making a discord bot with node.js and I have a .txt file with 3 lines:

User1|421
User2|5543
User3|12

And I want to parse only numbers after '|', I've used

fs.readFile('balance.txt', 'utf8', function(err, contents) {
         message.channel.sendMessage(contents);
   })

to get the text from it, what I want to do is check if the user that sends the request to check balance exists in the list, and if it exists print out the balance.

I'd like for the input to be

!balance

and output to be

$43

while checking:

User exists? Get line in which the user is in Get number after '|' and store it in a temporary variable to print

Thanks!

Upvotes: 1

Views: 3271

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30725

I'd try this approach, read this file into memory and create an accessor function for it:

const fs = require("fs");
const os = require('os');

fs.readFile('balance.txt', 'utf8', function(err, contents) {

    if (err) {
        console.error("Error occurred: ", err);
    } else {
        let balancesDetails = getUserBalances(contents);

        let user3BalanceDetails = balancesDetails.find(result => result.user === "User3");
        console.log("User 3 balance: ", user3BalanceDetails.balance);

        // Send the balance if required
        //message.channel.sendMessage(user3BalanceDetails.balance);
    }
});

function getUserBalances(fileContents) {
    return fileContents.split(os.EOL).map(line => line.split("|")).map(([user, balance]) => { return { user, balance: parseFloat(balance)} });
}

An example of this working in plain JavaScript would be like below (the only real difference is we can't use the OS object since this is Node.js only!):

let contents = `User1|421\nUser2|5543\nUser3|12`;

function getUserBalanceArray(fileContents) {
    return fileContents.split('\n').map(line => line.split("|")).map(([user, balance]) => { return { user, balance: parseFloat(balance)} });
}

function getUserBalanceMap(fileContents) {
    return fileContents.split('\n').map(line => line.split("|")).reduce((map, [user, balance]) => { map[user] = parseFloat(balance); 
    return map }, {});
}

console.log("File contents:\n" + contents);
console.log("Balance array: ", getUserBalanceArray(contents));
console.log("Balance map: ", getUserBalanceMap(contents));

Upvotes: 2

Related Questions