Skip to content

Instantly share code, notes, and snippets.

@Avi-E-Koenig
Last active January 19, 2025 14:52
Show Gist options
  • Save Avi-E-Koenig/3c15190726d1837802707588129cf5cd to your computer and use it in GitHub Desktop.
Save Avi-E-Koenig/3c15190726d1837802707588129cf5cd to your computer and use it in GitHub Desktop.
Whatsapp web js
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