Parsing error Javascript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Getting a parsing error in javascript while deploying firebase functions... Its showing unexpected token which if i'm not mistaken means that there is an unexpected character somewhere... Stuck here for weeks now... Can somone help me out please
Code
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref(`/Notifications/${user_id}/${notification_id}/`).onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to ', user_id);
if (!change.after.val()) {
return console.log("A Notification has been deleted from the database", notification_id);
}
const fromUser = admin.database().ref('/Notifications/${user_id}/${notification_id}').once('value');
return fromUser.then(fromUserResult => {
const fromUserId = fromUserResult.val().from;
console.log('You have a new notification from : ', from_user_id);
const userQuery = admin.database().ref('UserData/${fromUserId}/name').once('value');
return userQuery.then(userResult => {
const userName = userResult.val();
const deviceToken = admin.database().ref(`/UserData/${user_id}/TokenID`).once('value');
return deviceToken.then(result => {
const token_id = result.val();
const payload = {
notification: {
title: '${userName}',
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notofication Feature');
});
});
});
});

You're missing two pairs of }) at the end of the file. So:
...
return admin.messaging().sendToDevice(token_id, payload).then(response =>{
return console.log('This was the notofication Feature');
});
});
});
});
});
It is understandably impossible to see this with your current code.
The lack of indentation makes it incredibly hard to parse. That's why I passed the code through http://jsbeautifier.org/, which makes it much easier to parse.
I also recommend using a tool like https://eslint.org/demo/ to make it easier to find mistakes like this.

you'll still have few bugs in your code. on three places you're using single quote ' instead of back-tick `
...
const fromUser = admin.database().ref(`/Notifications/${user_id}/${notification_id}`).once('value');
...
const userQuery = admin.database().ref(`UserData/${fromUserId}/name`).once('value');
...
const payload = {
notification: {
title: `${userName}`,
body: "You have recieved a new Message",
icon: "default",
click_action: "com.appmaster.akash.messageplus_TARGET_NOTIFICATION"
},
data: {
from_user_id: fromUserId,
from_user_name: userName
}
};

Related

_query is not a function. (In '_query((0, _database.ref) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 15 hours ago.
Improve this question
I am getting an Error when using database _query
Error
ERROR TypeError: _query is not a function. (In '_query((0, _database.ref)(_FirebaseConfig.database, 'users'), (0, _database.orderByChild)('email'), (0, _database.equalTo)(email))', '_query' is undefined)
code:
(note that query is not being highlighted as used )
import { ref, get, set, orderByChild, equalTo, query } from 'firebase/database';
useEffect(() => {
const writeToDatabase = () => {
const email = UserDataFromGoogleAuth.email;
if (email) {
const query = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
get(query)
.then((snapshot) => {
const uuid = snapshot.exists() ? Object.keys(snapshot.val())[0] : uid();
const userRef = ref(database, `/users/${uuid}`);
const userData = {
id: uuid,
name: UserDataFromGoogleAuth.displayName,
email: email,
profilePicture: UserDataFromGoogleAuth.photoURL,
};
return set(userRef, userData);
})
}
};
writeToDatabase();
}, [location, UserDataFromGoogleAuth, props.online, database]);
**
"firebase": "^9.17.1",**
I am getting an Error when using database _query
On this line:
const query = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
You define a variable called query and then try to assign it a value based on calling that same uninitialized variable because it shadow's the query method you are importing from the firebase/database library.
Rename the variable to something else to prevent shadowing the imported method.
const usersWithMatchingEmailQuery = query(ref(database, 'users'), orderByChild('email'), equalTo(email));
get(usersWithMatchingEmailQuery)
.then(/* ... */)
Note: Don't forget to add a catch() to that Promise chain to handle errors.

How to solve "Message content must be a non-empty string" in node.js [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Here is my code,
const { Client, Intents } = require('discord.js');
const mineflayer = require("mineflayer");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
let sending = false
let chatData = []
let prefix = ".";
var settings = {
username: "StilShem_tvink",
host: "mstnw.net",
};
const bot = mineflayer.createBot(settings);
bot.on('kicked', (reason, loggedIn) => console.log(reason, loggedIn));
bot.on('error', err => console.log(err));
client.on("ready", async =>{
console.log("Discord bot is online!")
})
bot.on("login", async =>{
console.log("Minecraft bot is online!")
})
bot.on("message", message => {
if(sending == true) {
chatData.push(`${message}`)
}
})
client.on("messageCreate", async msg => {
let args = msg.content.split(" ").slice(1)
if(msg.content.startsWith(".chat")) {
let toSend = args.join(" ");
if(!toSend) return msg.reply("No args")
bot.chat(toSend)
sending = true
msg.channel.send(`${msg.author.tag} just sent ${toSend}`)
setTimeout(() => {
sending = false
msg.channel.send(chatData.join("\n"))
chatData = []
}, 750)
}
})
This code is for minecraft mineflayer with discord. And this code give me error.
C:\Users\ArtemiiYT\node_modules\discord.js\src\util\Util.js:414
if (!allowEmpty && data.length === 0) throw new error(errorMessage);
^
RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty
string.
at Function.verifyString (C:\Users\ArtemiiYT\node_modules\discord.js\src\util\Util.js:414:49)
at MessagePayload.makeContent (C:\Users\ArtemiiYT\node_modules\discord.js\src\structures\MessagePayload.js:113:22)
at MessagePayload.resolveData (C:\Users\ArtemiiYT\node_modules\discord.js\src\structures\MessagePayload.js:128:26)
at TextChannel.send (C:\Users\ArtemiiYT\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:168:61)
at Timeout._onTimeout (C:\Users\ArtemiiYT\Desktop\Всё\AFK bot\AFKBOTDS\bot.js:46:25)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) { [Symbol(code)]: 'MESSAGE_CONTENT_TYPE' }
Node.js v17.1.0
I didn't go on my way to run the code, but I think the chatData array is empty. so when you try to .join("\n") all the elements inside it together, you just get an empty string which discord just rejects and you get an error.
so you might want to check if there is anything in the array first.
if you are here for the code just add this in the interval function:
if(chatData.length < 1) {
// maybe inform the user there is no new chat message?
return;
}

Advice converting an onCreate firebase cloud function trigger with FCM Messaging to support async/await and database reads

I initially had a simple firebase cloud function that sent out a push notification to a topic when a new message child was created in my real-time database. But I wanted to add message filtering where notifications for messages from some filtered users would be sent only to admin users. For this, I have created user groups in my real-time database of the format {userName: FIRToken}, which gets written to from my iOS App every time it launches and I get a FIRToken. So now I will have to load 2 lists 1) Admin Users, 2) Filtered Users before I can actually decide where to send the notification.
So I looked into ways to do this and async/await seemed better than doing a promise inside a promise for loading my 2 user lists. I then saw a firestore video tutorial where a similar usecase function was converted to use async/await instead of promises in promises. Following that, I refactored my code to await on the 2 snapshots for admin and filtered users, before going on to decide where to send the notification and return a promise. My refactoring seems correct. But unfortunately, my old iPhone is stuck on <DeviceName> is busy: Copying cache files from device. Hence I can't physically login from 2 different devices and test if the notifications are going only to my admin user account. Which is why I am posting my function here to see if I have refactored my code correctly or missed something. Please let me know if I will get the intended results or I should fix something in the code.
Edit: Updated code to fix these issues:
Also, the methods to send messages are very confusing. send needs topic name to be defined in the payload but does not support apns. sendToTopic needs a topic name as an argument with the payload. sendMulticast fails to send messages to users whereas sendToDevice sends properly.
Finally sendToDevice supports sound field in notification field, but send does not.
functions.database
.ref("/discussionMessages/{autoId}/")
.onCreate(async (snapshot, context) => {
// console.log("Snapshot: ", snapshot);
try {
const groupsRef = admin.database().ref("people/groups");
const adminUsersRef = groupsRef.child("admin");
const filteredUsersRef = groupsRef.child("filtered");
const filteredUsersSnapshot = await filteredUsersRef.once("value");
const adminUsersSnapshot = await adminUsersRef.once("value");
var adminUsersFIRTokens = {};
var filteredUsersFIRTokens = {};
if (filteredUsersSnapshot.exists()) {
filteredUsersFIRTokens = filteredUsersSnapshot.val();
}
if (adminUsersSnapshot.exists()) {
adminUsersFIRTokens = adminUsersSnapshot.val();
}
// console.log(
// "Admin and Filtered Users: ",
// adminUsersFIRTokens,
// " ",
// filteredUsersFIRTokens
// );
const topicName = "SpeechDrillDiscussions";
const message = snapshot.val();
// console.log("Received new message: ", message);
const senderName = message.userName;
const senderCountry = message.userCountryEmoji;
const title = senderName + " " + senderCountry;
const messageText = message.message;
const messageTimestamp = message.messageTimestamp.toString();
const messageID = message.hasOwnProperty("messageID")
? message.messageID
: undefined;
const senderEmailId = message.userEmailAddress;
const senderUserName = getUserNameFromEmail(senderEmailId);
const isSenderFiltered = filteredUsersFIRTokens.hasOwnProperty(
senderUserName
);
console.log(
"Will attempt to send notification for message with message id: ",
messageID
);
var payload = {
notification: {
title: title,
body: messageText,
},
data: {
messageID: messageID,
messageTimestamp: messageTimestamp,
},
apns: {
payload: {
aps: {
sound: "default",
},
},
},
};
console.log("Is sender filtered? ", isSenderFiltered);
if (isSenderFiltered) {
adminFIRTokens = Object.values(adminUsersFIRTokens);
console.log("Sending filtered notification with sendMulticast()");
payload.tokens = adminFIRTokens; //Needed for sendMulticast
return admin
.messaging()
.sendMulticast(payload)
.then((response) => {
console.log(
"Sent filtered message (using sendMulticast) notification: ",
JSON.stringify(response)
);
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(adminFIRTokens[idx]);
}
});
console.log(
"List of tokens that caused failures: " + failedTokens
);
}
return true;
});
} else {
console.log("Sending topic message with send()");
payload.topic = topicName;
return admin
.messaging()
.send(payload)
.then((response) => {
console.log(
"Sent topic message (using send) notification: ",
JSON.stringify(response)
);
return true;
});
}
} catch (error) {
console.log("Notification sent failed:", error);
return false;
}
});

chatbot answers my previously asked questions again even when i am silent/not asking anything

I am developing a chatbot in urdu with wit.ai framework. Chatbot works fine but the issue is when i leave the chatbot for sometime after asking some questions, it start answering the previously told answers in a sequence by starting from first answer to the last one.it means it repeats a sentence but only once. when all the answers are resent, then chatbot does not send them again. I a using Pusher API for realtime responses.I am adding here things in the code which i am not sure about like i don't know what is the purpose of using cors.
Here is some part of my server.js file.
const cors = require('cors');
app.post('/chat', (req, res) => {
const { message } = req.body;
const responses = {
helloo: ["ہیلو! میں امید کرتا ہوں کہ آپ خیریت سے ہیں", ],
};
const firstEntityValue = (entities, entity) => {
const val =
entities &&
entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value;
if (!val) {
return null;
}
return val;
};
const handleMessage = ({ entities }) => {
const helloo = firstEntityValue(entities, 'hello');
if(helloo){
return pusher.trigger('bot', 'bot-response', {
message:
responses.helloo[Math.floor(Math.random() * responses.helloo.length)
],
});
}
return pusher.trigger('bot', 'bot-response', {
message: "میں معزرت خواہ ہوں۔ ",
});
};
client
.message(message)
.then(data => {
handleMessage(data);
})
.catch(error => console.log(error));
});
All this code works fine but i don't know where the issue is that chatbot answers the same answer twice.i am new to javascript and react also. i don't see a loop here which gives answer twice. kindly help me solve the issue.
https://drive.google.com/drive/folders/1TxbqAz_Hfv9bpgY60fLf5TVXwyux_fcI
This is the drive link to my project.

Paths must be non-empty strings and can't contain ".","#","$","[",or"]". How on earth do you solve this? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
So I am trying to work with notifications from device to device and this error is driving me crazy, I don't know where I am doing wrong. I have tried everything and searched up to my best to solve this, any help is greatly appreciated. Thank you!
[EDIT : i had posted the question about another error here and it got solved but lead to this new error]
This is my FirebaseMessagingClass
package com.pappu5.navigation;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseMessaging extends
com.google.firebase.messaging.FirebaseMessagingService {
private String channelId = "com.pappu5.navigation";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notificationTtile = remoteMessage.getNotification().getTitle();
String notificationBody = remoteMessage.getNotification().getBody();
String clickAction = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(this,channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notificationTtile)
.setContentText(notificationBody)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
int notificationId = (int) System.currentTimeMillis();
Intent intent = new Intent(clickAction);
intent.putExtra("user_id",from_user_id);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(notificationId, mBuilder.build());
}
This is Firebase index.js file
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification =
functions.database.ref('/Notifications/{user_id}/{notification_id}').
onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification to send to : ',
context.params.user_id);
const fromUser =
admin.database().ref('/Notifications/'+user_id+'/'+notification_id +
'/From').once('value');
return fromUser.then(fromUserResult => {
const from_user = fromUserResult.val();
console.log('You have new notification from : ',from_user);
const use_Query =
admin.database().ref(`/Chat_Profiles/{from_user}/name`).once('value');
const deviceToken =
admin.database().ref(`/Chat_Profiles/{user_id}/device_token`)
.once('value');
return Promise.all([use_Query,deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
const payload = {
notification: {
title: "Friend Request",
body: userName+" has sent you request",
icon: "default",
click_action : "com.pappu5.navigation_TARGET_NOTIFICATION"
},
data : {
from_user_id: from_user
}
};
console.log(payload);
return admin.messaging().sendToDevice(token_id,payload).then(response => {
return console.log('This was the notification feature');
});
});
});
});
In 'Chat_Profiles/'+from_user+'/name', from_user is an object. The default toString of an object returns [object Object], which is why you get "/Chat_Profiles/[object Object]/name", which is being refused. You likely wanted to use user_id, and not from_user.

Categories