Roulette node.js bot "Bot stopped with code null" - javascript

I have problem with my node.js bot to roulette. Bot is fully set up but when I launching it, it gives me error "Bot stopped with code null". Can someone help me to fix it?
Here is the error screenshot: http://i.imgur.com/zfZoMD4.png
Code:
function login(err, sessionID, cookies, steamguard) {
if(err) {
logger.error('Auth error');
logger.debug(err);
if(err.message == "SteamGuardMobile") {
account.twoFactorCode = SteamTotp.generateAuthCode(account.shared_secret);
logger.warn('Error in auth: '+account.twoFactorCode);
setTimeout(function() {
community.login(account, login);
}, 5000);
return;
}
process.exit(0);
}
logger.trace('Sucesfully auth');
account.sessionID = sessionID;
account.cookies = cookies;
community.getWebApiKey('csgobananas.com', webApiKey);
community.startConfirmationChecker(10000, account.identity_secret);
}
function webApiKey(err, key) {
if(err) {
logger.error('Cant make apikey')
logger.debug(err);
process.exit(0);
return;
}
account.key = key;
logger.trace('API key bot '+account.accountName+' '+account.key);
offersSetup();
community.loggedIn(checkLoggedIn);
}
function offersSetup() {
logger.trace('Loaded steam-tradeoffers');
offers.setup({
sessionID: account.sessionID,
webCookie: account.cookies,
APIKey: account.key
});
}
function checkLoggedIn(err, loggedIn, familyView) {
if((err) || (!loggedIn)) {
logger.error('We arent logged in')
process.exit(0);
} else {
logger.trace('Logged in');
account.auth = true;
bot_manager.js code:
var forever = require('forever-monitor');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
database: 'placeholder',
host: 'placeholder',
user: 'placeholder',
password: 'placeholder'
});
query('SELECT * FROM `bots`', function(err, row) {
if((err) || (!row.length)) {
console.log('Failed request or empty bot table');
console.log(err);
return process.exit(0);
}
console.log('List of bots:');
row.forEach(function(itm) {
console.log('Launching bot# '+itm.id);
var bot = new (forever.Monitor)('bot.js', {
args: [itm.id]
});
bot.on('start', function(process, data) {
console.log('Bot with ID '+itm.id+' started');
});
bot.on('exit:code', function(code) {
console.log('Bot stopped with code '+code);
});
bot.on('stdout', function(data) {
console.log(data);
});
bot.start();
});
});
function query(sql, callback) {
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
console.info('Database connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}

Related

Add 'time limit' loop in Javascript to use with imap-simple nodejs package

I currently have the code below, which was created from a previous question I posted last year here.
var imaps = require('imap-simple');
var configBauerEmail = {
imap: {
user: '********#hotmail.com',
password: '******',
host: 'imap-mail.outlook.com',
port: 993,
tls: true,
authTimeout: 30000
}
};
module.exports = {
'delete any existing emails...': function () {
imaps.connect(configBauerEmail).then(function (connection) {
connection.openBox('INBOX').then(function () {
var searchCriteria = ['ALL'];
var fetchOptions = { bodies: ['TEXT'], struct: true
};
return connection.search(searchCriteria, fetchOptions);
})
//Loop over each message
.then(function (messages) {
let taskList = messages.map(function (message) {
return new Promise((res, rej) => {
var parts = imaps.getParts(message.attributes.struct);
parts.map(function (part) {
return connection.getPartData(message, part)
.then(function (partData) {
//Display e-mail body
if (part.disposition == null && part.encoding != "base64") {
console.log(partData);
}
//Mark message for deletion
connection.addFlags(message.attributes.uid, "\Deleted", (err) => {
if (err) {
console.log('Problem marking message for deletion');
rej(err);
}
res();
});
});
});
});
});
return Promise.all(taskList).then(() => {
connection.imap.closeBox(true, (err) => {
if (err) {
console.log(err);
}
});
connection.end();
});
});
});
},
'send email to seller and wait for mailbox notification': function (browser) {
browser.url(browser.launch_url + browser.globals.testDealerBfsAdevertEmailTest);
browser.notificationDismissal();
browser.cmpDismissal();
browser.emailFunctionality.emailTheSeller();
browser.browserEnd();
},
'get new email info': function() {
const createPromise = ms => new Promise((resolve, reject) => {
setTimeout(() => resolve(ms), ms);
});
function findUnseenEmails(connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['UNSEEN'];
var fetchOptions = {
bodies: ['HEADER','TEXT'],
markSeen: false
};
return connection.search(searchCriteria, fetchOptions).then(function (results) {
var subjects = results.map(function (res) {
return res.parts.filter(function (part) {
return part.which === 'HEADER';
})
[0].body.subject[0];
});
console.log(subjects);
if (subjects.length > 0) {
connection.end();
return subjects;
} else {
return createPromise(60000).then(function() {
return findUnseenEmails(connection);
});
}
});
});
}
imaps.connect(configBauerEmail).then(function (connection) {
return findUnseenEmails(connection);
})
.then((subjects) => console.log('finished', subjects));
},
};
This works OK, in that the following loop that was added will loop over every 60 seconds checking that the email has 'arrived' in the mailbox.
if (subjects.length > 0) {
connection.end();
return subjects;
} else {
return createPromise(60000).then(function() {
return findUnseenEmails(connection);
});
}
});
However, at present if the email sending process has failed and the email account does not receive the email, the test will carry on looping continuously until the test is physically stopped.
What I'd now like to do is set some sort of 'time limit' within this loop, so that if the email has not arrived in the mailbox within 30 minutes the test will fail.
I appreciate that this will involve a limit setting in the loop above, but I've tried it in several locations within the loop and I can't get it to work.
Any help would be greatly appreciated. Thanks.

UnhandledPromiseRejectionWarning: Error: Cannot enqueue Handshake after already enqueuing a Handshake

I am trying to create a node.js server that would handle a POST request that would have data into two different MySQL tables.
Here the code behind my node.js server.
let mysql = require("mysql");
const http = require('http');
http.createServer(async function(req, res) {
let con = mysql.createConnection({
host: "...",
user: "...",
password: "...",
database: "..."
});
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
});
if (req.method == 'POST') {
let body = '';
req.on('data', function(data) {
body += data.toString();
if (body.length > 10000000) {
http.request.connection.destroy();
}
});
req.on('end', () => {
if (body) {
let item = JSON.parse(body);
addQuestion(con, item.title).then(function(result){
con.end();
addOptions(con, result.insertId, item.options).then(function(data){
con.end();
res.end(JSON.stringify({
message: "Saved!"
}));
});
});
}
});
return;
}
res.end(JSON.stringify({
message: "OK!"
}));
}).listen(80);
function addQuestion(con, title) {
return new Promise((resolve, reject) => {
con.connect(function(err) {
if (err) return reject(err);
let sql = "INSERT INTO _questions SET ?";
con.query(sql, {title: title}, function(err, result, fields) {
if (err) return reject(err);
return resolve(result);
});
});
});
}
function addOptions(con, questionId, options) {
return new Promise((resolve, reject) => {
con.connect(function(err) {
if (err) return reject(err);
let values = [];
for(let x = 0 ; x < options.length; x++){
let option = options[x];
values.push({
title: option.title,
is_correct: option.isCorrect,
question_id: questionId
});
}
let optionsSql = "INSERT INTO _options (title, is_correct, question_id) VALUES ?";
con.query(questionSql, values, function(err, requestData) {
if (err) return reject(err);
return resolve(result);
});
});
});
}
I am getting the following error
UnhandledPromiseRejectionWarning: Error: Cannot enqueue Handshake
after already enqueuing a Handshake.
How can I solve this issue?
**If you using the node-MySQL module, just remove the .connect and .end. Just solved the problem myself.
**

How to make auth with callback hell?

Create a auth system. When user make a post-query (router.js):
var user = require("../controllers/user");
router.post("/login", function(req, res, next){
user.login(req, function(result) {
res.send(result);
});
File controllers/user.js:
var mongo = require("./mongo");
exports.login = function (req, callback) {
var res;
var login = req.body.login,
password = req.body.password;
var user = new mongo.User({
login: login,
password: password
});
//check if exist user
user.findOne({
login: login
}, function (err, obj) {
if (err) {
console.log("user not found -> save");
user.save(function (err) {
if (err) {
console.log(err);
} else {
callback("OK");
}
});
} else {
console.log("ELSE");
if (password == obj["password"]) {
callback("OK");
}
}
});
}
I want when user.login will finished create/make new user -> call callback with result.
exports.login = function(req, callback){
user.findOne(/...login or sign up new user.../);
callback("Success");
}
So in case when user authorized ->
user.login(req, function(result) {
res.send(result); //this executes
});
How to make this?
The main problem was in syntax, when I tried to find user using user.findOne().
Instead user.findOne() I use mongo.User.findOne():
//mongo.User because I required a mongo.js, where connect to db
// where I had a User model
mongo.User.findOne({ login: login }, function(err, user){
if(err){
reject(err);
} else {
if(user) {
if(password == user["password"]) {
resolve("Login success.");
}
} else {
console.log("new user creating...");
var newUser = new mongo.User({ login: login, password: password });
newUser.save(function(err){
if(err) {
reject(err);
console.log("error with saving");
} else {
resolve("New user created.")
}
})
}
}
});
Also I have used a Promises (as said user Tomalak), so code in router.js:
function userCheck(req){
return new Promise(function(resolve, reject){
user.check(req, resolve, reject);
});
}
userCheck(req).then(result => {
console.log("promise result");
res.send(result);
}, error => {
console.log("promise error");
res.send(error);
});

Terminate IMAP Node correctly if no results

I am trying to exit the script if there are no emails that match our search criteria. If I don't do imap.end(), it never terminates. When I add the imap.end, I get an ECONNRESET. What's the proper way to exit out of IMAP early?
function openInbox(cb) {
imap.openBox('[Gmail]/All Mail', true, cb);
}
imap.once('ready', function() {
openInbox(function(err, box) {
if (err) throw err;
const aDayAgo = moment().subtract(1,'d');
imap.search([ ['SUBJECT', DPR_SUBJECT], ['SINCE', aDayAgo] ], function(err, results) {
if (err) throw err;
if (results.length == 0){
logging.log("No mail");
db.disconnect();
imap.end();
return;
}
var f = imap.fetch(results, {
bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
struct: true
});
f.on('message', function(msg, seqno) {
logging.verbose('Message #%d', seqno);
msg.once('end', function() {
logging.verbose(prefix + 'Finished');
});
});
f.once('error', function(err) {
logging.verbose('Fetch error: ' + err);
});
f.once('end', function() {
logging.log('Done fetching all messages!');
db.disconnect();
imap.end();
});
});
});
});
imap.once('error', function(err) {
logging.error(err.stack);
});
imap.once('end', function() {
logging.verbose('Connection ended');
});
exports.checkForMail = () => {
return imap.connect();
}

NODE JS Socket IO: req, res

I use node js and socket io on my website and i have a problem, i want to connect my client on my website when my "client.on('Connexion', function(data) { } " is called, and i have a problem :
/* ------- CALLBACK CONNECTION : --------*/
io.sockets.on('connection', function (client, req, res) {
client.on('Connexion', function(data) {
blabla...
if(results[0]) {
req.session.id = results[0];
req.session.firstname = results[1];
req.session.lastname = results[2];
req.session.email = results[4];
req.session.birthdate = results[5];
req.session.phonenum = results[6];
res.redirect("http://mydomain/" + "espace-client/");
/* HERE, req.session give and error --> TypeError: Cannot read property 'session' of undefined */
}
}
});
/* ------- I HAVE TEST THIS AND IT WORKS FINE : --------*/
app.get('/test/', function(req, res) {
req.session.id = "45";
res.send(req.session.id);
});
Thank you in advance :)
You can try to do this:
const io = socketIO.listen(server);
io.sockets
.on('connection', socket => {
socket.on('socket.setOnline', async event => {
const { access_token } = event;
if (!access_token) return socket.emit('socket.error', 'no access_token token');
jwt.verify(access_token, 'HelloThere', err => {
if (err) socket.emit('socket.error', err.message);
});
const user = await userService.getByAccessToken(access_token);
if (!user) return socket.emit('socket.error', 'user on setOnline not found');
user.update({ isOnline: true });
socket.emit('socket.notification', `#${user.id}: ${user.name} is online`);
socket.emit('socket.userStatus', { status: 'online' })
})
socket.on('socket.setOffline', async event => {
const { access_token } = event;
if (!access_token) return socket.emit('socket.error', 'no access_token token');
jwt.verify(access_token, 'HelloThere', err => {
if (err) socket.emit('socket.error', err.message)
});
const user = await userService.getByAccessToken(access_token);
if (!user) return socket.emit('socket.error', 'user on setOffline not found');
user.update({ isOnline: false });
socket.emit('socket.notification', `#${user.id}: ${user.name} is offline`);
socket.emit('socket.userStatus', { status: 'offline' })
})
socket.on('socket.checkUserStatus', async event => {
const { access_token } = event;
if (!access_token) return socket.emit('socket.error', 'no access_token token');
jwt.verify(access_token, 'HelloThere', err => {
if (err) socket.emit('socket.error', err.message);
});
const user = await userService.getByAccessToken(access_token);
socket.emit('socket.userStatus', { status: user.isOnline ? 'online' : 'offline' })
})
})

Categories

Resources