npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@rahullanjewar93/whatsapp-api-js

v2.1.0-1

Published

A TypeScript server agnostic Whatsapp's Official API framework

Downloads

3

Readme

whatsapp-api-js v2

npm Contributors

A TypeScript server agnostic Whatsapp's Official API framework.

List of contents

Set up

First, you need a Facebook app with the Whatsapp API activated. You can create your first app following this steps. Get the API token, either a temporal or a permanent one.

In your server you can install the module using npm:

npm install whatsapp-api-js

Now you can write code like this:

import WhatsAppAPI from "whatsapp-api-js";
import { Text, Image, Document } from "whatsapp-api-js/messages";
import * as Contacts from "whatsapp-api-js/messages/contacts";

// Kind reminder to not hardcode your token and secret
const TOKEN = "YOUR_TOKEN";
const APP_SECRET = "YOUR_SECRET";

const Whatsapp = new WhatsAppAPI({ token: TOKEN, appSecret: APP_SECRET });

// Assuming post is called on a POST request to your server
function post(e) {
    // The handlers work with any framework, as long as you pass the correct data
    // You can also use one of the middlewares provided in the package, keep reading
    return Whatsapp.post(
        JSON.parse(e.data),
        e.data,
        e.headers["x-hub-signature-256"]
    );
}

Whatsapp.on.message = async ({ phoneID, from, message, name }) => {
    console.log(
        `User ${name} (${from}) sent to bot ${phoneID} ${JSON.stringify(
            message
        )}`
    );

    let promise;

    if (message.type === "text") {
        promise = Whatsapp.sendMessage(
            phoneID,
            from,
            new Text(`*${name}* said:\n\n${message.text.body}`),
            message.id
        );
    }

    if (message.type === "image") {
        promise = Whatsapp.sendMessage(
            phoneID,
            from,
            new Image(message.image.id, true, `Nice photo, ${name}`)
        );
    }

    if (message.type === "document") {
        promise = Whatsapp.sendMessage(
            phoneID,
            from,
            new Document(message.document.id, true, undefined, "Our document")
        );
    }

    if (message.type === "contacts") {
        promise = Whatsapp.sendMessage(
            phoneID,
            from,
            new Contacts.Contacts(
                [
                    new Contacts.Name(name, "First name", "Last name"),
                    new Contacts.Phone(phone),
                    new Contacts.Birthday("2022", "04", "25")
                ],
                [
                    new Contacts.Name("John", "First name", "Last name"),
                    new Contacts.Organization("Company", "Department", "Title"),
                    new Contacts.Url("https://www.google.com", "WORK")
                ]
            )
        );
    }

    console.log(
        (await promise) ??
            "There are more types of messages, such as locations, templates, interactive, reactions and all the other media types."
    );

    Whatsapp.markAsRead(phoneID, message.id);
};

Whatsapp.on.sent = ({ phoneID, to, message }) => {
    console.log(`Bot ${phoneID} sent to user ${to} ${message}`);
};

To receive the post requests on message, you must setup the webhook at your Facebook app.

Back in the dashboard, click on WhatsApp > Settings, and setup the webhook URL. While setting it up, you will be asked for a Verify Token. This can be any string you want.

The package also has a GET wizard for the webhook authentication:

import WhatsAppAPI from "whatsapp-api-js";

const TOKEN = "YOUR_TOKEN";
const APP_SECRET = "YOUR_SECRET";
const VERIFY_TOKEN = "YOUR_VERIFY_TOKEN";

const Whatsapp = new WhatsAppAPI({
    token: TOKEN,
    appSecret: APP_SECRET,
    webhookVerifyToken: VERIFY_TOKEN
});

// Assuming get is called on a GET request to your server
function get(e) {
    return Whatsapp.get(e.query);
}

Once you are done, click the administrate button, and subscribe to the messages event.

And that's it! Now you have a functioning Whatsapp Bot connected to your server. For more information on the setup process for specific runtimes and frameworks, check out the Environments.md file.

Examples and Tutorials

There are a few examples that cover how to create each type of message, and how to use the basic methods of the library.

Check them out in the examples folder.

Types

The library is fully typed. Most types are available by importing /types or /emitters :

import { GetParams, PostData } from "whatsapp-api-js/types";
import { OnMessage, OnSent, OnStatus } from "whatsapp-api-js/emitters";

Changelog

To know what changed between updates, check out the releases on Github.

Documentation

The latest release documentation is available in whatsappapijs.web.app, and previous versions are available in secreto31126.github.io/whatsapp-api-js.

Contributors

Emoji key ✨

Contributions

If you have some free time and really want to improve the library or fix dumb bugs, feel free to read CONTRIBUTING.md file.

Breaking changes

You can get a full list of breaking changes in the BREAKING.md file.

Beta releases

Install the latest beta release with npm install whatsapp-api-js@beta. As any beta, it is 110% likely to break. I also use this tag to test npm releases. Use it at your own risk.