Node.js library for creating bots and sending/receiving messages using the Whatsapp Cloud API

Overview

whatsapp-cloud-api

whatsapp-cloud-api is a Node.js library for creating bots and sending/receiving messages using the Whatsapp Cloud API.

Contains built-in Typescript declarations.

run tests, lint, build npm publish npm npm bundle size npm

Install

npm i whatsapp-cloud-api

Usage

import { createBot } from 'whatsapp-cloud-api';

// replace the values below
const from = 'YOUR_WHATSAPP_BUSINESS_ACCOUNT_ID';
const token = 'YOUR_TEMPORARY_OR_PERMANENT_ACCESS_TOKEN';
const to = 'PHONE_NUMBER_OF_RECIPIENT';

// Create a bot that can send messages
const bot = createBot(from, token);

// Send text message
const result = await bot.sendMessage(to, 'Hello world');

// Send image
const result = await bot.sendImage(to, 'https://picsum.photos/200/300', {
  caption: 'Random jpg',
});

// Send location
const result = await bot.sendLocation(to, 40.7128, -74.0060, {
  name: 'New York',
});

// Send template
const result = await bot.sendTemplate(to, 'hello_world', 'en_us');

Documentation

Development

# install npm modules
npm i

# eslint
npm run lint

# typescript check
npm run ts-check

# test
## Read 'Local Testing' below before running this
npm t

# build
npm run build

Local Testing

Create a .env file in the root of your project:

FROM_PHONE_NUMBER_ID=""
ACCESS_TOKEN=""
VERSION=""
TO=""

Pull Requests

Any and all PRs are open.

Comments
  • Not able to connect to webhook

    Not able to connect to webhook

    I followed all the steps in the tutorial section and I was able to send messages, but my webhook endpoint was not verified. I've tried many ways, and the only way that works is using Glitch, as recommended in the API documentation. Do you know any solution that could solve my issue?

    question 
    opened by leonardodma 23
  • Where to get name of the sender

    Where to get name of the sender

    https://github.com/tawn33y/whatsapp-cloud-api/blob/dd73985e97539dd70f4eb74ee256eef63dda2062/src/startExpressServer.ts#L71

    Where on the api can i get the name of the sender, When i check the from key it only has cellNumber of the sender but no name

    bot.on('message', async (msg) => { console.log(msg.from.name); //undefined console.log(msg.from); //+27xxxxxxxxxx }

    enhancement 
    opened by RyzorBent 13
  • How to use this module, to handle different WhatsApp cloud API tokens from different users at the same time.

    How to use this module, to handle different WhatsApp cloud API tokens from different users at the same time.

    Greetings,

    My MERN SAAS app where I'm using this module on the backend nodejs is getting completed. But now I'm not sure on how the backend nodejs is going to handle multiple users with different [ phone numbers, WhatsApp API tokens, etc. ]. are going to use the SAAS platform, Because the module needs the tokens at start-up time and keeps them in memory throughout.

    What architecture approach do you suggest that I can use to easily handle this situation? any suggestions will be highly appreciated.

    how to use 
    opened by RyzorBent 6
  • sendText - Generic error step 2 tutorial

    sendText - Generic error step 2 tutorial

    Hello, i just followed the tutorial steps and i have this response after step 2

    { error: { message: '(#131000) Generic error', type: 'OAuthException', code: 131000, error_data: { messaging_product: 'whatsapp', details: 'Generic error' }, error_subcode: 2494002, fbtrace_id: 'AC1dtC9ImEGwkBiss2Xt0mA' } }

    I could make it work using Postman.

    bug 
    opened by TGw44 6
  • help with list_reply

    help with list_reply

    Hello, I have a question when I send a list of options (list_reply) and the user enters an "account status" option and then enters the document number. How do I get that value going through the previous validations again?

    image

    how to use 
    opened by kev095 4
  • hi i got this error

    hi i got this error

    Unsupported post request. Object with ID 'XXXXXXXXX' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api

    Object with ID is YOUR_WHATSAPP_BUSINESS_ACCOUNT_ID

    how to use 
    opened by razordouble7 4
  • I can't send a list

    I can't send a list

    I do not know how to do it

    let sections = [{
                "title": "Afternoon slots",
                "rows": [{"id": "1",
                        "title": "13:00",
                        "description": "Collection: Crouch End Bakery"
                    },
                    {"id": "2",
                        "title": "13:30",
                        "description": "Collection: Hampstead Bakery"
                    },
                    {"id": "3",
                        "title": "13:00",
                        "description": "Collection: Hampstead Bakery"
                    }
                ]
            },
            {
                "title": "Evening slots",
                "rows": [{"id": "4",
                        "title": "18:00",
                        "description": "Collection: Crouch End Bakery"
                    },
                    {"id": "5",
                        "title": "18:30",
                        "description": "Collection: Hampstead Bakery"
                    },
                    {"id": "6",
                        "title": "17:00",
                        "description": "Collection: Crouch End Bakery"
                    }
                ]
            }
        ];
    const result4 = await bot.sendList(to, 'asdf', 'fdsa', sections, '');
    

    what is the mistake?

    opened by jkupovic 2
  • Deno support

    Deno support

    Nice work. I was wondering, any plans to add Deno support? Similar to grammY maybe? Can see an example here: https://github.com/grammyjs/examples/blob/main/supabase-edge-functions/supabase/functions/telegram-bot/index.ts

    good first issue 
    opened by thorwebdev 2
  • Adding gulp as a task runner

    Adding gulp as a task runner

    This PR adds gulp and a couple of its plugins to automate some of the tasks specified in package.json You can then have the option of adding further tasks and compilation options without changing much of what is in the package.jsin file

    I have disabled the test task for now as several tests are failing at the moment

    opened by nyandika 1
  • Add try-catch for failing tests

    Add try-catch for failing tests

    Some tests currently fail with no error and just throws an empty string, unless you use a try-catch statement. Need to fix this in the main code, but for now, can simply add a try-catch in the tests to know why the test failed.

    e.g. image

    enhancement 
    opened by tawn33y 1
  • how to pass variables

    how to pass variables

    for(let i=0;i<2;i++){ const result = await bot.sendTemplate(to[i], 'charge_alert', 'en_US', [ { "type": "body", "parameters": [{ "type": "text", "text": {me} }, { "type": "text", "text": {friend} }, { "type": "text", "text": {msg}

                        }
                 ]
       }
    ])
    

    }

    } catch (err) { console.log(err); }

    #All works fine except when variable are passed it does't work

    how to use 
    opened by AlfaDigitals 1
  • possible error when adding routes

    possible error when adding routes

    Hi, I'm starting the following:

    const { createBot } = require('whatsapp-cloud-api'); const axios = require('axios'); const express = require('express');

    const app = express();

    const from = process.env.WHATSAPP_PHONE_NUMBER_ID; const token = process.env.WHATSAPP_TOKEN; const webhookVerifyToken = process.env.VERIFY_TOKEN;

    // Create a bot that can send messages const bot = createBot(from, token); (async function() { await bot.startExpressServer({ webhookVerifyToken: process.env.VERIFY_TOKEN, port: process.env.PORT || 2040, webhookPath: /webhook, }); })();

    app.get('/hello', (req, res) => { res.send('Hello World!') }) but when consulting the /hello route it gives me 404 as a result, is there an error with the route handler? thank you

    opened by KevinJoseph 6
  • ERR_UNHANDLED_REJECTION when trying to receive the Message from the bot

    ERR_UNHANDLED_REJECTION when trying to receive the Message from the bot

    Hi Everyone, currently Im trying to receive "Received your text message!" that the bot sends when receives a message.

    Right now I'm receiving start message when I start the server. But when trying to send the message, I got this output.

    image

    Right now My code is this ->

    ` const { createBot } = require('whatsapp-cloud-api');

    (async () => { try { // replace the values below const from = ""; const token = ""; const to = ""; // const to = "524426581099"; const webhookVerifyToken = "";

    // Create a bot that can send messages
    const bot = createBot(from, token);
    
    // Send text message
    const result = await bot.sendText(to, "Hello world");
    
    // Start express server to listen for incoming messages
    // NOTE: See below under `Documentation/Tutorial` to learn how
    // you can verify the webhook URL and make the server publicly available
    await bot.startExpressServer({
      webhookVerifyToken,
    });
    
    // Listen to ALL incoming messages
    // NOTE: remember to always run: await bot.startExpressServer() first
    bot.on("message", async (msg) => {
      console.log(msg);
    
      if (msg.type === "text") {
        await bot.sendText(msg.from, "Received your text message!");
      } else if (msg.type === "image") {
        await bot.sendText(msg.from, "Received your image!");
      }
    });
    

    } catch (err) { console.log(err); } })(); `

    question 
    opened by Mizar-Contasti 1
  • sendSticker fails to send without throwing error

    sendSticker fails to send without throwing error

    i am able to successfully SendText and SendVideo, however bot.sendSticker, using the url of a webp file fails:

    try{ await bot.sendSticker(from, msgUrl); console.log(sticker sent); res.status(200).send('Sticker Sent'); }catch(err){ console.log(get/sendsticker error:,err); res.status(200).send({message:'Error sending Sticker',"to":from,"text":msgText}); }

    Results: no error is thrown, "sticker sent" displayed, but the sticker is not sent to my whatsapp ....
    using url: https://pelicansecured.com/mobilemenu/assets/imgs/delivery_on_the_way.webp

    help wanted 
    opened by mrkencable 2
  • Pull Request for trying to read status response

    Pull Request for trying to read status response

    • Added 'Status' types increateBot.types.ts according to https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks/components
    • Changed on callback parameter to also accept Status
    • Will now publish 'status' and '<status-type>' to PubSub when receiving only status
    • Add new tests to also test for the statuses.

    image

    • In addition, also added the log() function to console.log to a log.txt in root directory for debugging purposes (can be removed)
    opened by alfonsusac 1
  • I seem to always get 2 failed tests when running `npm t`

    I seem to always get 2 failed tests when running `npm t`

    Hello, I tried to clone this repository to work on adding the status feature. But i cannot seem to get npm t running.

    This is the result

     FAIL  dist/createBot.test.js (37.59 s)
      send functions
        √ sends text (628 ms)
        √ sends message (502 ms)
        √ sends image (580 ms)
        √ sends document (553 ms)
        √ sends audio (610 ms)
        √ sends video (522 ms)
        √ sends sticker (654 ms)
        √ sends location (517 ms)
        √ sends template (589 ms)
        √ sends contacts (508 ms)
        √ sends reply button (612 ms)
        √ sends list (540 ms)
      server functions
        √ invalid webhook token (37 ms)
        × verify webhook token (3 ms)
        √ send invalid body (16 ms)
        × listen for new messages (30014 ms)
    
      ● server functions › verify webhook token
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        connect ECONNREFUSED 127.0.0.1:80
    
    
    
      ● server functions › listen for new messages
    
        thrown: "Exceeded timeout of 30000 ms for a test.
        Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
    
          265 |
          266 |   // eslint-disable-next-line no-async-promise-executor
        > 267 |   test('listen for new messages', (): Promise<void> => new Promise(async (resolve, reject) => {
              |   ^
          268 |     const payloads = [
          269 |       {
          270 |         from: '12345678',
    
          at src/createBot.test.ts:267:3
          at Object.<anonymous> (src/createBot.test.ts:194:1)
    
    Test Suites: 1 failed, 1 total
    Tests:       2 failed, 14 passed, 16 total
    Snapshots:   0 total
    Time:        37.783 s, estimated 39 s
    Ran all test suites matching /dist/i.
    

    I tried using various webhook_path but it seem to keep getting 403 (forbidden) Here is my webhook path

    WEBHOOK_PATH="http://localhost:3000/webhook/whatsapp"
    

    I also tried manually using rest api

    GET http://localhost:3000/webhook/whatsapp?hub.mode=subscribe&hub.challenge=random&hub.verify_token=41ESBjuy5E
    

    But gets 403 Forbidden instead.

    I am running on Windows 10.

    I also want to know what WEBHOOK_PATH do you use?

    question 
    opened by alfonsusac 3
Releases(v0.2.6)
  • v0.2.6(Sep 2, 2022)

  • v0.2.5(Jul 23, 2022)

    • Reduced bundle size by removing unnecessary files/folders from build.
    • Repaired broken packages by fixing failing husky issues.
    • Unpublished v0.2.2...v0.2.4 (broken packages).
    • Add steps to do local package build & test it.
    Source code(tar.gz)
    Source code(zip)
  • v0.2.1(Jul 23, 2022)

  • v0.2.0(Jul 8, 2022)

  • v0.1.0(Jun 18, 2022)

    What's new

    Stable release. No changes.

    API

    • createBot(fromPhoneNumberId, accessToken, version)
      • sendMessage(to, text, [options])
      • sendImage(to, urlOrObjectId, [options])
      • sendDocument(to, urlOrObjectId, [options])
      • sendAudio(to, urlOrObjectId)
      • sendVideo(to, urlOrObjectId, [options])
      • sendSticker(to, urlOrObjectId)
      • sendLocation(to, latitude, longitude, [options])
      • sendTemplate(to, name, languageCode, [components])
      • sendContacts(to, contacts)
      • sendReplyButtons(to, bodyText, buttons, [options])
      • sendList(to, buttonName, bodyText, sections, [options])

    Contributors

    Source code(tar.gz)
    Source code(zip)
  • v0.1.0-beta(Jun 18, 2022)

  • v0.1.0-alpha.2(Jun 7, 2022)

    Utilizes a more cleaner API:

    • createBot(fromPhoneNumberId, accessToken, version)
      • sendMessage(to, text, [options])
      • sendImage(to, urlOrObjectId, [options])
      • sendDocument(to, urlOrObjectId, [options])
      • sendAudio(to, urlOrObjectId)
      • sendVideo(to, urlOrObjectId, [options])
      • sendSticker(to, urlOrObjectId)
      • sendLocation(to, latitude, longitude, [options])
      • sendTemplate(to, name, languageCode, [components])
      • sendContacts(to, contacts)
      • sendReplyButtons(to, bodyText, buttons, [options])
      • sendList(to, buttonName, bodyText, sections, [options])
    Source code(tar.gz)
    Source code(zip)
  • v0.1.0-alpha(Jun 7, 2022)

    Minimum first version. Contains basic functions such as:

    const bot = createBot();
    
    bot.sendText()
    bot.sendMedia()
    bot.sendLocation()
    bot.sendContacts()
    bot.sendInteractive()
    bot.sendTemplate()
    
    Source code(tar.gz)
    Source code(zip)
Owner
Tony
I'm a Software Engineer on a journey to create the things I wish existed. He/him.
Tony
A javascript based whatsapp bot for downloading and sending media from youtube and facebook in different formats alongwith couple of other features.

Whatsmazan Available Features Downlaod youtube mp4 Video and send Downlaod youtube mp3 audio and send Search something from youtube Downlaod facebook

mazan labeeb 10 Oct 30, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
WhatsApp Bots With Library Baileys-MD

Family-Bot Join Group Diskusi NO BOT UNTUK PENGGUNA WINDOWS/VPS/RDP Unduh & Instal Git Klik Disini Unduh & Instal NodeJS Klik Disini Unduh & Instal FF

Fokus ID 82 Dec 29, 2022
An easy-to-use library that provide acronymous sending on form changes

Form Async Form Async is an easy-to-use library that provide acronymous sending on form changes. It's a great solution to preventing data loss when fi

Marc-Antoine Loignon 3 Jan 5, 2022
A framewok for building efficient and scalable, cross-platform bots (WhatsApp, Discord, Telegram and more) in a single codebase

project... An over-engineered all-in-one bot framewok for building efficient and scalable bots. Yep that's not a typo u heard it right "scalable bots"

Shubham Badgujar 6 Dec 24, 2022
kakaolink-plugin is a remote-kakao plugin for sending KakaoLinks instead of plain text

kakaolink-plugin Discord Server About kakaolink-plugin is a remote-kakao plugin for sending KakaoLinks instead of plain text. Requirements Node.js v17

null 5 Oct 1, 2022
An application for sending webhooks on Discord.

Cordhook ?? Cordhook is an application for sending webhooks on Discord with ease. ?? Built with Tauri for desktop and Next.js for web. ?? Styled with

Marin Heđeš 5 Jan 4, 2023
This package creates embeds and buttons in a very simple way using the whatsapp-web.js module for whatsapp

This package creates embeds and buttons in a very simple way using the whatsapp-web.js module for whatsapp

DeathAbyss 17 Jan 3, 2023
Zero Two Bot,A fully Modular Whatsapp Bot to do everything possible in WhatsApp by Team Zero Two

?? ???????? ?????? ???? ?? A Moduler WhatsApp Bot designed for both PM and Groups - To take your boring WhatsApp usage into a whole different level. T

Sam Pandey 69 Dec 25, 2022
A library for controlling the Minecraft Console Client and making bots for it in JavaScript/TypeScript.

MCC.jS About A work in progress JavaScript/TypeScript library for remote control and bot creation for the Minecraft Console Client using RPC over WebS

Anon 2 Sep 14, 2022
auto-vote-topgg automates voting for bots on top.gg using google chrome!

auto-vote-topgg auto-vote-topgg automates voting for bots on top.gg using google chrome! uses your account thats already logged into top.gg you must b

Anonymous 2 Jan 29, 2022
Store data using zero width spaces! Might be useful for discord bots.

ZWSP Store data using zero width spaces! Might be useful for discord bots. Installation npm i zwsp Usage Import the library: import { encode, decode}

Xaro 8 Dec 12, 2022
awsrun 189 Jan 3, 2023
OBL is a free, libre and open source botlist for Discord, Revolt, Telegram and Guilded. No nfts,no web3,no daos. only bots lol

OBL (aka OpenBotList) Obl is a free,libre and open source botlist for Discord, Revolt, Telegram and Guilded that has free bananas ( Revolt, Telegram a

OpenBotList Foundation 10 Sep 26, 2022
Util for kafkajs to buffer messages and send them in batches, inspired by node-rdkafka

kafkjajs-buffer Plugin for kafkajs to buffer messages and send them in batches, inspired by node-rdkafka Overview kafkajs-buffer adds queue/buffer cap

Alberto Juan 7 Sep 7, 2022
Mixed Messages is a simple Node.js application, that will print a randomized fake fact to the terminal each time it is ran.

Mixed Messages - Fake Fact Generator Mixed Messages is a simple Node.js application, That will print a randomized fake fact to the terminal each time

Parietic 2 Jan 10, 2022
Examples and challenges of my video about Creating and testing a complete Node.js Rest API (Without frameworks)

Building a complete Node.js WebApi + testing with no frameworks Welcome, this repo is part of my youtube video about Creating and testing a complete N

Erick Wendel 120 Dec 23, 2022