Coder Social home page Coder Social logo

mimamch / wa-multi-session Goto Github PK

View Code? Open in Web Editor NEW
95.0 7.0 31.0 103 KB

Multiple Session Whatsapp Socket Javascript Library

Home Page: https://www.npmjs.com/package/wa-multi-session

License: MIT License

TypeScript 100.00%
wa-gateway whatapp whatsapp-api whatsapp-chat whatsapp-web baileys chat js-library js-package messaging

wa-multi-session's Introduction

Whatsapp Multi Session - Connecting More Whatsapp Session in 1 App

Connecting Your app with Whatsapp Messaging

Lightweight library for whatsapp. Not require Selenium or any other browser.

Stand above Baileys Library.

Installation

Install package using npm

npm install wa-multi-session@latest

Then import your code

Using JS Module

import * as whatsapp from "wa-multi-session";

or using CommonJS

const whatsapp = require("wa-multi-session");

Session Usage/Examples

Start New Session

// create session with ID : mysessionid

const session = await whatsapp.startSession("mysessionid");
// Then, scan QR on terminal

Get All Session ID

const sessions = whatsapp.getAllSession();
// returning all session ID that has been created

Get Session Data By ID

const session = whatsapp.getSession("mysessionid");
// returning session data

Load Session From Storage / Load Saved Session

whatsapp.loadSessionsFromStorage();
// Start saved session without scan again

Messaging Usage/Examples

Send Text Message

await whatsapp.sendTextMessage({
  sessionId: "mysessionid", // session ID
  to: "6281234567890", // always add country code (ex: 62)
  text: "Hi There, This is Message from Server!", // message you want to send
});

Send Image

const image = fs.readFileSync("./myimage.png"); // return Buffer
const send = await whatsapp.sendImage({
  sessionId: "session1",
  to: "6281234567890",
  text: "My Image Caption",
  media: image, // can from URL too
});

Send Video

const video = fs.readFileSync("./myvideo.mp4"); // return Buffer
const send = await whatsapp.sendVideo({
  sessionId: "session1",
  to: "6281234567890",
  text: "My Video Caption",
  media: video, // can from URL too
});

Send Document File

const filename = "mydocument.docx";
const document = fs.readFileSync(filename); // return Buffer
const send = await whatsapp.sendDocument({
  sessionId: "session1",
  to: "6281234567890",
  filename: filename,
  media: document,
  text: "Hei, Check this Document",
});

Send Voice Note

const filename = "myaudio.mp3";
const audio = fs.readFileSync(filename); // return Buffer
const send = await whatsapp.sendVoiceNote({
  sessionId: "session1",
  to: "6281234567890",
  media: audio,
});

Read a Message

await whatsapp.readMessage({
  sessionId: "session1",
  key: msg.key,
});

Send Typing Effect

await whatsapp.sendTyping({
  sessionId: "session1",
  to: "6281234567890",
  duration: 3000,
});

Listener Usage/Examples

Add Listener/Callback When Receive a Message

whatsapp.onMessageReceived((msg) => {
  console.log(`New Message Received On Session: ${msg.sessionId} >>>`, msg);
});

Add Listener/Callback When QR Printed

whatsapp.onQRUpdated(({ sessionId, qr }) => {
  console.log(qr);
});

Add Listener/Callback When Session Connected

whatsapp.onConnected((sessionId) => {
  console.log("session connected :" + sessionId);
});

Handling Incoming Message Examples

whatsapp.onMessageReceived(async (msg) => {
  if (msg.key.fromMe || msg.key.remoteJid.includes("status")) return;
  await whatsapp.readMessage({
    sessionId: msg.sessionId,
    key: msg.key,
  });
  await whatsapp.sendTyping({
    sessionId: msg.sessionId,
    to: msg.key.remoteJid,
    duration: 3000,
  });
  await whatsapp.sendTextMessage({
    sessionId: msg.sessionId,
    to: msg.key.remoteJid,
    text: "Hello!",
    answering: msg, // for quoting message
  });
});

Save Media Message (Image, Video, Document)

wa.onMessageReceived(async (msg) => {
  if (msg.message?.imageMessage) {
    // save image
    msg.saveImage("./myimage.jpg");
  }

  if (msg.message?.videoMessage) {
    // save video
    msg.saveVideo("./myvideo.mp4");
  }

  if (msg.message?.documentMessage) {
    // save document
    msg.saveDocument("./mydocument"); // without extension
  }
});

Optional Configuration Usage/Examples

Set custom credentials directory

// default dir is "wa_credentials"
whatsapp.setCredentialsDir("my_custom_dir");
// or : credentials/mycreds

Change Log

v3.3 September 2023 (LATEST)

What's New:

  • Send Voice Note
  • Send Sticker
  • onMessageUpdate (message ack status)

v3.2.1 July 2023

  • Add error class named: WhatsappError

v3.1.2 July 2023

  • Add send document message

v3.0.0 June 2023

Authors

Feedback or Support

If you have any feedback or support, please reach out to me at [email protected]

wa-multi-session's People

Contributors

jobians avatar mimamch avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

wa-multi-session's Issues

onMessageReceived from iphone users

hi i was making a simple app to responde msg automatically and notice that when an iphone user sends me a msg i don't receive the content of the message anywhere, this is the code
whatsapp.onMessageReceived(async (msg) => { console.log(New Message =>, msg);

and this is the log from iphone users
New Message => { key: { remoteJid: ****@s.whatsapp.net', fromMe: false, id: '****', participant: undefined }, messageTimestamp: 1689286004, pushName: '****', broadcast: false, messageStubType: 2, messageStubParameters: [ 'Bad MAC' ], sessionId: 'qeso', saveImage: [Function (anonymous)], saveVideo: [Function (anonymous)], saveDocument: [Function (anonymous)] }
i replaced some private data with "****"
am i doing something wrong? is this fixeable? thanks in advance

with not iphone users i found the content of the message in msg.message.conversation

if the iphone user send a msg on a gruop chat im able to see the content but not on private chats

ex of the log when iphone user send msg on a group

New Message => { key: { remoteJid: '****@g.us', fromMe: false, id: '****', participant: '****@s.whatsapp.net' }, messageTimestamp: 1689286637, pushName: '****', broadcast: false, message: Message { senderKeyDistributionMessage: SenderKeyDistributionMessage { groupId: '****@g.us', axolotlSenderKeyDistributionMessage: [Uint8Array] }, extendedTextMessage: ExtendedTextMessage { text: 'TEXT HERE', contextInfo: [ContextInfo] }, messageContextInfo: MessageContextInfo { deviceListMetadata: [DeviceListMetadata], deviceListMetadataVersion: 2 } }, sessionId: 'qeso', saveImage: [Function (anonymous)], saveVideo: [Function (anonymous)], saveDocument: [Function (anonymous)] }

Backup session to AWS or similar to prevent deletion

Hey,

Great Library and works perfect!

One issue, after I rebuild my Nodejs server all of the sessions get deleted.
Is this something that I can prevent?

I was thinking maybe to backup and restore the sessions to AWS S3.
Even got the saving part working
(currently im saving the entire WASocket object as I couldnt understand which part of it actually holds the token itself)

async function saveWhatsappSessionToAWS(sessionId, session) {
  console.log(`saveWhatsappSessionToAWS sessionId`, sessionId);
  console.log(`saveWhatsappSessionToAWS session`, session);

  // Convert the JSON object to a string
  const wasocketString = JSON.stringify(session);
  console.log(`saveWhatsappSessionToAWS wasocketString`, wasocketString);

  return new Promise(async (resolve, reject) => {
    const awsParams = {
      Body: wasocketString,
      Bucket: 'test',
      Key: `${sessionId}_wa_session`, // Modify Key structure as needed
    };

    // Create an S3 client
    const client = new S3Client({ region: 'us-east-1' });

    try {
      // Upload the session token content to S3
      await client.send(new PutObjectCommand(awsParams));
      console.log(`Session token for ${sessionId} uploaded to AWS S3.`);
      resolve(true)
    } catch (err) {
      console.error('Error uploading session token to S3:', err);
      resolve(false)
    }
  });
}

the problem is to retrieve it back:

async function loadWhatsappSessionsFromAWS(sessionId) {
  console.log(`loadWhatsappSessionsFromAWS sessionId`, sessionId);

  return new Promise(async (resolve, reject) => {
    const awsParams = {
      Bucket: 'test',
      Key: `${sessionId}_wa_session`, // Modify Key structure as needed
    };
    // Create an S3 client
    const client = new S3Client({ region: 'us-east-1' });

    try {
      // Retrieve the session token from S3
      const response = await client.send(new GetObjectCommand(awsParams));

      if (response.Body) {
        const sessionString = response.Body.toString('utf-8');
        console.log(`sessionString for ${sessionId} retrieved from AWS S3:\n`, sessionString);

        if (typeof sessionString === 'string' && sessionString.trim() !== '') {
          const session = JSON.parse(sessionString);
          console.log(`session for ${sessionId} retrieved from AWS S3:\n`, session);

          const waConnection = new WAConnection();
          waConnection.loadAuthInfo(session);
          console.log(`waConnection for ${sessionId} retrieved from AWS S3:\n`, waConnection);

          resolve(waConnection)
        } else {
          resolve(false)
        }
      } else {
        console.log(`Session token for ${sessionId} not found in AWS S3.`);
        resolve(false)
      }
    } catch (err) {
      console.error('Error retrieving session token from S3:', err);
      resolve(false)
    }
  });
}

the restore results in an error: "SyntaxError: Unexpected token o in JSON at position 1" because the WASocket probably gets corrupted while serializing..

any suggestions?

Pertanyaan

Maaf saya belum mencoba
tapi apakah untuk mengirim pesan tombol, gambar, url dan lain lain sama dengan baileys ? atau cuma text saja.

How to store values in session

  • I need to store values in session variable
    const session = await whatsapp.startSession("mysessionid");

Can you please suggest me?

Cek status pesan yang dikirim

Bisa nggak ya kita get messages yang udah dikirim sebelumnya? Saya ada case mau kirim bulk messages terus get messages nya dan cek status nya, apakah berhasil terkirim atau tidak

Terimakasih

WA Logout per hari

Saya sedang mengetes library ini dari 3 hari yang lalu. tapi kenapa setiap pagi whatsapp sesi nya selalu disconnect / harus scan ulang qr.
saya menggunakan versi yang terupdate.

Send Location ? Why Not

Hey this is not about the issue on this repository just sharing the information, I see and understand the workflow of this package, I understand that this is a combination of the previous package, namely bailyes whatsapp whose repository is currently closed, but it can still run except button templates and list templates, I use this repository for my project and I costum with the concept of using bailyes, I read the previous issue can I send a button, location or so on ? I tried the technique below. please try to make sure again, I hope there is a latest update for something like this

=================================================
const id = '[email protected]'
const session = whatsapp.getSession(sessionId)
session.sendMessage( id, { location: { degreesLatitude: 24.121231, degreesLongitude: 55.1121221 } } )

=================================================

Best Regards
Ojan Alpha

onMessageUpdate()

onMessageUpdate() function not working its showing only session is not the data: MessageUpdated
maybe message type is wrong please check it on Socket/index.ts line 103 callback.get(CALLBACK_KEY.ON_MESSAGE_UPDATED)?.(sessionId, data);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.