Twitch Bot in Node JS log system - javascript

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

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?

Related

How to detect if the bot has been mentioned?

How can I detect if my bot is mentioned?
I tried these thus far:
if (msg.content.toLowerCase().includes('#The Guardian of The Bar#5180')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
if (msg.content.toLowerCase().includes('#The Guardian of The Bar')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
if (msg.content.includes('#The Guardian of The Bar#5180')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
if (msg.content.includes('#The Guardian of The Bar#5180')) {
msg.channel.send("My prefix here is" + prefix + "\n You can start with ``" + prefix + "help``");
}
I'm not experienced in discord.js, but according to this in the documentation, a message object has a method message.isMemberMentioned(User or GuildMember). Using this method, one can use
client.on('message', message => { //this event is fired, whenever the bot sees a new message
if (message.isMemberMentioned(client.user)) { //we check, whether the bot is mentioned, client.user returns the user that the client is logged in as
//this is where you put what you want to do now
}
});
I would like to recommend, that you read the documentation fully, before you try to make a bot.
On v12 discord.js you now have to use message.mentions.has(bot.user)

Returning a concatenated string from a functions' properties in javascript

I'm a total JS beginner. Here is the JsBin link formLetter test should be passing.
TL;DR
This:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender
};
console.log(formLetter("Hermione", "Luna","How are you?"));
Should return:
"Hello Hermione,
How are you?
Sincerely,
Luna"
But instead I get this:
"Hello [object Object],
undefined
Sincerely,
undefined"
Edit
Sorry for the confusion. I'm working on different problems inside one JsBin. This is the correct JsBin with the isolated code.
This is because you are only getting one object passed into the function call. This object contains the information you need in lieu of the named arugments you have provided.
The first argument, recipient being [object Object] tells you that it's an object. undefined means that nothing was passed in their place. This signifies the common pattern of a config or param object being passed to the function call. Because of this, what you have as named arguments should really be property look ups on the object provided as the first argument.
Your function definition should look more like:
var formLetter = function (letter) {
// do something with letter
};
Inside of that function call, you may then hit the properties of the letter object to see if they contain what you need, Doing console.log debugging in dev tools will help track it down.
The line:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender
};
in your example needs one semicolon after "sender", like:
var formLetter = function(recipient, msg, sender) {
return "Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender;
};
Your undefined is related to the use of anidated console.log.
You do:
console.log(longMessage.formLetter("Hermione", "Luna","How are you?"));
and (in the JsBin) you have also:
var longMessage = {
formLetter: function(recipient, sender, msg) {
console.log("Hello " + recipient + ",\n" + "\n" + msg + "\n" + "\nSincerely," + "\n" + sender);
}
};
In the example of your question you have them corrected.
Double check the code you post, please.
After looking at your test in jsbin, I noticed that in your assert.deepEqual() method you run formLetter(letter) and compares it to the concatenated string you created.
The problem is that formLetter() expects three string values and you send it an object (letter). That's why you get [Object object] in the first location and undefined in the others.
You should run formLetter(letter.recipient, letter.msg, letter.sender) in your assert and it should work properly.

binding variables to SQL statements using node-sqlite3

I am trying to convert this:
var query_string = 'SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_A = "' + item + '" ' +
'UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM ' + organism + PIPE_output_table +
' WHERE ' + score_type + ' > ' + cutoff['range'] + ' AND protein_B = "' + item + '";';
db.each(query_string, function (err, row) {
...
To this:
var query_string = "SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'" +
" UNION SELECT protein_A, protein_B, PIPE_score, site1_A_start FROM $table WHERE $score_type > $score AND protein_A = '$protein'";
var placeholders = {
$table: organism + PIPE_output_table,
$score_type: score_type,
$score: cutoff['range'],
$protein: item
};
var stmt = db.prepare(query_string, placeholders, function(err) {
console.log(err);
stmt.each(function(err,row) {
...
})
}
but I keep getting this error:
Error: SQLITE_ERROR: near "$table": syntax error
But I am not sure what is syntactically wrong here since the format is as I have seen it in the API documentation. I have tried '?', '#', and ':' before each variables but none seem to be recognized.
What's wrong in my code?
Bind parameters only work for values in the WHERE clause. Table and column names (collectively called "identifiers") won't work.
"SELECT foo FROM bar WHERE this = $that" # OK
"SELECT foo FROM bar WHERE $this = 'that'" # Not OK
Normally you'd work around this by escaping and quoting identifiers and inserting them into the query. A good database library has a method call for this...
var this = db.quote_literal(input_column);
'SELECT foo FROM bar WHERE ' + this + ' = ?'
Unfortunately, node-sqlite3 doesn't appear to have one. :(
SQLite does provide a quoting function, the %w operator, but node-sqlite3 doesn't appear to make it available.
You'll have to write your own. Follow the instructions from this answer in Python and convert them to Javascript.
Ensure the string can be encoded as UTF-8.
Ensure the string does not include any NUL characters.
Replace all " with "".
Wrap the entire thing in double quotes.
I'm not very good with Javascript, so I'll leave you to code that.

error due to single quote in a parameter in url query string

I have a screen from which I am passing a parameter to other screeen. This parameter contains a single quote. (For eg. ABC's xyz). The other screen shows this paramter correctly on screen. However, I am not able to submit the request on load to servlet. I am not able to figure out why?
Tried using URL encoding, replacing ' with \' and replacing ' with %27. Didn't work for me. Plz help.
The code is as follows.
child page var scheme = document.forms[0].scheme.value;
window.location.href = redirectVal+".jsp?levelOfReport="
+ levelOfReport
+ "&circleCode="
+ circleCode
+ "&networkCode="
+ networkCode
+ "&moduleCode="
+ moduleCode
+ "&regionCode="
+ regionCode
+ "&branchCode="
+ branchCode
+ "&circleName="
+ circleName
+ "&moduleName="
+ moduleName
+ "&branchName="
+ branchName
+ "&Amount="
+ Amount
+ "&scheme="
+ scheme + "&fromDate=" + fromDate + "&toDate=" + toDate;
Child page
SubmitButton('./Report.do?method=getAgriProductWisePerformanceReport&levelOfReport=&scheme=<%=request.getParameter("scheme")%>
You're missing the end to your method call.
SubmitButton('./Report.do?method=getAgriProductWisePerformanceReport&levelOfReport=&scheme=<%=request.getParameter("scheme")%>
Map your quotes to eachother, you're telling it to do something like
SubmitButton('./SubmitButton('./Report.do?method=getAgriProductWisePerformanceReport&levelOfReport=&scheme=HTTP
You need to add an additional '); at the end of that line

Contacts of Firefox OS problems with mozContacts.tel

I've been trying to get the contact name and last name and also get the cellphone number but when I am using the getAll() method the Console display this:
Found: Daniel Garcia [object Object]
As you can see it displays the Name + LastName + tel. Why does it display tel like [object Object]
Here is my code:
var allContacts = navigator.mozContacts.getAll({
sortBy: "givenName",
sortOrder: "ascending"
});
allContacts.onsuccess = function(event) {
if (cursor.result) {
if (cursor.result.familyName[0]== undefined) {
cursor.result.familyName[0]= "";
}
console.log("Found: " + cursor.result.givenName[0] + " " + cursor.result.familyName[0] + ' ' + cursor.result.tel[0]);
cursor.continue();
} else {
console.log("No more contacts");
}
}
tel here is an array of objects - a list of all the possible phone numbers for the contact. Each of this objects has several useful properties. In javascript when you are printing out an object it prints an object string representation (like [object Object]).
Check out docs to understand the structure of the tel object and get it printed the way you want: https://developer.mozilla.org/en-US/docs/Web/API/mozContact.tel
Thank you very much it work just like Aras and jamesh proposed
console.log("Found: " + cursor.result.givenName[0] + " " + cursor.result.familyName[0]+' '+JSON.stringify(cursor.result.tel[0]));
and the console display this:
"Found: Daniel Garcia {"type":["mobile"],"value":"8112441018"}"

Categories

Resources