Skip to content

Instantly share code, notes, and snippets.

@icleitoncosta
Created November 19, 2022 21:15
Show Gist options
  • Save icleitoncosta/d2ca995f37ae5ea0af727469fc1b3d92 to your computer and use it in GitHub Desktop.
Save icleitoncosta/d2ca995f37ae5ea0af727469fc1b3d92 to your computer and use it in GitHub Desktop.
Function to pré generate messageId for WhatsApp Web APIs
/**
* Function to pre generate messageId for WhatsApp WEB APIs
* For groups is necessary send deviceNumber
**/
export function generateWhatsAppMsgId (to: string, deviceNumber?: string) {
if (/^\d+@c.us$/.test(parseWid(to))) {
return `true_${parseWid(to)}_${newId()}`
} else {
if(!deviceNumber) throw new Error("Please, send device number for send msg to groups");
return `true_${parseWid(to)}_${newId()}_${parseWid(deviceNumber)}`
}
}
function parseWid(number: string): string {
if(/^\d+@c.us$/.test(number) || /^\d+-\d+@g.us$/.test(number))
return number;
else if(/^\d+$/.test(number))
return number + "c.us";
else if(/^\d+-\d+$/.test(number))
return number + "g.us";
else
throw new Error("Send the whatsapp number correctly");
}
function newId(): string {
const t = new Uint8Array(8);
const randomHex = self.crypto.getRandomValues(t);
const parsed = parseHex(randomHex);
return '3EB0' + parsed;
}
function parseHex(e: any) {
const arr = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70];
const t = [];
for (let r = 0; r < e.length; r++) {
const i = e[r];
t.push(arr[i >> 4], arr[15 & i]);
}
return String.fromCharCode.apply(String, t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment