socket.handshake.session.keyname shows undefined - sockets

I'm making a multiplayer game. below is the flow of the process when i get an error:
(1) After logging in the username is getting stored in session:
socket.on('login', function(username)
{
socket.handshake.session.username = username;
socket.handshake.session.save();
var afterLogin = '/groups';
socket.emit('afterLogin', afterLogin);
});
(2) User get redirect to another page and complete the game, after completing the game user send score and room id to the server:
var submitScore = { score: hit, room: 'gryffindor'};
socket.emit('submitScore', submitScore);
(3) Server get the score and room-id and iterate through all the client and decide the max score, get the username from the session, and send the winner name and score to all user:
socket.on('submitScore', function(submitScore)
{
var room = submitScore.room;
var score = submitScore.score;
if (room == "gryffindor")
{
gryfScoreArray[socket.handshake.session.username] = score;
checkGryfUser --;
if (checkGryfUser == 0)
{
var max = 0;
var winnerName;
for(var index in gryfScoreArray)
{
if (gryfScoreArray[index] > max)
{
max = gryfScoreArray[index];
winnerName = index;;
}
}
// console.log(socket.id);
var winner = {username: winnerName, maxScore: max}
io.in(room).emit('gryfWinner', winner);
// console.log(winner.username);
// console.log(winner.maxScore);
}
}
So, the problem is socket.handshake.session.username giving undefined in point point (3)

Related

Trying to Move Cards

I am trying to move a card I have found using the search function from one list to another on the same board.
I have tried to set up a new list using the a new factory.list and searching for the list using FirstorDefault LINQ Query but keep getting an Error.
Below is some code I have tried to move my cards.
string query = jnum;
var search = factory.Search(query, 1, SearchModelType.Cards, new IQueryable[] { board });
await search.Refresh();
var CardList = search.Cards.ToList();
foreach (var card in CardList)
{
string tName = card.Name.Substring(0, 6);
if (tName == jnum.Trim())
{
cardid = card.Id;
}
}
var FoundCard = factory.Card(cardid);
string FoundListid = FoundCard.List.Id;
var fromlist = factory.List(FoundListid);
if (Item != null)
{
if (mail.Body.ToUpper().Contains("Approved for Print".ToUpper()))
{
//var ToList = factory.List("5db19603e4428377d77963b4");
var ToList = board.Lists.FirstOrDefault(l => l.Name == "Signed Off");
FoundCard.List = ToList;
// from on proof
//MessageBox.Show("Approved for Print");
}
else if (mail.Body.ToUpper().Contains("Awaiting Review".ToUpper()))
{
//var ToList = factory.List("5db19603e4428377d77963b3");
var ToList = board.Lists.FirstOrDefault(l => l.Name == "On Proof");
FoundCard.List = ToList;
// from in progress or to start
// MessageBox.Show("Awaiting Review");
}
else if (mail.Body.ToUpper().Contains("Amends".ToUpper()))
{
var ToList = factory.List("5dc9442eb245e60a39b3d4a7");
FoundCard.List = ToList;
// from on proof
//MessageBox.Show("Amends");
}
else
{
// non job mail
}
}
I keep getting a is not a valid value Error.
Thanks for help

Download all user aliases to a Google spreadsheet

I am attempting to list all user aliases in our network. However, I am having a bit of trouble. I'm working from a bit of canned code here. I know the alias is an array but accessing it per user then listing just the aliases has me seeing double. Any help or tips is much appreciated!
function AliasDomainUsersList() {
var users_alias = [];
var options_alias = {
domain: "northstarmoving.com", // Google Apps domain name
customer: "my_customer",
maxResults: 100,
projection: "full", // Fetch basic details of users
viewType: "domain_public",
orderBy: "email" // Sort results by users
}
do {
var response = AdminDirectory.Users.list(options_alias);
response.users.forEach(function(user) {
users_alias.push([user.name.fullName, user.primaryEmail]);
});
// For domains with many users, the results are paged
if (response.nextPageToken) {
options_alias.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Users-Aliases") || ss.insertSheet("Users-Aliases", 1);
sheet.getRange(1,1,users_alias.length, users_alias[0].length).setValues(users_alias);
}
I think something like this might work. I haven't tested this because I'm the only person in my business account.
function AliasDomainUsersList() {
var users_alias = [];
var options_alias = {
domain: "northstarmoving.com", // Google Apps domain name
customer: "my_customer",
maxResults: 100,
projection: "full", // Fetch basic details of users
viewType: "domain_public",
orderBy: "email" // Sort results by users
}
do {
var response = AdminDirectory.Users.list(options_alias);
for(var i=0;i<response.users.length;i++) {//you will probably want to do this your way.
users_alias.push([response.users[i].name,response.users[i].primaryEmail]);
}
// For domains with many users, the results are paged
if (response.nextPageToken) {
options_alias.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Users-Aliases") || ss.insertSheet("Users-Aliases", 1);
sheet.getRange(1,1,users_alias.length, users_alias[0].length).setValues(users_alias);
var sheet2=ss.getSheetByName('AnotherSheet')
var rg2=sheet2.getRange(1,1,users_alias.length,1);
var vA2=rg2.getValues();
for(var i=0;i<vA2.length;i++) {
vA2[i][0]=users_alias[i][1];
}
rg2.setValues(vA2);
}
Managed to work out the solution (with some help). Here it is:
function getDomainUsersList() {
var users = [];
var options = {
domain: "northstarmoving.com", // Google Apps domain name
customer: "my_customer",
maxResults: 500,
projection: "full", // Fetch details of users
viewType: "domain_public",
orderBy: "email" // Sort results by users
}
do {
var response = AdminDirectory.Users.list(options);
response.users.forEach(function(user) {
users.push([user.name.fullName, user.primaryEmail]);
});
// For domains with many users, the results are paged
if (response.nextPageToken) {
options.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Users") || ss.insertSheet("Users", 1);
sheet.getRange(1,1,users.length, users[0].length).setValues(users);
}

Google apps script, forward all emails except one

I have a script that forwards all of my emails that come in during specific times to email#domain.com.
The problem I am having, is that sometimes email#domain.com sends me an email during that time.
Can anyone suggest a way to add a rule that it should forward to all addresses except forwarding address?
function forwardEmails() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var settings = ss.getSheetByName('Settings').getDataRange().getValues();
if (settings[1][1] == 'No')
return;
if (settings[2][1] == "")
throw new Error('Please set Forward Email!');
var email = PropertiesService.getScriptProperties().getProperty('email');
if (!email)
throw new Error('First authorize script by clicking on menu: Email Forwarder >> Authorize Script');
var today = (new Date());
var applicableRules = validRules(today);
if (applicableRules) {
var unread = GmailApp.getInboxUnreadCount();
if (!unread)
return;
var threads = GmailApp.getInboxThreads(0, unread>100?100:unread);
var cutOff = today.getTime() - (MINUTES*60*1000 + 100); // 10 mins + 100 ms
for (var i=0; i<threads.length; i++) {
var msgs = threads[i].getMessages();
for (var j=0; j<msgs.length; j++) {
var from = msgs[j].getFrom();
var msgDate = msgs[j].getDate();
var msgTime = (new Date(msgDate)).getTime();
var diff1 = msgTime - cutOff;
if (diff1 > 0 && from.indexOf(email) == -1) {
var to = msgs[j].getTo();
var subject = msgs[j].getSubject();
var attach = msgs[j].getAttachments();
var body = msgs[j].getBody();
var plainBody = msgs[j].getPlainBody();
var replyTo = msgs[j].getReplyTo();
var options = {replyTo: from};
if (attach.length > 0)
options.attachment = attach;
GmailApp.sendEmail(settings[2][1], subject, plainBody, options );
}
}
}
}
} catch (error) {
var html = '<p>'+ error + '</p><br><br>Email Forwarder Rules & Settings<p>Line: '+ error.lineNumber + ', Filename: ' + error.fileName + '</p>';
if (!email)
email = Session.getActiveUser().getEmail();
MailApp.sendEmail(email, 'Email Forwarder Script Failed!', error + '\n\nEmail Forwarder Rules & Settings URL: ' + ss.getUrl(), {htmlBody: html});
}
}
Instead of using getInboxThreads() use search().
getInboxThreads() will return threads in your inbox while search() will return those that meet the search query. The following query will include include messages in your inbox but exclude those from email#domain.com
in:inbox -from:email#domain.com
You could add a check in the second loop of the "forwardEmails" function. The code below would skip any unread emails which have arrived from the forwarding address (I'm assuming the forwarding email is referenced in "settings[2][1]".
for (var i=0; i<threads.length; i++) {
var msgs = threads[i].getMessages();
for (var j=0; j<msgs.length; j++) {
var from = msgs[j].getFrom();
var msgDate = msgs[j].getDate();
var msgTime = (new Date(msgDate)).getTime();
var diff1 = msgTime - cutOff;
// New code
if (from === settings[2][1]) {
continue;
}

how to collect data from user with the facebook messenger bot api in node js

I am building a messenger bot in node. I want it to collect user input data and have a conversation or ask questions, but the code I have doesn't work. the part that does not work is it only continues to the next else if block if i type the same code. and second the array is not capturing the text after the first if statement. Is there a better way to do it? Could someone provide code?
My code is below. what i want is like in this iimage:
var currentbot = 0;
var awnswers = [];
app.post('/webhook', function(req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
var text = event.message.text;
if (text == "hi") {
start(event.message.text, event.sender.id);
}
}
}
res.sendStatus(200);
});
var awnswers = [];
function start(text, id) {
if (count == 0) {
sendTextMessage('hello lets order!', id);
arr.push(text);
console.log(awnswers);
count = 1;
} else if (count == 1) {
sendTextMessage('what size do you want?', id);
arr.push(text);
console.log(awnswers);
count = 2;
} else if (count == 2) {
sendTextMessage('its on its way!', id);
arr.push(text);
console.log(awnswers);
count = 0;
}
}
function sendTextMessage(messageText, recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: process.env.access_token
},
method: 'POST',
json: messageData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
The main issues I think I see are:
Start() is only called when text == hi
Count is not defined
You're pushing to the array 'arr' not, awnswers
You can fix these by:
Calling start() on every message
Defining count like var count = 0; at the top of your file, next to var currentbot
awnswers.push(text);

Email a reminder based on the status of a cell Google apps script

I am attempting to set a simple reminder email to a technician to remind when a routine service is due. I have a 2d array and code that works, but it only sends 1 email, which is the lowest row.
I'm kinda new to this, but I would like it to run through each row and send a reminder for every overdue.
Any help appreciated.
This is what I have now:
function Email_Reminder()
{;
var sheet = SpreadsheetApp.getActiveSheet();
statusArray = sheet.getDataRange().getValues();
status = "overdue";
for (i=3;i < statusArray.length;i++){
if (status == statusArray[i][6]) {
var customer = statusArray[i][0];
}
}
var email = "djens12#gmail.com"
var subject = "Reminder";
var body = "This is a reminder that the service is overdue for " +customer+ "";
MailApp.sendEmail(email,subject,body,{NoReply : true});
}
thanks
Just move your MailApp.sendEmail() inside your for loop
function Email_Reminder()
{;
var sheet = SpreadsheetApp.getActiveSheet();
statusArray = sheet.getDataRange().getValues();
status = "overdue";
var email = "djens12#gmail.com"
var subject = "Reminder";
for (i=3;i < statusArray.length;i++){
if (status == statusArray[i][6]) {
var customer = statusArray[i][0];
var body = "This is a reminder that the service is overdue for " +customer+ "";
MailApp.sendEmail(email,subject,body,{NoReply : true});
}
}
}