this.challstr = parts.join('|');
const reqOptions = {
hostname: "play.pokemonshowdown.com",
path: "/~~showdown/action.php",
agent: false,
};
let loginQuerystring;
if (!Config.pass) {
reqOptions.method = 'GET';
reqOptions.path += `?act=getassertion&userid=${toId(Config.nick)}&challstr=${this.challstr}`;
} else {
reqOptions.method = 'POST';
loginQuerystring = `act=login&name=${toId(Config.nick)}&pass=${Config.pass}&challstr=${this.challstr}`;
reqOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': loginQuerystring.length,
};
}
debug(`Sending login to ${reqOptions.path}${loginQuerystring ? ` | Data: ${loginQuerystring}` : ''}`);
const req = https.request(reqOptions, res => {
res.setEncoding('utf8');
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
if (data === ';') {
console.log(`LOGIN FAILED - The name ${Config.nick} is registered and ${Config.pass ? 'an invalid' : 'no'} password was provided.`);
process.exit(1);
}
if (data.length < 50) {
console.log(`LOGIN FAILED - ${data}`);
process.exit(1);
}
if (data.indexOf('heavy load') > -1) {
console.log(`LOGIN FAILED - The login server is experiencing heavy load and cannot accommodate the bot's connection right now.`);
process.exit(1);
}
try {
data = JSON.parse(data.slice(1));
if (data.actionsuccess) {
data = data.assertion;
} else {
console.log(`Unable to login; the request was unsuccessful\n${JSON.stringify(data)}\n`);
process.exit(1);
}
} catch (e) {}
// Autojoining should be handled before sending /trn; since only
// eleven rooms can be autojoined at a time, leave any extras to
// be joined manually. (This allows the server to remember the first
// eleven if you happen to cut back on rooms)
if (Config.autojoin.length) {
const [autojoin, extra] = [Config.autojoin.slice(0, 11), Config.autojoin.slice(11)];
this.send(`|/autojoin ${autojoin.join(',')}`);
if (extra.length) this.extraJoin = extra;
}
this.send(`|/trn ${Config.nick},0,${data}`);
});
});
req.on('error', e => {
console.error(`Error while logging in: ${e.stack}`);
return;
});
if (loginQuerystring) req.write(loginQuerystring);
req.end();