WhiskeySockets / Baileys

Lightweight full-featured typescript/javascript WhatsApp Web API
https://baileys.whiskeysockets.io/
MIT License
3.52k stars 1.19k forks source link

[BUG] Pairing code login mode not working anymore #328

Closed alexandrereyes closed 8 months ago

alexandrereyes commented 1 year ago

Describe the bug The auth pairing code is not working anymwore, i tried to run example.ts, the pair code shows on the console but wa doesn't notifies about it and also, the pairing code (yes, the console shows the code!) doesn't work on wa. 400 error on console:

{"level":10,"time":"2023-08-14T18:44:30.947Z","pid":49820,"hostname":"Desk-Ale","class":"ns","msg":"recv 63 bytes, total recv 63 bytes"}
{"level":10,"time":"2023-08-14T18:44:30.947Z","pid":49820,"hostname":"Desk-Ale","class":"ns","msg":"7679.52164-1","msg":"recv frame"}
{"level":10,"time":"2023-08-14T18:44:30.948Z","pid":49820,"hostname":"Desk-Ale","msg":"<iq from='@s.whatsapp.net' type='error' id='7679.52164-1'>\n\t\t<error code='400' text='bad-request'/>\n</iq>"}

I tried with 2 real numbers, no success! Anybody facing the same issue?

To Reproduce Steps to reproduce the behavior: Very simple: Run example.ts with --use-pairing-code and try to login

Expected behavior Receive wa notification about the code and the code work on wa

Environment (please complete the following information):

FERDIZ-afk commented 1 year ago

I also experienced the same thing

makanSukros commented 1 year ago

Same here

olalonde commented 1 year ago

Same issue here. Getting this message right after requesting pairing code.

[15:01:52.761] DEBUG (23866): communication recv
    unhandled: true
    msgId: "31234.38503-1"
    fromMe: false
    frame: {
      "tag": "iq",
      "attrs": {
        "from": "@s.whatsapp.net",
        "type": "error",
        "id": "31234.38503-1"
      },
      "content": [
        {
          "tag": "error",
          "attrs": {
            "code": "400",
            "text": "bad-request"
          }
        }
      ]
    }

It was working a few days ago.

burstfreeze commented 1 year ago

For a test, hardcode the value in https://github.com/WhiskeySockets/Baileys/blob/49ab16f5925789b85219bec2f35686234dab08a0/src/Socket/socket.ts#L528 to Chrome (macOS).

WA sends $Browser ($OS) and the server now seems to expect it in that very format

Auties00 commented 1 year ago

For a test, hardcode the value in https://github.com/WhiskeySockets/Baileys/blob/49ab16f5925789b85219bec2f35686234dab08a0/src/Socket/socket.ts#L528 to Chrome (macOS).

WA sends $Browser ($OS) and the server now seems to expect it in that very format

Does that fix it? As I explained on discord it should be as easy as cloning my repo https://github.com/Auties00/WhatsappWebRequestAnalyzer And seeing which nodes changed(probably something minor). I'd do it if I weren't on vacation

burstfreeze commented 1 year ago

I can't try it right now but the request payload is 14 bytes and the wa web source does what I said regarding $Browser ($OS)

lyfe00011 commented 1 year ago

Chrome (Linux) - this fix it

Salientekill commented 1 year ago

Could you tell me what I would have to change to work?

alexandrereyes commented 1 year ago

change yout makeWASocket method, example:

const sock = makeWASocket({
    browser: ['Chrome (Linux)', '', ''],
})
Radit10 commented 1 year ago

It's work thank you

A-d-i-t-h-y-a-n commented 1 year ago

👀

A-d-i-t-h-y-a-n commented 1 year ago

It's work thank you

Really 👀

ArifzynXD commented 1 year ago

Oke work, thks

mkhotib20 commented 1 year ago

thanks @alexandrereyes it works

curiousHG commented 1 year ago

Still not working for me, I am trying using the given Example.ts file and changing the browser to 'Chrome (Linux)' or 'Chrome (MacOS)' didn't work for me. Every time I enter the code on my device it says incorrect code. And the logs start to give QR code for some reason after the failed attempt.

A-d-i-t-h-y-a-n commented 1 year ago

Still not working for me, I am trying using the given Example.ts file and changing the browser to 'Chrome (Linux)' or 'Chrome (MacOS)' didn't work for me. Every time I enter the code on my device it says incorrect code. And the logs start to give QR code for some reason after the failed attempt.

Oh, But in my case it's Ok I just changed browser to Chrome (Linux) https://hermit.adithyan.xyz/qr

syxhri commented 1 year ago

Still not working for me, I am trying using the given Example.ts file and changing the browser to 'Chrome (Linux)' or 'Chrome (MacOS)' didn't work for me. Every time I enter the code on my device it says incorrect code. And the logs start to give QR code for some reason after the failed attempt.

I also experienced the same thing. But when I try to enter the phone number without the plus sign it works

curiousHG commented 1 year ago

Still not working for me, I am trying using the given Example.ts file and changing the browser to 'Chrome (Linux)' or 'Chrome (MacOS)' didn't work for me. Every time I enter the code on my device it says incorrect code. And the logs start to give QR code for some reason after the failed attempt.

I also experienced the same thing. But when I try to enter the phone number without the plus sign it works

This fixed it, Thanks!

Arctic-beaver commented 11 months ago

Is it still working with 'Chrome (Linux)'?

change yout makeWASocket method, example:

const sock = makeWASocket({
  browser: ['Chrome (Linux)', '', ''],
})
Riders004 commented 11 months ago

It's work thank you

Can you share your code to me

AKAZAMD commented 10 months ago

use whiskeysockets/baileys 6.4.1

GianFTZ commented 10 months ago

@Auties00 did it had already fixed?

Riders004 commented 10 months ago

Ini cara yang paling sempurna dan aman untuk pairing code dan saya pernah coba dan berhasil, menggunakan browser Safari (Linux) browser 1.0.0

"use strict";
const { Boom } = require("@hapi/boom");
const NodeCache = require("node-cache");
const {
    makeWASocket,
    makeInMemoryStore,
    useMultiFileAuthState,
    fetchLatestBaileysVersion,
    makeCacheableSignalKeyStore,
    DisconnectReason,
    jidDecode,
    delay,
    proto
} = require("@whiskeysockets/baileys");
const moment = require("moment");
const fs = require("fs");

const timer = moment(new Date()).format("HH:mm:ss DD/MM/YYYY");

const logger = require("pino")({
    timestamp: () => `,"time":"${new Date().toJSON()}"`
}).child({});
logger.level = "silent";

const useStore = !process.argv.includes("--no-store");
const usePairingCode = process.argv.includes("--use-pairing-code");

const msgRetryCounterCache = new NodeCache();

const rl = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
});

const question = text => new Promise(resolve => rl.question(text, resolve));

const store = useStore ? makeInMemoryStore({ logger }) : undefined;

store?.readFromFile("./store_multi.json");
// 10detik
setInterval(() => {
    store?.writeToFile("./store_multi.json");
}, 10000);

function uncache(module = ".") {
    return new Promise(function (resolve, reject) {
        try {
            delete require.cache[require.resolve(module)];
            resolve();
        } catch (error) {
            reject(error);
        }
    });
}

function nocache(module, cb = function () {}) {
    console.log(`module ${module} memantau perubahan data.\n`);
    fs.watchFile(require.resolve(module), async function () {
        await uncache(require.resolve(module));
        cb(module);
    });
}

async function connectoWhatsapps() {
    const { state, saveCreds } = await useMultiFileAuthState("@OpenWA");
    const { version, isLatest } = await fetchLatestBaileysVersion();

    const sock = makeWASocket({
        version,
        logger,
        printQRInTerminal: !usePairingCode,
        browser: ["Safari (Linux)", "browser", "1.0.0"],
        auth: {
            creds: state.creds,
            keys: makeCacheableSignalKeyStore(state.keys, logger)
        },
        msgRetryCounterCache,
        generateHighQualityLinkPreview: true,
        patchMessageBeforeSending,
        getMessage
    });

    store?.bind(sock.ev);

    require("./index");
    nocache("./index", function (module) {
        console.log(
            `\n[ WHATSAPPS BOT ] ${timer} ${module} telah di update!...`
        );
    });

    sock.ev.on("chats.set", function () {
        console.log("got chats", store.chats.all());
    });

    sock.ev.on("contacts.set", function () {
        console.log("got contacts", Object.values(store.contacts));
    });

    if (usePairingCode && !sock.authState.creds.registered) {
        const phoneNumber = await question(
            "Masukkan nomor telepon seluler anda: +"
        );
        if (/\d/.test(phoneNumber)) {
            const code = await sock.requestPairingCode(
                phoneNumber.replace(/[^0-9]/g, "")
            );
            console.log(
                "jika ada notif whatsapp [Memasukkan kode menautkan perangkat baru] maka sudah di pastikan berhasil!"
            );
            console.log(`pairing code: ${code.match(/.{1,4}/g).join("-")}`);
        } else {
            console.log("Nomor telepon tidak valid.");
            process.exit();
        }
    }

    const sendMessageWTyping = async (msg, jid) => {
        await sock.presenceSubscribe(jid);
        await delay(500);
        await sock.sendPresenceUpdate("composing", jid);
        await delay(2000);
        await sock.sendPresenceUpdate("paused", jid);
        await sock.sendMessage(jid, msg);
    };

    sock.ev.on("connection.update", function ({ connection, lastDisconnect }) {
        switch (connection) {
            case "close":
                switch (new Boom(lastDisconnect?.error)?.output?.statusCode) {
                    case DisconnectReason.badSession:
                        console.log(
                            `Bad Session File, hapus session dan scan scan lagi.`
                        );
                        process.exit();
                        break;
                    case DisconnectReason.connectionClosed:
                        console.log(
                            "Connection closed, menyambungkan kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.connectionLost:
                        console.log(
                            "Connection Lost from Server, menyambungkan kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.connectionReplaced:
                        console.log(
                            "Connection Replaced, sesi baru lainnya dibuka dan terhubung kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.loggedOut:
                        console.log(`Device Logged Out, scan ulang lagi.`);
                        process.exit();
                        break;
                    case DisconnectReason.restartRequired:
                        console.log("Restart Required, memulai ulang...");
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.timedOut:
                        console.log(
                            "Connection TimedOut, menyambungkan kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.Multidevicemismatch:
                        console.log("Multi device mismatch, scan ulang lagi.");
                        process.exit();
                        break;
                    default:
                        console.log(``);
                }
                break;
            case "connecting":
                console.log(
                    `using WA v${version.join(".")}, isLatest ${isLatest}`
                );
                break;
            case "open":
                console.log(" nama :", sock.user.name);
                console.log(" nomor:", sock.user.id.split(":")[0]);
                rl.close();
                break;
            default:
        }
    });

    sock.ev.on("creds.update", function () {
        saveCreds();
    });

    sock.ev.on("messages.upsert", function ({ messages, type }) {
        console.log("recv messages ", JSON.stringify(messages, undefined, 2));
    });

    sock.decodeJid = function (jid) {
        if (!jid) return jid;
        if (/:\d+@/gi.test(jid)) {
            const decode = jidDecode(jid) || {};
            return (
                (decode.user &&
                    decode.server &&
                    decode.user + "@" + decode.server) ||
                jid
            );
        }
    };

    sock.ev.on("contacts.update", function (update) {
        for (const contact of update) {
            const id = sock.decodeJid(contact.id);
            if (store && store.contacts)
                store.contacts[id] = {
                    id,
                    name: contact.notify
                };
        }
    });

    sock.ev.on(
        "group-participants.update",
        function ({ id, participants, action }) {}
    );

    sock.reply = async function (from, content, message) {
        await sock.sendMessage(from, { text: content }, { quoted: message });
    };

    return sock;

    function patchMessageBeforeSending(message) {
        const requiresPatch = !!(
            message.buttonsMessage ||
            message.templateMessage ||
            message.listMessage
        );
        if (requiresPatch) {
            message = {
                viewOnceMessage: {
                    message: {
                        messageContextInfo: {
                            deviceListMetadataVersion: 2,
                            deviceListMetadata: {}
                        },
                        ...message
                    }
                }
            };
        }
        return message;
    }

    async function getMessage(key) {
        if (store) {
            const msg = await store.loadMessage(key.remoteJid, key.id);
            return msg?.message || undefined;
        }
        // only if store is present
        return proto.Message.fromObject({});
    }
}

connectoWhatsapps();

U can use chrome for faster

PurpShell commented 8 months ago

This issue is fixed from my analysis.

ibnusurkati commented 7 months ago

use this, it's works for me

...
browser: Browsers.ubuntu('CHROME'),
...

because if we look at the original source, array browser[1] refers to an enum that uses uppercase letters.

Screenshot 2024-01-21 at 22 44 57 Screenshot 2024-01-21 at 22 45 33
Riders004 commented 7 months ago

use this, it's works for me

...
browser: Browsers.ubuntu('CHROME'),
...

because if we look at the original source, array browser[1] refers to an enum that uses uppercase letters.

Screenshot 2024-01-21 at 22 44 57 Screenshot 2024-01-21 at 22 45 33

Well it's got fixed

Jann-X commented 6 months ago

I've used it before. but still not working. what should I replace?

change yout makeWASocket method, example:

const sock = makeWASocket({
  browser: ['Chrome (Linux)', '', ''],
})
Riders004 commented 6 months ago

I've used it before. but still not working. what should I replace?

change yout makeWASocket method, example:

const sock = makeWASocket({
    browser: ['Chrome (Linux)', '', ''],
})

const sock = makeWASocket({ browser: ['ubuntu', 'chrome', ''], })

Cosm1cBug commented 6 months ago

Ini cara yang paling sempurna dan aman untuk pairing code dan saya pernah coba dan berhasil, menggunakan browser Safari (Linux) browser 1.0.0

"use strict";
const { Boom } = require("@hapi/boom");
const NodeCache = require("node-cache");
const {
    makeWASocket,
    makeInMemoryStore,
    useMultiFileAuthState,
    fetchLatestBaileysVersion,
    makeCacheableSignalKeyStore,
    DisconnectReason,
    jidDecode,
    delay,
    proto
} = require("@whiskeysockets/baileys");
const moment = require("moment");
const fs = require("fs");

const timer = moment(new Date()).format("HH:mm:ss DD/MM/YYYY");

const logger = require("pino")({
    timestamp: () => `,"time":"${new Date().toJSON()}"`
}).child({});
logger.level = "silent";

const useStore = !process.argv.includes("--no-store");
const usePairingCode = process.argv.includes("--use-pairing-code");

const msgRetryCounterCache = new NodeCache();

const rl = require("readline").createInterface({
    input: process.stdin,
    output: process.stdout
});

const question = text => new Promise(resolve => rl.question(text, resolve));

const store = useStore ? makeInMemoryStore({ logger }) : undefined;

store?.readFromFile("./store_multi.json");
// 10detik
setInterval(() => {
    store?.writeToFile("./store_multi.json");
}, 10000);

function uncache(module = ".") {
    return new Promise(function (resolve, reject) {
        try {
            delete require.cache[require.resolve(module)];
            resolve();
        } catch (error) {
            reject(error);
        }
    });
}

function nocache(module, cb = function () {}) {
    console.log(`module ${module} memantau perubahan data.\n`);
    fs.watchFile(require.resolve(module), async function () {
        await uncache(require.resolve(module));
        cb(module);
    });
}

async function connectoWhatsapps() {
    const { state, saveCreds } = await useMultiFileAuthState("@OpenWA");
    const { version, isLatest } = await fetchLatestBaileysVersion();

    const sock = makeWASocket({
        version,
        logger,
        printQRInTerminal: !usePairingCode,
        browser: ["Safari (Linux)", "browser", "1.0.0"],
        auth: {
            creds: state.creds,
            keys: makeCacheableSignalKeyStore(state.keys, logger)
        },
        msgRetryCounterCache,
        generateHighQualityLinkPreview: true,
        patchMessageBeforeSending,
        getMessage
    });

    store?.bind(sock.ev);

    require("./index");
    nocache("./index", function (module) {
        console.log(
            `\n[ WHATSAPPS BOT ] ${timer} ${module} telah di update!...`
        );
    });

    sock.ev.on("chats.set", function () {
        console.log("got chats", store.chats.all());
    });

    sock.ev.on("contacts.set", function () {
        console.log("got contacts", Object.values(store.contacts));
    });

    if (usePairingCode && !sock.authState.creds.registered) {
        const phoneNumber = await question(
            "Masukkan nomor telepon seluler anda: +"
        );
        if (/\d/.test(phoneNumber)) {
            const code = await sock.requestPairingCode(
                phoneNumber.replace(/[^0-9]/g, "")
            );
            console.log(
                "jika ada notif whatsapp [Memasukkan kode menautkan perangkat baru] maka sudah di pastikan berhasil!"
            );
            console.log(`pairing code: ${code.match(/.{1,4}/g).join("-")}`);
        } else {
            console.log("Nomor telepon tidak valid.");
            process.exit();
        }
    }

    const sendMessageWTyping = async (msg, jid) => {
        await sock.presenceSubscribe(jid);
        await delay(500);
        await sock.sendPresenceUpdate("composing", jid);
        await delay(2000);
        await sock.sendPresenceUpdate("paused", jid);
        await sock.sendMessage(jid, msg);
    };

    sock.ev.on("connection.update", function ({ connection, lastDisconnect }) {
        switch (connection) {
            case "close":
                switch (new Boom(lastDisconnect?.error)?.output?.statusCode) {
                    case DisconnectReason.badSession:
                        console.log(
                            `Bad Session File, hapus session dan scan scan lagi.`
                        );
                        process.exit();
                        break;
                    case DisconnectReason.connectionClosed:
                        console.log(
                            "Connection closed, menyambungkan kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.connectionLost:
                        console.log(
                            "Connection Lost from Server, menyambungkan kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.connectionReplaced:
                        console.log(
                            "Connection Replaced, sesi baru lainnya dibuka dan terhubung kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.loggedOut:
                        console.log(`Device Logged Out, scan ulang lagi.`);
                        process.exit();
                        break;
                    case DisconnectReason.restartRequired:
                        console.log("Restart Required, memulai ulang...");
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.timedOut:
                        console.log(
                            "Connection TimedOut, menyambungkan kembali..."
                        );
                        connectoWhatsapps();
                        break;
                    case DisconnectReason.Multidevicemismatch:
                        console.log("Multi device mismatch, scan ulang lagi.");
                        process.exit();
                        break;
                    default:
                        console.log(``);
                }
                break;
            case "connecting":
                console.log(
                    `using WA v${version.join(".")}, isLatest ${isLatest}`
                );
                break;
            case "open":
                console.log(" nama :", sock.user.name);
                console.log(" nomor:", sock.user.id.split(":")[0]);
                rl.close();
                break;
            default:
        }
    });

    sock.ev.on("creds.update", function () {
        saveCreds();
    });

    sock.ev.on("messages.upsert", function ({ messages, type }) {
        console.log("recv messages ", JSON.stringify(messages, undefined, 2));
    });

    sock.decodeJid = function (jid) {
        if (!jid) return jid;
        if (/:\d+@/gi.test(jid)) {
            const decode = jidDecode(jid) || {};
            return (
                (decode.user &&
                    decode.server &&
                    decode.user + "@" + decode.server) ||
                jid
            );
        }
    };

    sock.ev.on("contacts.update", function (update) {
        for (const contact of update) {
            const id = sock.decodeJid(contact.id);
            if (store && store.contacts)
                store.contacts[id] = {
                    id,
                    name: contact.notify
                };
        }
    });

    sock.ev.on(
        "group-participants.update",
        function ({ id, participants, action }) {}
    );

    sock.reply = async function (from, content, message) {
        await sock.sendMessage(from, { text: content }, { quoted: message });
    };

    return sock;

    function patchMessageBeforeSending(message) {
        const requiresPatch = !!(
            message.buttonsMessage ||
            message.templateMessage ||
            message.listMessage
        );
        if (requiresPatch) {
            message = {
                viewOnceMessage: {
                    message: {
                        messageContextInfo: {
                            deviceListMetadataVersion: 2,
                            deviceListMetadata: {}
                        },
                        ...message
                    }
                }
            };
        }
        return message;
    }

    async function getMessage(key) {
        if (store) {
            const msg = await store.loadMessage(key.remoteJid, key.id);
            return msg?.message || undefined;
        }
        // only if store is present
        return proto.Message.fromObject({});
    }
}

connectoWhatsapps();

Why u are using the 'patch message' which was previously used for sending list messages and all? Is it still working?

@Riders004

Ytsixx commented 4 months ago

IMG_20240424_063707 Hello 👋 I hope everyone is well I would like to know how I can add a button to my project I have had more than 3 weeks without success

Português: Olá 👋 Espero que todos estejam bem. Gostaria de saber como posso adicionar um botão ao meu projeto. Já faz mais de 3 semanas sem sucesso.

Riders004 commented 4 months ago

IMG_20240424_063707 Hello 👋 I hope everyone is well I would like to know how I can add a button to my project I have had more than 3 weeks without success

Português: Olá 👋 Espero que todos estejam bem. Gostaria de saber como posso adicionar um botão ao meu projeto. Já faz mais de 3 semanas sem sucesso.

Can you share me code of this reply message code ?