Text undefined - JavaScript - javascript

I'm currently making a chatbot for a school project.
So basically what I want is for the chatbot to send a copy of a certain message from the user's input to another channel. But when I run my code it returns the value as undefined. My code looks like the following:
bot.on('message', data => {
if (data.type !== 'message' || data.subtype === 'bot_message') {
return;
}
findClassroomMention(data.text);
});
var classrooms =
{
L108: ["L108","108"],
L208: ["L208","208"]
};
function findClassroomMention(message) {
var found = false
for(var ClassroomId in classrooms) {
for(var term of classrooms[ClassroomId]) {
if(message.includes(term)) {
found = ClassroomId;
break;
}
}
if (found) {
notifyProblemSolver();
break;
}
}
return found
};
function notifyProblemSolver(ClassroomId) {
const params = {
icon_emoji: ':smiley:'
}
bot.postMessageToChannel('caris','We have a problem in ' + ClassroomId, params);
};
For example the user's input is:
Hi I have a problem in classroom L108
Then I want the chatbot to send a message to the problemsolver containing the value L108, like this:
We have a problem in L108
But when I run the code it sends L108 as undefined:
We have a problem in undefined

You forgot to pass the ClassroomId in notifyProblemSolver()
Problem
if (found) {
// You forgot to pass the ClassroomId
notifyProblemSolver();
break;
}
Solution
if (found) {
// Add the ClassroomId
notifyProblemSolver(ClassroomId);
break;
}

from what I can see, notifyProblemSolver function is only called in
if (found) {
notifyProblemSolver();
break;
}
If you don't pass any arguments to the function call it, your ClassroomId parameter will be undefined in that specific call. I think what you meant to do was pass found to it like:
if (found) {
notifyProblemSolver(found);
break;
}

Related

One Function for Multiple Variables

I am making a sign up sheet app. There are several time slots one can write their name into and submit, showing their name where they have entered it at the corresponding time.
So far I can only get the function to do one name at a time. Is there a way to have it do the same function but for each time slot? Each input field has a corresponding <li> where I wish the input.value to appear. I am trying a switch() to no avail here.
Any help would be greatly appreciated.
Thanks
function addName(e) {
switch(e) {
case 0:
scheduleThree.appendChild(document.createTextNode(inputThree.value));
storeNameInLocalStorage(inputThree.value);
break;
case 1:
scheduleThreeTwoFive.appendChild(document.createTextNode(inputThreeTwoFive.value));
storeNameInLocalStorage(inputThreeTwoFive.value);
break;
}
}
For reference this is the working code for the function to run once. I know there must be a way to do it without writing new functions for each of the 12 time slots.
function addName(e) {
if(inputThree.value === '') {
// alert('Please enter your name');
} else {
scheduleThree.appendChild(document.createTextNode(inputThree.value));
storeNameInLocalStorage(inputThree.value);
}
}
function storeNameInLocalStorage(name) {
let names;
if(localStorage.getItem('names') === null){
names = [];
} else {
names = JSON.parse(localStorage.getItem('names'));
}
names.push(name);
localStorage.setItem('names', JSON.stringify(names));
}
function getNames() {
let names;
if(localStorage.getItem('names') === null){
names = [];
} else {
names = JSON.parse(localStorage.getItem('names'));
}
names.forEach(function(name){
scheduleThree.appendChild(document.createTextNode(name));
inputThree.remove();
inputThreeParent.appendChild(document.createTextNode(name))
})
}

TypeError: Cannot read property of null

I get the error in the title even though I have tried all the solutions. About the value of null;
If my code is ;
Output: TypeError: Cannot read property of null
case '!facebook':
face.Profile(facebook, function(result) {
let like = result.profiles.like;
let comments = result.profiles.comments;
if(like === null || comments === null){
//code.
}
else {
//code.
}
});
break;
You have to verify that each child of your object exists before you reference the next level. In your case, that means testing the existence of result and then result.profiles before trying to use any of the object values in profiles. See the code below.
Without seeing the rest of your case statement or how you're setting the value of face, it's hard to tell if you're going to run into other issues.
case '!facebook':
face.Profile(facebook, function(result) {
// Set default values
let like = null;
let comments = null;
// Set values only if there's a result containing profiles
if (result && result.profiles) {
like = result.profiles.like;
comments = result.profiles.comments;
}
if (like === null || comments === null){
//code
} else {
//code
}
});
break;

Calling a function within a for loop - JavaScirpt

Hi I am trying to call a function within a for loop but It isn't working...This is how my code currently looks like:
bot.on('message', data => {
if (data.type !== 'message' || data.subtype === 'bot_message') {
return;
}
findClassroomMention(data,text);
});
var classrooms =
{
L108: ["lokaal 108","L108","108"],
L208: ["lokaal 208","L208","208"]
};
function findClassroomMention(message) {
var found = false
for(var ClassroomId in classrooms) {
for(var term of classrooms[ClassroomId]) {
if(message.includes(term)) {
found = ClassroomId;
notifyProblemSolver();
break;
}
}
if (found) notifyProblemSolver(); break;
}
return found
};
function notifyProblemSolver(ClassroomId) {
const params = {
icon_emoji: ':smiley:'
}
bot.postMessageToChannel('caris','We have a problem in' + ClassroomId, params);
};
I want the function notifyProblemSolver() to be called in the for loop...But if I run the code it isn't working. Any tips? Thanks in advance!
I think if (found) notifyProblemSolver; break; is the issue. That break will be called regardless of if (found) so for(var ClassroomId in classrooms) { will only run once.
I think you meant
if (found) {
notifyProblemSolver();
break;
}
I've seen some unnecessary semicolons at the end of functions. Also the part:
if (found) notifyProblemSolver; break;
Should be replaced with:
if (found) notifyProblemSolver(); break;
Because you are calling a function here, instead it was an expression.
Let me know if this works.
Full code modification here:
https://jsfiddle.net/terza_terza/ms9xLrzu/3/

parse JSON object with value passed as single quote string

I an getting aws event parameter as follow in the lambda call.
let event = { pathParameters: '{"foo":"35314"}' }
When I am trying to validate the parameter in condition , it cant find foo key on pathParameters
Here my condition check
if (event.pathParameters && event.pathParameters.foo) {
//do something
} else {
console.log('fail');
}
It going in else condition . I tried JSON.parse(JSON.strinify(event)). It did not help. I do get the Object if I do JSON.parse(event.pathParameters).
Any way to resolve the issue on root level object.
No, you can't parse the event to get access to the '{"foo": "35314}'", you need to parse the event.pathParameters value to get the actual foo and its value, 35314
let event = { pathParameters: '{"foo":"35314"}' }
if (event.pathParameters && JSON.parse(event.pathParameters).foo) {
console.log("'foo' =", JSON.parse(event.pathParameters).foo);
} else {
console.log('fail');
}
This is because the data that you are getting has JSON as stringified in pathParameters, so you'll have to parse with that key something like
JSON.parse(event.pathParameters).foo
let event = { pathParameters: '{"foo":"35314"}' } // foo is a string
if (event.pathParameters) {
try {
const { foo } = JSON.parse(event.pathParameters);
// use foo
} catch (jsonError) {
console.log('There was some json parse error', jsonError);
}
} else {
console.log('fail');
}
You need to parse the data from event.pathParameters
function doSomething(event) {
let pathParametersObj = JSON.parse(event.pathParameters);
if (pathParametersObj && pathParametersObj.foo) {
//do something
console.log('pass');
} else {
console.log('fail');
}
}
let event1 = {
pathParameters: '{"foo":"35314"}'
}
let event2 = {
pathParameters: null
}
doSomething(event1);
doSomething(event2);

Debugging a background script in a Chrome extension

I'm trying to use some code from an open source library and I'm having some trouble logging to check where the code is failing.
In background.js:
chrome.extension.onRequest.addListener(function(request, sender, response) {
// This does not show in my console
console.log("request here");
switch(request.type) {
case 'enable?':
objectName.onTabSelect(sender.tab.id);
break;
case 'search':
// Also does not log here
console.log("Gets to first search item");
var e = objectName.search(request.text);
response(e);
break;
case 'open':
....
}
In content.js:
//This shows in my console
console.log("CHAR");
console.log(char);
document.body.innerText.match(/[\u3400-\u9FBF]/g).forEach(function (char) {
chrome.extension.sendRequest({
"type": "search",
"text": char
},
function (char_return) {
//This shows in my console, but is an empty obj and why I want to debug
console.log("char return");
console.log(char_return);
});
});
In main.js, a background script:
var objectName = {
...
search: function(text) {
// Does not log here. This is the area I REALLY want to log.
console.log("Char search gets here");
var entry = this.dict.wordSearch(text);
if (entry != null) {
for (var i = 0; i < entry.data.length; i++) {
var word = entry.data[i][1];
if (this.dict.hasKeyword(word) && (entry.matchLen == word.length)) {
// the final index should be the last one with the maximum length
entry.grammar = { keyword: word, index: i };
}
}
}
return entry;
}
}
How do I log in a background script? It looks like maybe I should be using the chrome.webRequest method? Could this be because some of the methods are deprecated? I intend on updating them to the new methods once I've got the application working, but to get it working I need to log and see where it is failing.
This is the first Chrome extension I've built so I'm not quite sure how this works.

Categories

Resources