Search code examples
javascriptnode.jstwitch

Twitch Bot in Node JS log system


I'm working on a twitch bot in node.js and using tmi.js https://github.com/Schmoopiie/tmi.js

My problem is with the logging system I created. I think I'm misunderstanding node.js from the ground up here. I need to get the username from the chatter that just typed something. This is my code:

client.on('chat', function (channel, user, message, self) {

    fs.open('logs/' + user +'.txt','r',function(err,fd){
    if (err && err.code=='ENOENT') 
    {
    fs.writeFile('logs/' + user +'.txt', '[' + 'GMT' + moment().format('Z ') + moment().format('D.M.YYYY H:mm:ss')  + '] ' + user + ': ' + message, function (err) {});
    } else {
    fs.appendFile('logs/' + user +'.txt', '[' + 'GMT' + moment().format('Z ') + moment().format('D.M.YYYY H:mm:ss')  + '] ' + user + ': ' + message + '\n', function(){});      
    }
    });

});

this triggers everytime a user types a message in chat. And I thought the variable "user" would have the value of the chatter that just typed something.

But the value of user is always [object Object]

Am I overlooking something? I can't find a way to get the username of the current chatter.

Thanks for the help guys


Solution

  • I can't say I have any experience with tmi.js, but it appears the user variable you're getting there is an object, not a string. When you try to cast it to a string using +, you get [object Object] by default. Try doing this:

    fs.appendFile('logs/' + JSON.stringify(user) +'.txt', '[' + 'GMT' + moment().format('Z ') + moment().format('D.M.YYYY H:mm:ss')  + '] ' + JSON.stringify(user) + ': ' + message + '\n', function(){});
    

    or, even better, because you want that just for debugging:

    console.log(user);
    

    And check the console. It probably won't be pretty, but at least you'll be able to see what's inside the user variable. Perhaps it will be an object with a username property, and you'll be able to simply use user.username?