Last active
January 19, 2025 14:52
-
-
Save Avi-E-Koenig/3c15190726d1837802707588129cf5cd to your computer and use it in GitHub Desktop.
Whatsapp web js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client, LocalAuth, WAState } from "whatsapp-web.js"; | |
const _createClientInstance = (): Client => { | |
global.client = global.client?.getState() | |
? global.client | |
: new Client({ | |
authStrategy: new LocalAuth({ | |
clientId: "client", | |
}), | |
}); | |
return global.client; | |
} | |
let resolveClientReadyPromise: () => void; // A variable to store the resolver | |
const clientIsReadyPromise = new Promise<void>((resolve) => { | |
resolveClientReadyPromise = resolve; // Save the resolve function for later use | |
}); | |
const GetClientOrInitialize = async () => { | |
const client = _createClientInstance(); | |
//re define the listeners | |
client.once("ready", () => { | |
console.log("Client is ready"); | |
global.clientReady.state = true; | |
resolveClientReadyPromise(); | |
}); | |
let readyState: WAState = null; | |
try { | |
readyState = await client.getState(); | |
} catch (error) { } | |
console.log("Client.getState()", readyState); | |
if (readyState !== WAState.CONNECTED) { | |
await client.initialize(); | |
} | |
return client; | |
}; | |
export { | |
GetClientOrInitialize, | |
clientIsReadyPromise | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment