I want to get all the flights of the airline_name and destination entred, but I get all flights of all airlines and all destinations not of the specified entries. What should I change in the code so it can work?
function get_flights_by_airline_destination(airline_name, destination, callback) {
let request = require('request');
let url = 'http://api.aviationstack.com/v1/flights?access_key=xxxx&flight_status=scheduled'
request(url, function (err, response, body) {
if (err) {
console.log('error:', error);
callback(err);
} else {
let vol = JSON.parse(body)
result= []
num = vol.pagination.limit
for (let i = 0; i < 10; i++) {
arrival = vol.data[i].arrival.timezone
airline=vol.data[i].airline.name
if ((destination == arrival)&&(airline_name == airline)) {
one_flight = {number: vol.data[i].flight.number, date: vol.data[i].flight_date, departure: vol.data[i].departure.timezone, arrival: vol.data[i].arrival.timezone, from: vol.data[i].departure.airport, to: vol.data[i].arrival.airport, airline: vol.data[i].airline.name}
result.push(one_flight)
}
}
callback(null, result)
}
});
}
function get_flights( req, res) {
get_flights_by_airline_destination( 'air france','europe/rome' ,function( err, result) {
if ( err) {
console.log("error")
}
else {
var links = []
result.map( ( result) => {
links.push(
'from '+' '+result["departure"]+' '+ 'to'+' '+result["arrival"]+' '+'on'+' '+result["airline"],
)
})
console.log(links)
}
})
}
get_flights()
I have a list of 80 items and I get 10 item on each page.Now my idea is to write all the data into file in such a way that first 10 will be in one file and then next 10 in another and so on i get 8 pages for my 80 blogs of 10 in each page.The problem is I am getting only one file got written with 10 blogs what about the else.Can anyone please find the error.Thanks.For that I wrote the script as follows,
I find that the loop is not getting incremented.
exports.getBlogsTest = function(req, res) {
helper.logs('getBlogs', 'blog');
var pages = ['undefined', '2', '3', '4', '5', '6', '7', '8'],
pageNum = '';
pages.forEach(function(i, v) {
try {
var currentPage = Number(i);
var itemsPerPage = 10;
var startItem = (currentPage - 1) * itemsPerPage;
async.waterfall([
function(done) {
try {
if (currentPage === 1) {
blogs.count().exec(function(err, count) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
throw err;
} else {
done(err, count);
}
});
} else {
done('', 'page');
}
} catch (e) {
helper.logs('getBlogs', 'blog', e.message);
}
},
function(count, done) {
try {
if (count) {
if (count && count !== 'page') {
res.setHeader('totalItems', count);
}
blogs.find().sort({ date: -1 }).select('-text').skip(startItem).limit(itemsPerPage).exec(function(err, data) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
throw err;
}
if (data && data.length > 0) {
res.send(data);
console.log('reached###################')
if (i === 'undefined') {
pageNum = '';
} else {
pageNum = i;
}
var fileName = 'public/amp/test2/amp-blog-list' + pageNum + '.html';
var modData = data;
fs.writeFile(fileName, modData, function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
} else {
res.send([]);
}
});
} else {
res.send([]);
}
} catch (e) {
helper.logs('getBlogs', 'blog', e.message);
}
}
],
function(err) {
helper.logs('getBlogs', 'blog', err, 'console');
throw err;
});
} catch (e) {
helper.logs('getBlogs', 'blog', e.message);
}
})
};
Why are you using so many try catch?
While it might be useful in many cases you should avoid using it when not necessary.
A few points where you had an issues:
var currentPage = Number(i);
when i is 'undefined' currentPage === NaN
same for var startItem = (currentPage - 1) * itemsPerPage;
when currentPage is 'NaN' startItem === NaN
What i guess is that you thought the params in forEach are (index, value) but it's the other way round (value, index)
I tried to improve your code a bit but haven't actualy run it.
exports.getBlogsTest = function(req, res) {
helper.logs('getBlogs', 'blog');
var itemsPerPage = 10;
for (var i = 1; i < 11; i++) { // pages 1-10
(function(currentPage){ // currentPage = i
var startItem = (currentPage - 1) * itemsPerPage;
async.waterfall([
function(done) {
if (currentPage === 1) {
blogs.count().exec(function(err, count) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
//throw err;
done(err); // the done callback will be called with the error
} else {
done(null, count); // no error so send null
}
});
} else {
done(null, 'page'); // no error so send null
}
},
function(count, done) {
if (count) {
if (count !== 'page') {
res.setHeader('totalItems', count);
}
blogs.find().sort({ date: -1 }).select('-text').skip(startItem).limit(itemsPerPage).exec(function(err, data) {
if (err) {
helper.logs('getBlogs', 'blog', err, 'console');
done(err); // you never called done
//throw err;
}
if (data && data.length > 0) {
res.send(data);
var fileName = 'public/amp/test2/amp-blog-list' + (currentPage === 1 ? '' : currentPage) + '.html';
var modData = data;
fs.writeFile(fileName, modData, function(err) {
if (err) {
done(err);
return console.log(err);
}
console.log("The file was saved!");
done(); // you never called done
});
} else {
res.send([]);
done(); // you never called done
}
});
} else {
res.send([]);
done(); // you never called done
}
}
], function done(err) {
// this is called when waterfall is done or in case of error
// it would always throw if you didn't check for error
// also is it necessary to throw?
// if (err) throw err;
helper.logs('getBlogs', 'blog', err, 'console');
});
})(i);
}
};
I m doing a javascript function using mongoose to find a group which contains a list of users emails, that part works perfectly. After I want to find each user of the list and add the new group name instead of the old group name, I don't know why, but it doesn't work, the function returns me the group before doing the for loop, and the users are not modified.
Here is my user model :
var userSchema = mongoose.Schema({
local : {
email : String,
password : String,
}
groups : { type: [String], default: []}
});
And here my Group model :
var groupSchema = mongoose.Schema({
title : String,
creator : String,
listOfUsers : { type: [String], default: []}
});
And here my function :
Group.findOne({ '_id': groupId}, function (error, group){
var oldTitle = group.title;
group.title = req.body.title;
group.save();
if(error){
throw (error)
}
for(var i = 0; i < group.listOfUsers.length;i++){
User.findOne({'local.email': group.listOfUsers[i]}, function(error,user){
if(error){
throw (error)
}
for(var j=0;j<user.groups.length;j++){
if(user.groups[j] == oldTitle){
user.groups[j] = group.title;
user.save();
}
}
});
}
return res.json(group);
you can use async to fix the callback problem
async.waterfall(
[
function (callback) {
Group.findOne({
'_id': groupId
}, function (error, group) {
if (error) {
throw (error)
} else {
callback(null, group);
}
})
},
function (group, callback) {
for (var i = 0; i < group.listOfUsers.length; i++) {
User.findOne({
'local.email': group.listOfUsers[i]
}, function (error, user) {
if (error) {
throw (error)
} else {
callback(null, user, group);
}
});
}
},
function (user, group, callback) {
var oldTitle = group.title;
group.title = req.body.title;
for (var j = 0; j < user.groups.length; j++) {
if (user.groups[j] == oldTitle) {
user.groups[j] = group.title;
user.save();
}
}
callback(null, 'done');
}
],
function (err, result) {
console.info("4");
console.info(err);
console.info(result);
});
forgive me if i made any mistake, it is always hard to write code without data, i hope you will understand how i wanted to solve.
and don't forget
var async = require('async');
at the beginning
You should do user.save() only after for loop is finished. I updated for loops with forEach which I feel more comfortable to use.
Group.findbyId(groupId, function(err, group) {
var oldTitle = group.title;
group.title = req.body.title;
if (group.save()) {
listOfUsers.forEach(function(groupUser) {
User.findOne({'local.email' : groupUser}, function (err, user) {
if(user) {
user.group.forEach(function(userGroup) {
if (userGroup == oldTitle) {
userGroup = group.title;
}
})
user.save();
}
});
});
res.json(group);
} else {
res.status(400).json({messsage: 'Error while saving group!'});
}
});
I'm trying to code a steam trade bot that accept trade offers automatically. I can decline login via trade bot and decline trade offers but when it should accept trade offer automatically it doesn't. I get this error insted of accepting offers;
/var/node_modules/mysql/lib/protocol/Parser.js:82
throw err;
^
ReferenceError: item is not defined
at Query._callback (/var/tradebot.js:419:18)
at Query.Sequence.end (/var/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at Query._handleFinalResultPacket (/var/node_modules/mysql/lib/protocol/sequences/Query.js:144:8)
at Query.EofPacket (/var/node_modules/mysql/lib/protocol/sequences/Query.js:128:8)
at Protocol._parsePacket (/var/node_modules/mysql/lib/protocol/Protocol.js:271:23)
at Parser.write (/var/node_modules/mysql/lib/protocol/Parser.js:77:12)
at Protocol.write (/var/node_modules/mysql/lib/protocol/Protocol.js:39:16)
at Socket.<anonymous> (/var/node_modules/mysql/lib/Connection.js:96:28)
at Socket.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:163:16)
My tradebot.js source code;
var admin = 'xxx';
var logOnOptions = {
accountName: 'xxxx,
password: 'xxxx'
};
var GameTime = 120;
////
var authCode = '98Y39';
var globalSessionID;
if (require('fs').existsSync('sentry_'+logOnOptions['accountName']+'.hash')) {
logOnOptions['shaSentryfile'] = require('fs').readFileSync('sentry_'+logOnOptions['accountName']+'.hash');
} else if (authCode != '') {
logOnOptions['authCode'] = authCode;
}
var sitename;
sitename = "csgowin.net";
var Steam = require('steam');
var SteamTradeOffers = require('steam-tradeoffers');
var mysql = require('mysql');
var request = require("request");
var steamuserinfo = require('steam-userinfo');
steamuserinfo.setup("5EA5FFD1E19CD74C2E8F736BB9CFF152");
var mysqlInfo;
mysqlInfo = {
host : 'localhost',
user : 'xxx',
password : 'xx',
database : 'xxx',
charset : 'utf8_general_ci'
};
var mysqlConnection = mysql.createConnection(mysqlInfo);
var steam = new Steam.SteamClient();
var offers = new SteamTradeOffers();
var recheck = true;
steam.logOn(logOnOptions);
steam.on('debug', console.log);
function getUserName(steamid) {
steamuserinfo.getUserInfo(steamid, function(error, data){
if(error) throw error;
var datadec = JSON.parse(JSON.stringify(data.response));
return (datadec.players[0].personaname);
});
}
function proceedWinners() {
var url = 'http://'+sitename+'/getwinner34634f.php';
request(url, function(error, response, body){});
}
var locked=false,proceeded;
var itemscopy;
var detected=false;
var detected2=false;
function CheckTimer() {
if(locked == true) return;
locked = true;
if(recheck == true) {
recheck = false;
checkoffers(1000);
}
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, rows, fields) {
if(err) return;
mysqlConnection.query('SELECT `starttime` FROM `games` WHERE `id`=\''+rows[0].value+'\'', function(errs, rowss, fieldss) {
if(errs) return;
var timeleft;
if(rowss[0].starttime == 2147483647) timeleft = GameTime;
else {
var unixtime = Math.round(new Date().getTime()/1000.0);
timeleft = rowss[0].starttime+GameTime-unixtime;
if(timeleft < 0) timeleft = 0;
}
if(timeleft == 0) {
if(proceeded == true) return;
proceedWinners();
proceeded = true;
} else proceeded = false;
});
});
detected2 = false;
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, itemx) {
if(err) {
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: globalSessionID,
webCookie: newCookie
}, function(err) {
if (err) {
}
});
});
return;
}
if(detected2 == true) {
return;
}
detected2 = true;
itemscopy = itemx;
detected = false;
mysqlConnection.query('SELECT * FROM `queue` WHERE `status`=\'active\'', function(err, row, fields) {
if(err) {
return;
}
if(detected == true) {
return;
}
detected = true;
for(var i=0; i < row.length; i++) {
var gameid = row[i].id;
mysqlConnection.query('UPDATE `queue` SET `status`=\'sent\' WHERE `id`=\''+gameid+'\'', function(err, row, fields) {});
var sendItems = (row[i].items).split('/');
var item=[],num=0;
for (var x = 0; x < itemscopy.length; x++) {
for(var j=0; j < sendItems.length; j++) {
if (itemscopy[x].tradable && (itemscopy[x].market_name).indexOf(sendItems[j]) == 0) {
sendItems[j] = "xxx";
item[num] = {
appid: 730,
contextid: 2,
amount: itemscopy[x].amount,
assetid: itemscopy[x].id
}
num++;
}
}
}
if (num > 0) {
var gamenum = row[i].id;
offers.makeOffer ({
partnerSteamId: row[i].userid,
itemsFromMe: item,
accessToken: row[i].token,
itemsFromThem: [],
message: 'Ваш выигрыш на сайте '+sitename+' в игре #'+gamenum
}, function(err, response){
if (err) {
return;
}
console.log('Trade offer for queue '+gamenum+' sent!');
});
}
}
});
});
setTimeout(function(){locked = false;},100000);
}
steam.on('loggedOn', function(result) {
console.log('Logged in!');
steam.setPersonaState(Steam.EPersonaState.LookingToTrade);
steam.addFriend("xxx");
steam.sendMessage(admin,"Я включился!");
});
steam.on('webSessionID', function(sessionID) {
globalSessionID = sessionID;
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: sessionID,
webCookie: newCookie
}, function(err) {
if (err) {
throw err;
}
setInterval(CheckTimer,1000);
});
});
});
steam.on('friendMsg', function(steamID, message, type) {
if(type != Steam.EChatEntryType.ChatMsg) return;
if(steamID == admin) {
if(message.indexOf("/sendallitems") == 0) {
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, items) {
if(err) {
steam.sendMessage(steamID, 'Не могу загрузить свой инвентарь, попробуй ещё раз');
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: globalSessionID,
webCookie: newCookie
}, function(err) {
if (err) {
}
});
});
return;
}
var item=[],num=0;
for (var i = 0; i < items.length; i++) {
if (items[i].tradable) {
item[num] = {
appid: 730,
contextid: 2,
amount: items[i].amount,
assetid: items[i].id
}
num++;
}
}
if (num > 0) {
offers.makeOffer ({
partnerSteamId: steamID,
itemsFromMe: item,
itemsFromThem: [],
message: ''
}, function(err, response){
if (err) {
throw err;
}
steam.sendMessage(steamID, 'Обмен отправлен!');
});
}
});
} else if(message.indexOf("/send") == 0) {
var params = message.split(' ');
if(params.length == 1) return steam.sendMessage(steamID, 'Формат: /send [название предмета]');
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, items) {
if(err) {
steam.sendMessage(steamID, 'Не могу загрузить свой инвентарь, попробуй ещё раз');
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: globalSessionID,
webCookie: newCookie
}, function(err) {
if (err) {
}
});
});
return;
}
var item=0;
for (var i = 0; i < items.length; i++) {
if((items[i].market_name).indexOf(params[1]) != -1) {
item = items[i].id;
break;
}
}
if (item != 0) {
offers.makeOffer ({
partnerSteamId: steamID,
itemsFromMe: [
{
appid: 730,
contextid: 2,
amount: 1,
assetid: item
}
],
itemsFromThem: [],
message: ''
}, function(err, response){
if (err) {
throw err;
}
steam.sendMessage(steamID, 'Обмен отправлен!');
});
}
});
} else if(message.indexOf("/show") == 0) {
var params = message.split(' ');
offers.loadMyInventory({
appId: 730,
contextId: 2
}, function(err, items) {
if(err) {
steam.sendMessage(steamID, 'Не могу загрузить свой инвентарь, попробуй ещё раз');
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: globalSessionID,
webCookie: newCookie
}, function(err) {
if (err) {
}
});
});
return;
}
steam.sendMessage(steamID,'Смотри: ');
for (var i = 0; i < items.length; i++) {
steam.sendMessage(steamID,'http://steamcommunity.com/id/xxx/inventory/'+items[i].appid+'_'+items[i].contextid+'_'+items[i].id);
}
});
}
}
steamuserinfo.getUserInfo(steamID, function(error, data){
if(error) throw error;
var datadec = JSON.parse(JSON.stringify(data.response));
var name = datadec.players[0].personaname;
console.log(name + ': ' + message); // Log it
});
//steam.sendMessage(steamID, 'I\'m a bot that accepts all your unwanted items. If you would like to grab a few crates from me, please request a trade.');
});
function checkoffers(number) {
if (number > 0) {
offers.getOffers({
get_received_offers: 1,
active_only: 1,
get_sent_offers: 0,
get_descriptions: 1,
language: "en_us"
}, function(error, body) {
if(error) return;
if(body.response.trade_offers_received){
body.response.trade_offers_received.forEach(function(offer) {
if (offer.trade_offer_state == 2){
if(offer.items_to_give) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
return;
}
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'maxitems\'', function(err, row, fields) {
if(offer.items_to_receive.length > row[0].value) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
offer.items_to_receive = [];
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'toomuch\',\'System\')', function(err, row, fields) {});
return;
}
});
offers.loadPartnerInventory({partnerSteamId: offer.steamid_other, appId: 730, contextId: 2, tradeOfferId: offer.tradeofferid, language: "en"}, function(err, hitems) {
if(err) {
steam.webLogOn(function(newCookie) {
offers.setup({
sessionID: globalSessionID,
webCookie: newCookie
}, function(err) {
if (err) {
}
});
});
recheck = true;
return;
}
var items = offer.items_to_receive;
var wgg=[],num=0;
for (var i = 0; i < items.length; i++) {
for(var j=0; j < hitems.length; j++) {
if(items[i].assetid == hitems[j].id) {
wgg[num] = hitems[j];
num++;
break;
}
}
}
var price=[];
for(var i=0; i < num; i++) {
if(wgg[i].appid != 730) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'onlycsgo\',\'System\')', function(err, row, fields) {});
return;
}
if(wgg[i].market_name.indexOf("Souvenir") != -1) {
offers.declineOffer({tradeOfferId: offer.tradeofferid});
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'souvenir\',\'System\')', function(err, row, fields) {});
return;
}
var itemname = wgg[i].market_name;
var url = 'http://'+sitename+'/cost.php?item='+encodeURIComponent(itemname);
(function(someshit) {
request(url, function(error, response, body){
if(!error && response.statusCode === 200){
if(body == "notfound") { offers.declineOffer({tradeOfferId: offer.tradeofferid}); mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'notavailable\',\'System\')', function(err, row, fields) {}); }
else {
wgg[someshit].cost = parseFloat(body);
}
} else offers.declineOffer({tradeOfferId: offer.tradeofferid});
});})(i)
}
setTimeout(function() {
var sum=0;
for(var i=0; i < num; i++) {
sum += wgg[i].cost;
}
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'minbet\'', function(err, row, fields) {
if(sum < row[0].value) {
num = 0;
offers.declineOffer({tradeOfferId: offer.tradeofferid});
mysqlConnection.query('INSERT INTO `messages` (`userid`,`msg`,`from`) VALUES (\''+offer.steamid_other+'\',\'toosmall!\',\'System\')', function(err, row, fields) {});
return;
}
});
steamuserinfo.getUserInfo(offer.steamid_other, function(error, data){
if(error) throw error;
var datadec = JSON.parse(JSON.stringify(data.response));
var name = datadec.players[0].personaname;
var avatar = datadec.players[0].avatarfull;
if(num == 0) return;
mysqlConnection.query('SELECT `value` FROM `info` WHERE `name`=\'current_game\'', function(err, row, fields) {
var current_game = (row[0].value);
mysqlConnection.query('SELECT `cost`,`itemsnum` FROM `games` WHERE `id`=\''+current_game+'\'', function(err, row, fields) {
var current_bank = parseFloat(row[0].cost);
var itemsnum = row[0].itemsnum;
if(item.length > 0) {
mysqlConnection.query('UPDATE `games` SET `starttime`=UNIX_TIMESTAMP() WHERE `id` = \'' + current_game + '\'', function(err, row, fields) {});
}
for(var j=0; j < num; j++) {
mysqlConnection.query('INSERT INTO `game' + current_game + '` (`userid`,`username`,`item`,`color`,`value`,`avatar`,`image`,`from`,`to`) VALUES (\'' + offer.steamid_other + '\',\'' + name + '\',\'' + wgg[j].market_name + '\',\'' + wgg[j].name_color + '\',\'' + wgg[j].cost + '\',\'' + avatar + '\',\'' + wgg[j].icon_url + '\',\''+current_bank+'\'+\'0\',\''+current_bank+'\'+\''+wgg[j].cost+'\')', function(err, row, fields) {});
mysqlConnection.query('UPDATE `games` SET `itemsnum`=`itemsnum`+1, `cost`=`cost`+\''+wgg[j].cost+'\' WHERE `id` = \'' + current_game + '\'', function(err, row, fields) {});
current_bank = parseFloat(current_bank + wgg[j].cost);
itemsnum++;
}
if(itemsnum > 50) {
proceedWinners();
}
offers.acceptOffer({tradeOfferId: offer.tradeofferid});
console.log('Accepted trade offer #'+offer.tradeofferid+' by '+name+' ('+offer.steamid_other+')');
});
});
});
},3000);
});
}
});
}
});
}
}
var pew;
steam.on('tradeOffers', checkoffers);
steam.on('sentry', function(data) {
require('fs').writeFileSync('sentry_'+logOnOptions['accountName']+'.hash', data);
});
Thank you.
As stated in the message, the error is on line 419 in the statement:
if(item.length > 0) {
mysqlConnection.query('UPDATE `games` SET `starttime`=UNIX_TIMESTAMP() WHERE `id` = \'' + current_game + '\'', function(err, row, fields) {});
}
item is not defined. Perhaps you meant row?
I'm working with the exact same code as you.
Here was my solution for when I came across that error:
I replaced:
if(item.length > 0)
with if(itemsnum > 0)
However I came across a few other errors after that, and maybe you have too.
Could we exchange steam information so we can iron out all of the bugs in this code together?