Node JS Discord Log guildMemberUpdate - node.js

I have tried various things and there are no errors but my bot has no response I tried to change my nickname, avatar, etc. there is no response here I am using node js please help me following my sample code. but when I attempt to carry it over to role adding and deletion, usernames, nicknames, and avatar changes, the bot fails to log this and crashes. How do I fix this issue within my code?
//declare changes
var Changes = {
unknown: 0,
addedRole: 1,
removedRole: 2,
username: 3,
nickname: 4,
avatar: 5
};
var change = Changes.unknown;
//check if roles were removed
var removedRole = '';
oldMember.roles.every(function(value) {
if(newMember.roles.find('id', value.id) == null) {
change = Changes.removedRole;
removedRole = value.name;
}
});
//check if roles were added
var addedRole = '';
newMember.roles.every(function(value) {
if(oldMember.roles.find('id', value.id) == null) {
change = Changes.addedRole;
addedRole = value.name;
}
});
//check if username changed
if(newMember.user.username != oldMember.user.username)
change = Changes.username;
//check if nickname changed
if(newMember.nickname != oldMember.nickname)
change = Changes.nickname;
//check if avatar changed
if(newMember.user.displayAvatarURL != oldMember.user.displayAvatarURL)
change = Changes.avatar;
//post in the guild's log channel
var log = newMember.guild.channels.cache.get("channelID")
if (log != null) {
switch(change) {
case Changes.unknown:
log.send('**[User Update]** ' + newMember);
break;
case Changes.addedRole:
log.send('**[User Role Added]** ' + newMember + ': ' + addedRole);
break;
case Changes.removedRole:
log.send('**[User Role Removed]** ' + newMember + ': ' + removedRole);
break;
case Changes.username:
log.send('**[User Username Changed]** ' + newMember + ': Username changed from ' +
oldMember.user.username + '#' + oldMember.user.discriminator + ' to ' +
newMember.user.username + '#' + newMember.user.discriminator);
break;
case Changes.nickname:
log.send('**[User Nickname Changed]** ' + newMember + ': ' +
(oldMember.nickname != null ? 'Changed nickname from ' + oldMember.nickname +
+ newMember.nickname : 'Set nickname') + ' to ' +
(newMember.nickname != null ? newMember.nickname + '.' : 'original username.'));
break;
case Changes.avatar:
log.send('**[User Avatar Changed]** ' + newMember);
break;
}
}
})

Related

App doesn't broadcast when wakeLocks added

I have a geoLocation app for a Firefox OS device (ZTE Open v1.1), that broadcasts to a web server its location details.
However, my code doesn't run if I minimise the app and turn the screen off.
I thought adding the following requestWakeLocks to the code would sort the problem, but it doesn't seem to help:
var lock = window.navigator.requestWakeLock('gps');
var lock = window.navigator.requestWakeLock('wifi');
Do you have any idea what I am doing wrong?
Code:
function init() {
document.addEventListener("DOMContentLoaded", watchPosition, false); // to test on web browser
//document.addEventListener("deviceready", watchPosition, false); // deviceready is a cordova event
}
/* ---------------------------------- Local Variables ---------------------------------- */
var checkPeriodically;
var watchPositionOutput = document.getElementById('watchPositionOutput');
var ajaxVars; // HTTP POST data values
/* ---------------------------------- Local Functions ---------------------------------- */
function watchPosition() {
var lock = window.navigator.requestWakeLock('gps'); // FireFox-OS only - keeps the gps active when screen is off
var lock = window.navigator.requestWakeLock('wifi');
checkPeriodically = setInterval(checkTime, 10000);
var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);
var options = {
enableHighAccuracy: true,
}
function onSuccess(position) {
ajaxVars =
"lt=" + position.coords.latitude +
"&lg=" + position.coords.longitude +
"&ac=" + position.coords.accuracy +
"&sp=" + position.coords.speed +
"&ts=" + position.timestamp +
"&sec=SEC_TOKEN";
var dt = new Date(position.timestamp);
date_time =
dt.getFullYear() + '-' +
(dt.getMonth() + 1) + '-' +
dt.getDate() + ' ' +
dt.getHours() + ':' +
dt.getMinutes() + ':' +
dt.getSeconds();
watchPositionOutput.innerHTML =
'Latitude: ' + position.coords.latitude + '<br>' +
'Longitude: ' + position.coords.longitude + '<br>' +
'Accuracy: ' + position.coords.accuracy + '<br>' +
'Speed: ' + position.coords.speed + '<br>' +
'Timestamp: ' + date_time + '<br>';
}
function onError(error) {
watchPositionOutput.innerHTML = 'code: ' + error.code + '<br>' +'message: ' + error.message + '<br>';
}
}
// update the server with location data
function ajax_post(postData){
// when there is no data in postData
if (typeof(postData) === 'undefined') { return false; } // exit the function
var req = new XMLHttpRequest(); // Create XMLHttpRequest object
var url = "http://example.com/locate-me/post.php";
//var url = "http://localhost/locate-me/post.php";
req.open("POST", url, true);
// Set content type header info for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var return_data = req.responseText; // return whatever php echos
var date_time = new Date(return_data * 1000); // php is currently returning the time (timestamp)
document.getElementById("status").innerHTML = "Server time: " + date_time;
}
}
// Send data to PHP, and wait for response to update the status div
req.send(postData); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
// schedule to post the position data to a php script during certain times on certain days
function checkTime(){
// for example a day (day 0 == Sun) between 06:00 abd 23:45
var d = new Date();
var today = d.getDay();
var hms = d.getHours()+":"+d.getMinutes();
// mon - thurs
if( (today === 1 || today === 2 || today === 3 || today === 4) && hms > "10:23" && hms < "15:40") {
ajax_post(ajaxVars);
}
// friday
else if( today === 5 && hms > "13:00" && hms < "13:40") {
ajax_post(ajaxVars);
}
// testing: run all the time
else if( today < 7 ) {
ajax_post(ajaxVars);
}
else {
document.getElementById("status").innerHTML = "Data not scheduled to be posted to the server yet";
}
}
init();
Have you tried?
navigator.requestWakeLock('cpu');
If that still does not work, maybe you should follow the discussion in:
Firefox OS Background services

* Suitescript 2.0 * How can update the status of a custom record from Map Reduce script?

So all i want to do is if the m/r script fails, update the corresponding dropdown value on custom record from m/r script.
How to do this in SuiteScript 2.0
You can use the summary step to get the errors that occurred in your Map Reduce script. The following code should help you achieve this:
function summarize(summary) {
handleErrors(summary);
handleSummaryOutput(summary.output);
//*********** HELPER FUNCTIONS ***********
function handleErrors(summary) {
var errorsArray = getErrorsArray(summary);
if(!errorsArray || !errorsArray.length){
log.debug('No errors encountered');
return;
}
for (var i in errorsArray) {
log.error('Error ' + i, errorsArray[i]);
}
if(errorsArray && errorsArray.length){
//
//INSERT YOUR CODE HERE
//
}
return errorsArray;
//*********** HELPER FUNCTIONS ***********
function getErrorsArray(summary){
var errorsArray = [];
if (summary.inputSummary.error){
log.audit('Input Error', summary.inputSummary.error);
errorsArray.push('Input Error | MSG: ' + summary.inputSummary.error);
}
summary.mapSummary.errors.iterator().each(function (key, e){
var errorString = getErrorString(e);
log.audit('Map Error', 'KEY: ' + key + ' | ERROR: ' + errorString);
errorsArray.push('Map Error | KEY: ' + key + ' | ERROR: ' + errorString);
return true; //Must return true to keep looping
});
summary.reduceSummary.errors.iterator().each(function (key, e){
var errorString = getErrorString(e);
log.audit('Reduce Error', 'KEY: ' + key + ' | MSG: ' + errorString);
errorsArray.push('Reduce Error | KEY: ' + key + ' | MSG: ' + errorString);
return true; //Must return true to keep looping
});
return errorsArray;
//*********** HELPER FUNCTIONS ***********
function getErrorString(e){
var errorString = '';
var errorObj = JSON.parse(e);
if (errorObj.type == 'error.SuiteScriptError' || errorObj.type == 'error.UserEventError'){
errorString = errorObj.name + ': ' + errorObj.message;
} else {
errorString = e;
}
return errorString;
}
}
}
function handleSummaryOutput(output){
var contents = '';
output.iterator().each(function (key, value){
contents += (key + ' ' + value + '\n');
return true;
});
if(contents){
log.debug('output', contents);
}
}
}

MSCRM 4.0 : Getting Error when saving and clicking on the Item in the field value after auto populating look up though Javascript

I am getting an error after auto populating a Look-UP though javascript. My code is below. It is working and I am able to autopopulate. But when I click on the autopopulated filed I am getting an error. Also an error while saving the record.Errors are :
1) 'ryan_leadengagementprincipalassignment with id = ******* does not exist' (When I click on the populated Lookup value)
2) The requested record is not found or you do not have sufficient privilege to view it. (While saving the record)
Code:
var LEPAccountLookup= crmForm.all.customerid.DataValue;
if (LEPAccountLookup!= null && LEPAccountLookup!= 'undefined')
{
var LEPAccountID= LEPAccountLookup[0].id;
var LEPAccountxml = '' +
'<?xml version=\'1.0\' encoding=\'utf-8\'?>' +
'<soap:Envelope xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'>' +
GenerateAuthenticationHeader() +
' <soap:Body>' +
' <RetrieveMultiple xmlns=\'http://schemas.microsoft.com/crm/2007/WebServices\'>' +
' <query xmlns:q1=\'http://schemas.microsoft.com/crm/2006/Query\' xsi:type=\'q1:QueryExpression\'>' +
' <q1:EntityName>ryan_leadengagementprincipalassignment</q1:EntityName>' +
' <q1:ColumnSet xsi:type=\'q1:AllColumns\' />' +
' <q1:Distinct>false</q1:Distinct>' +
' <q1:Criteria>' +
' <q1:FilterOperator>And</q1:FilterOperator>' +
' <q1:Conditions>' +
' <q1:Condition>' +
' <q1:AttributeName>ryan_accountnameid</q1:AttributeName>' +
' <q1:Operator>Like</q1:Operator>' +
' <q1:Values>' +
' <q1:Value xsi:type=\'xsd:string\'>' + LEPAccountID + '</q1:Value>' +
' </q1:Values>' +
' </q1:Condition>' +
' </q1:Conditions>' +
' </q1:Criteria>' +
' </query>' +
' </RetrieveMultiple>' +
' </soap:Body>' +
'</soap:Envelope>' +
'';
//alert(LEPAccountxml);
var xmlHttpRequest = new ActiveXObject('Msxml2.XMLHTTP');
xmlHttpRequest.Open('POST', '/mscrmservices/2007/CrmService.asmx', false);
xmlHttpRequest.setRequestHeader('SOAPAction','http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple');
xmlHttpRequest.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xmlHttpRequest.setRequestHeader('Content-Length', LEPAccountxml.length);
xmlHttpRequest.send(LEPAccountxml);
var resultLEPAccountxml = xmlHttpRequest.responseXML;
//alert(resultLEPAccountxml);
//----------------------------------------------------------------------------------------------------------------------
var entityNodes = resultLEPAccountxml.selectNodes('//RetrieveMultipleResult/BusinessEntities/BusinessEntity');
for (var i = 0; i < entityNodes.length; i++) {
var entityNode = entityNodes[i];
var LEPAccountNode = entityNode.selectSingleNode("q1:ryan_accountnameid");
var LEPAccountNodename = entityNode.selectSingleNode('./q1:ryan_accountnameid/#name');
var LEPParentPracAreaNode = entityNode.selectSingleNode("q1:ryan_parentpracticeareaid");
var LEPParentPracAreaNodename = entityNode.selectSingleNode('./q1:ryan_parentpracticeareaid/#name');
var LEPPracAreaNode = entityNode.selectSingleNode("q1:ryan_practiceareaid");
var LEPPracAreaNodename = entityNode.selectSingleNode('./q1:ryan_practiceareaid/#name');
var LEPLegalEntityNode= entityNode.selectSingleNode("q1:ryan_legalid");
var LEPLegalEntityNodename = entityNode.selectSingleNode('./q1:ryan_legalid/#name');
var LEPNode= entityNode.selectSingleNode("q1:ryan_leadengagementid");
var LEPNodename = entityNode.selectSingleNode('./q1:ryan_leadengagementid/#name')
var LEPAccountid= (LEPAccountNode == null) ? null : LEPAccountNode.text;
var LEPAccountname= (LEPAccountNodename == null) ? null : LEPAccountNodename.text;
var LEPPareantPracAreaid= (LEPParentPracAreaNode == null) ? null : LEPParentPracAreaNode.text;
var LEPPareantPracAreaname= (LEPParentPracAreaNodename == null) ? null : LEPParentPracAreaNodename.text;
var LEPPracAreaid= (LEPPracAreaNode == null) ? null : LEPPracAreaNode.text;
var LEPPracAreaname= (LEPPracAreaNodename == null) ? null : LEPPracAreaNodename.text;
var LEPLegalEntityid= (LEPLegalEntityNode == null) ? null : LEPLegalEntityNode.text;
var LEPLegalEntityname= (LEPLegalEntityNodename == null) ? null : LEPLegalEntityNodename.text;
var LEPEntityid= (LEPNode == null) ? null : LEPNode.text;
var LEPEntityname= (LEPNodename == null) ? null : LEPNodename.text;
//alert(LEPAccountid);
//(LEPAccountname);
var LEPAccount = crmForm.all.customerid.DataValue;
var LEPLE = crmForm.all.ryan_ryanlegalentityid.DataValue;
var LEPPPA = crmForm.all.ryan_parentpracticearea2id.DataValue;
var LEPPA = crmForm.all.ryan_practiceareaid.DataValue;
if((LEPAccount != null) &&(LEPLE != null) && (LEPPPA != null) && (LEPPA != null))
{
if ((LEPAccountid== LEPAccount[0].id) && (LEPLegalEntityid== LEPLE[0].id) && (LEPPareantPracAreaid== LEPPPA[0].id) && (LEPPracAreaid== LEPPA[0].id))
{
var lookup = [];
var lookupValue = new Object();
lookupValue.id = LEPEntityid;
lookupValue.typename = 'ryan_leadengagementprincipalassignment';
lookupValue.name = LEPEntityname;
lookup[0] = lookupValue;
crmForm.all.ryan_leadengagementprincipalid.DataValue = lookup;
crmForm.all.ryan_leadengagementprincipalid.ForceSubmit = true;
}
}
}
}
There is likely something wrong with your SOAP call. When you debug it, does resultLEPAccountXml have an xml response string? or is it just returning an error/empty set? (it appears you were alerting that and have commented it out)
Unfortunately I'm not familiar enough with your particular data model to verify that you are querying for the same table that you are attempting to populate. Is the ryan_leadengagementid field on the ryan_leadengagementprincipalassignment table indeed the correct field to use to set the lookup on whatever form you are executing this script (ie is ryan_leadengagementprincipalid a lookup to the ryan_leadengagementprincipalassignment table)? If you are setting the lookup for the wrong table, then that will cause an issue that looks exactly like this.
Also (as a side note), it appears you are doing a RetrieveMultiple, and looping through and setting the target field multiple times potentially - is this the intended functionality (setting that lookup based on all the leadengagementprincipalassignment results)? The setting of the lookup field looks fine, so I suspect it is the code to retrieve the values which should be used to set the lookup that is the culprit here.

Asterisk 11 active calls event over AMI

Data I would like to have:
Num From , Num To , Duration, Codec, Context, Hold status
ofc in realtime update
I using node.js + nami
what the best way to get this information?
tried use an action Status(), but this gives me not full information about call and if I run it every second browser dies.
here is what I have:
updateCallList();
function updateCallList() {
socket.emit('GET_ACTIVE_CALLS', function(calls) {
$("#callsList").find("tr:gt(0)").remove();
if (calls.response != 'Success') return;
var calls = calls.events;
for (call in calls) {
if (calls[call].privilege == 'Call') {
var callFrom = calls[call].calleridnum + '<' + calls[call].calleridname + '>';
var callTo = calls[call].extension;
var callDuration = calls[call].seconds;
var callRoute = calls[call].context;
var tmpRow = '<tr>';
tmpRow = tmpRow + '<td>' + callFrom + '</td>';
tmpRow = tmpRow + '<td>' + callTo + '</td>';
tmpRow = tmpRow + '<td>' + callDuration + '</td>';
tmpRow = tmpRow + '<td>' + callRoute + '</td>';
tmpRow = tmpRow + '</tr>';
$('#callsList tr:last').after(tmpRow);
}
}
setInterval(function(){
updateCallList();
},1000);
});
}
server side
socket.on('GET_ACTIVE_CALLS', function (callback) {
action = new namiLib.Actions.Status();
nami.send(action, function (response) {
callback(response);
});
});
You need start daemon which will collect NewExten, Link, Unlink, Hangup events and create list of channels.
http://www.voip-info.org/wiki/view/asterisk+manager+events
Also you can do action command with "core show channels" "core show channel XXXXX", but asterisk will die if you do alot of that.
http://www.voip-info.org/wiki/view/Asterisk+Manager+API+Action+Command

how to block nodejs for result of query

I am pretty new to nodejs.
What I want my code to do it to query a database a number of times, collect data from all the queries in one variable and then use it somewhere.
But I guess nodejs instead of waiting for the result of the queries, execute without blocking.
This is what I think is happening. Sorry if I am wrong.
for (var i = step_min; i < (step_max); i += step) {
query = 'select count(' + colName + ') as num_count from ' +
rows[0].tablename + ' where ' + 'dictionaryid=' +
rows[0].dictionaryid + ' and ' + colName + ' between ' + i +
' and ' + (i + step);
connection.query(query, function(err, rows1, fields) {
if (err) {
console.log(err);
throw err;
}
try {
console.log("$$$$$$$$$$$$$$$ pushed : "+ rows1[0].num_count);
contents.push(rows1[0].num_count);
console.log('contents : '+ contents+'\n');
} catch (e) {
if (e instanceof SyntaxError) {
console.log("Syntax Error for input function");
}
}
});
console.log("##################### " + query + "\n");
console.log('contents : '+ contents+'\n');
}
Any advice either on how to block nodejs till the result from query is obtained or otherwise a way to restructure my code ?
Thanks in advance.
You are correct that it is not waiting for your queries before executing. You can look at the node-mysql-queues module which you can use to queue queries, and execute the given callback after all have executed (it will also allow you do perform transactions)
Another (hack) approach is to set a counter of the number of queries you are executing. In the callback of each transaction save the result into your return object and decrement the counter. If it is <= 0 then all your queries have completed, and you can execute your main callback with the return object.
Also, watch out for SQL injection.
try this:
https://github.com/luciotato/waitfor
your code with wait.for:
for (var i = step_min; i < (step_max); i += step) {
query = 'select count(' + colName + ') as num_count from ' +
rows[0].tablename + ' where ' + 'dictionaryid=' +
rows[0].dictionaryid + ' and ' + colName + ' between ' + i +
' and ' + (i + step);
var rows1 = wait.forMethod(connection,"query",query); //waits until callback
console.log("$$$$$$$$$$$$$$$ pushed : "+ rows1[0].num_count);
contents.push(rows1[0].num_count);
}
console.log("##################### " + query + "\n");
console.log('contents : '+ contents+'\n');
} catch (e) {
if (e instanceof SyntaxError) {
console.log("Syntax Error for input function");
}
....
}
Doing something like below could be a work around.
//Its just a test code whatever came to mind first so I'll tune it later...
var contents = [];
var lock = 0;
for (var i = step_min; i < (step_max + step); i += step) {
lock++;
}
for (var i = step_min; i < (step_max + step); i += step) {
query = 'select count(' + colName + ') as num_count from ' + rows[0].tablename + ' where ' + 'dictionaryid=' + rows[0].dictionaryid + ' and ' + colName + ' between ' + i + ' and ' + (i + step);
connection.query(query, function(err, rows1, fields) {
if (err) {
console.log(err);
throw err;
}
try {
console.log("$$$$$$$$$$$$$$$ pushed : " + rows1[0].num_count);
contents.push(rows1[0].num_count);
console.log('contents : ' + contents + '\n');
} catch (e) {
if (e instanceof SyntaxError) {
console.log("Syntax Error for input function");
}
}
lock--;
if (lock == 0) {
queryDone();
}
});
}
function queryDone() {
console.log("##################### " + query + "\n");
console.log('contents : ' + contents + '\n');
var id = obj.exptID + '.' + obj.exptITR + '.' + obj.nodeID + '.' + obj.resourceName + '.' + colName;
serie = {
name: colName,
data: contents,
id: id
};
console.log("--------------------\n " + step_max + "\n" + step_min + "\n------------------------\n");
}
The approach is to fire a function when all queries are done as Nick said...

Resources