Skip to content

Error in client.getChats()  #2527

Description

@punit-mistry

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

hey
i am try to make the whatsapp clone so after the scanning the qrcode i am getting all the contact using the client.getChats() after that i am fetching all the messages but after scanning i am getting
Error retrieving chat history: Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'getChats')

Expected behavior

as a user i am expecting to get all the contact number and name but i am getting this Error retrieving chat history: Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'getChats')

Steps to Reproduce the Bug or Issue

  1. scanning the qrcode using the /qrcode
  2. getting all the contacts
  3. Error retrieving chat history: Error: Evaluation failed: TypeError: Cannot read properties of undefined (reading 'getChats')

Relevant Code

const client = new Client({
    authStrategy: new LocalAuth()
});
 

let isWhatsAppReady = false;

app.get('/qrcode', async (req, res) => {
  if (!isWhatsAppReady) {
    let qrData = '';

    // Create a promise to wait for the QR code generation
    const waitForQRCode = new Promise((resolve) => {
      // Generate and display the QR code in the terminal
      client.on('qr', (qr) => {
        console.log(qr);
        qrData = qr;
        qrcode.generate(qr, { small: true });
        
        // Resolve the promise once the QR code is generated
        resolve();
      });
    });

    // Listen for the 'authenticated' event to know when WhatsApp is ready
// Listen for the 'authenticated' event to know when WhatsApp is ready
client.on('authenticated', (session) => {
  console.log('WhatsApp authenticated');
  isWhatsAppReady = true; // Set WhatsApp as ready when authenticated
});

// Initialize the WhatsApp client
client.initialize();

    // Wait for the QR code to be generated before sending the response
    await waitForQRCode;

    // Respond with QR code data as JSON
    res.json({ qrCodeData: qrData });
  } else {
    res.send(`
      <div class="flex gap-5">
        <input
          type="text"
          className="w-60 border-2 border-black h-10 p-2 rounded-lg"
          placeholder="Send WhatsApp Message.."
          id="messageInput"
        />
        <button
          className="bg-green-600 p-2 rounded-lg text-white font-bold"
          id="sendMessageButton"
        >
          💬 Send Message
        </button>
      </div>
    `);
  }
});

app.get('/chat/messages/:username', async (req, res) => {
  if (isWhatsAppReady) {
    try {
      const { username } = req.params;

      // Find the chat by username
      const chat = await client.getChatById(username);

      // Check if the chat exists
      if (chat) {
        // Define search options to retrieve messages
        const searchOptions = {
          limit: 10, // Number of messages to retrieve (adjust as needed)
        };

        // Fetch messages from the chat
        const messages = await chat.fetchMessages(searchOptions);

        // Extract relevant message information
        const messageData = messages.map((message) => ({
          id: message.id.id,
          content: message.body,
          timestamp: message.timestamp,
          FromMe:message.id.fromMe
        }));

        res.json(messageData);
      } else {
        res.status(404).send('Chat not found');
      }
    } catch (error) {
      console.error('Error retrieving chat messages:', error);
      res.status(500).send('Error retrieving chat messages.');
    }
  } else {
    res.status(400).send('WhatsApp is not yet ready.');
  }
});


app.post('/send-message', async (req, res) => {
  const { message,DriverNumber } = req.body;
console.log(message,DriverNumber)
  if (isWhatsAppReady) {
    try {
      await client.sendMessage(DriverNumber,message);
      res.send('Message sent successfully!');
    } catch (error) {
      console.error('Error sending message:', error);
      res.status(500).send('Error sending message.');
    }
  } else {
    res.status(400).send('WhatsApp is not yet ready.');
  }
});


// Define an API endpoint for retrieving the entire chat history
app.get('/chat/history', async (req, res) => {
  try {
    // Check if WhatsApp is ready
    if (isWhatsAppReady) {
      const chats = await client.getChats();
      let chatHistory = [];

      // Define your Options for message retrieval here
      const Options = {
        limit: 10, // Number of messages to retrieve per chat (adjust as needed)
      };

      for (const chat of chats) {
        const messages = await chat.fetchMessages(Options);

        const allMessages = messages.map((message) => ({
          id: message.id.id,
          content: message.body,
          timestamp: message.timestamp,
          from: message.id.fromMe,
        }));

        chatHistory.push({
          chatId: chat.name, // Use chat.name or chat.id._serialized depending on your needs
          number: chat.id,
          isGroup: chat.isGroup,
          messages: allMessages,
        });
      }

      res.json(chatHistory);
    } else {
      res.status(400).send('WhatsApp is not yet ready.');
    }
  } catch (error) {
    console.error('Error retrieving chat history:', error);
    res.status(500).send('Error retrieving chat history.');
  }
});
  



client.on('ready', () => {
  console.log('WhatsApp Client is ready!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Browser Type

Google Chrome

WhatsApp Account Type

Standard

Does your WhatsApp account have multidevice enabled?

No, I am not using Multi Device

Environment

os :windows
node.js Version: v20.0.0

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething is broken

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions