diff --git a/README.md b/README.md index 7dcadd1..69663b1 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,38 @@ # whatsapp-api-client library for javascript -[![build](/~https://github.com/green-api/whatsapp-api-client/workflows/build_library/badge.svg)](/~https://github.com/green-api/whatsapp-api-client/actions/workflows/build_library.yml) -[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](/~https://github.com/green-api/whatsapp-api-client/blob/master/LICENSE) -[![GitHub release](https://img.shields.io/github/v/release/green-api/whatsapp-api-client.svg)](/~https://github.com/green-api/whatsapp-api-client/releases) -[![npm version](https://badge.fury.io/js/%40green-api%2Fwhatsapp-api-client.svg)](https://www.npmjs.com/package/@green-api/whatsapp-api-client) +![](https://img.shields.io/badge/license-CC%20BY--ND%204.0-green) +![](https://img.shields.io/npm/v/%40green-api%2Fwhatsapp-api-client) +![](https://img.shields.io/github/actions/workflow/status/green-api/whatsapp-api-client-js/build.yml) +![](https://img.shields.io/npm/dm/%40green-api%2Fwhatsapp-api-client) -- [English documentation](README.md) -- [Документация на русском языке](README_RUS.md) +## Support links -This library helps you easily create a javascript application to connect the WhatsApp API using service [green-api.com](https://green-api.com/en). You need to get `ID_INSTANCE`and `API_TOKEN_INSTANCE` in the [control panel](https://console.green-api.com) in order to use this library. It's free for developers. +[![Support](https://img.shields.io/badge/support@green--api.com-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:support@greenapi.com) +[![Support](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/greenapi_support_eng_bot) +[![Support](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://wa.me/77273122366) + +## Guides & News + +[![Guides](https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white)](https://www.youtube.com/@greenapi-en) +[![News](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/green_api) +[![News](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://whatsapp.com/channel/0029VaLj6J4LNSa2B5Jx6s3h) + +- [Документация на русском языке](/~https://github.com/green-api/whatsapp-api-client-js/blob/master/docs/README.md). + +This library helps you easily create a javascript application to connect the WhatsApp API using +service [green-api.com](https://green-api.com/en). You need to get `ID_INSTANCE`and `API_TOKEN_INSTANCE` in +the [control panel](https://console.green-api.com) in order to use this library. It's free for developers. ## API -The API corresponds with [REST API](https://green-api.com/en/docs/api/) from green-api since the library wraps own methods as https calls to the service. Therefore using these [docs](https://green-api.com/en/docs/) is highly encouraged. +The API corresponds with [REST API](https://green-api.com/en/docs/api/) from green-api since the library wraps own +methods as https calls to the service. Therefore, using these [docs](https://green-api.com/en/docs/) is highly +encouraged. ## Installing -Library supports both browser environment without package managers and Node/Webpack apps with package manager that can handle `require` or `import` module expressions. +Library supports both browser environment without package managers and Node/Webpack apps with package manager that can +handle `require` or `import` module expressions. For webpack and npm based apps: ``` @@ -26,40 +42,52 @@ npm i @green-api/whatsapp-api-client For vanilla html-js website modify index.html: ```html + ``` -## Importing +## Importing There are several ways to import the library in a project -Using common javascript +Using common javascript + ``` const whatsAppClient = require("@green-api/whatsapp-api-client"); ``` -Using ES6 javascript + +Using ES6 javascript + ``` import whatsAppClient from "@green-api/whatsapp-api-client"; ``` -Using typescript + +Using typescript + ``` import * as whatsAppClient from "@green-api/whatsapp-api-client"; ``` -Using browser javascript +Using browser javascript + ``` ``` -## Authentification +## Authentication -Sending WhatsApp message like any other call to the API requires account registered on [green-api.com](https://green-api.com/en) and authentication completed on mobile WhatsApp app. To register account you have to proceed to the [control panel](https://console.green-api.com/). After registering you wll get own unique pair of `ID_INSTANCE` and `API_TOKEN_INSTANCE` keys. +Sending WhatsApp message like any other call to the API requires account registered +on [green-api.com](https://green-api.com/en) and authentication completed on mobile WhatsApp app. To register account +you have to proceed to the [control panel](https://console.green-api.com/). After registering you wll get own unique +pair of `ID_INSTANCE` and `API_TOKEN_INSTANCE` keys. -WhatsApp mobile app authentication may be achived by using [control panel](https://console.green-api.com/). You need to scan QR-code generated within the control panel. +WhatsApp mobile app authentication may be achieved by using [control panel](https://console.green-api.com/). You need to +scan QR-code generated within the control panel. ## Examples -Please do not use 'phoneNumber' parameter when calling methods. It is deprecated. Examples below are based on 'chatId' paramemeter +Please do not use 'phoneNumber' parameter when calling methods. It is deprecated. Examples below are based on 'chatId' +parameter ### Send WhatsApp message @@ -69,56 +97,59 @@ Use common javascript const whatsAppClient = require("@green-api/whatsapp-api-client"); const restAPI = whatsAppClient.restAPI({ - idInstance: "YOUR_ID_INSTANCE", - apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", + idInstance: "YOUR_ID_INSTANCE", + apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", }); -restAPI.message.sendMessage("79999999999@c.us", null , "hello world").then((data) => { - console.log(data); +restAPI.message.sendMessage("79999999999@c.us", null, "hello world").then((data) => { + console.log(data); }); ``` or use browser js script ```html + ``` -Or use ES6 syntax. For node js app, you propably have to add in `package.json` property `"type": "module"`. Notice that all examples below are ES6 based. +Or use ES6 syntax. For Node.js app, you probably have to add in `package.json` property `"type": "module"`. Notice that +all examples below are ES6 based. ```js import whatsAppClient from "@green-api/whatsapp-api-client"; (async () => { - const restAPI = whatsAppClient.restAPI({ - idInstance: "YOUR_ID_INSTANCE", - apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", - }); - const response = await restAPI.message.sendMessage( - "79999999999@c.us", - null, - "hello world" - ); + const restAPI = whatsAppClient.restAPI({ + idInstance: "YOUR_ID_INSTANCE", + apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", + }); + const response = await restAPI.message.sendMessage( + "79999999999@c.us", + null, + "hello world" + ); })(); ``` -### Using credentials file for `ID_INSTANCE` and `API_TOKEN_INSTANCE` keys (nodejs only!) +### Using credentials file for `ID_INSTANCE` and `API_TOKEN_INSTANCE` keys (Node.js only!) -You might want to store yours credentials separatedly from code. The library allow you to create a text file with preferred name and location with the format: +You might want to store yours credentials separately from code. The library allow you to create a text file with +preferred name and location with the format: ``` API_TOKEN_INSTANCE = "MY_API_TOKEN_INSTANCE" @@ -129,7 +160,7 @@ And then pass this file as described below: ```js const restAPI = whatsAppClient.restAPI({ - credentialsPath: "examples\\credentials", + credentialsPath: "examples\\credentials", }); ``` @@ -139,29 +170,29 @@ const restAPI = whatsAppClient.restAPI({ import whatsAppClient from "@green-api/whatsapp-api-client"; (async () => { - let restAPI = whatsAppClient.restAPI({ - idInstance: "YOUR_ID_INSTANCE", - apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", - }); - - try { - // Receive WhatsApp notifications. - console.log("Waiting incoming notifications..."); - await restAPI.webhookService.startReceivingNotifications(); - restAPI.webhookService.onReceivingMessageText((body) => { - console.log(body); - restAPI.webhookService.stopReceivingNotifications(); - //console.log("Notifications is about to stop in 20 sec if no messages will be queued...") + let restAPI = whatsAppClient.restAPI({ + idInstance: "YOUR_ID_INSTANCE", + apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", }); - restAPI.webhookService.onReceivingDeviceStatus((body) => { - console.log(body); - }); - restAPI.webhookService.onReceivingAccountStatus((body) => { - console.log(body); - }); - } catch (ex) { - console.error(ex.toString()); - } + + try { + // Receive WhatsApp notifications. + console.log("Waiting incoming notifications..."); + await restAPI.webhookService.startReceivingNotifications(); + restAPI.webhookService.onReceivingMessageText((body) => { + console.log(body); + restAPI.webhookService.stopReceivingNotifications(); + //console.log("Notifications is about to stop in 20 sec if no messages will be queued...") + }); + restAPI.webhookService.onReceivingDeviceStatus((body) => { + console.log(body); + }); + restAPI.webhookService.onReceivingAccountStatus((body) => { + console.log(body); + }); + } catch (ex) { + console.error(ex.toString()); + } })(); ``` @@ -171,23 +202,24 @@ import whatsAppClient from "@green-api/whatsapp-api-client"; import whatsAppClient from "@green-api/whatsapp-api-client"; (async () => { - const restAPI = whatsAppClient.restAPI({ - idInstance: "YOUR_ID_INSTANCE", - apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", - }); - const response = await restAPI.file.sendFileByUrl( - "79999999999@c.us", - null, - "https://avatars.mds.yandex.net/get-pdb/477388/77f64197-87d2-42cf-9305-14f49c65f1da/s375", - "horse.png", - "horse" - ); + const restAPI = whatsAppClient.restAPI({ + idInstance: "YOUR_ID_INSTANCE", + apiTokenInstance: "YOUR_API_TOKEN_INSTANCE", + }); + const response = await restAPI.file.sendFileByUrl( + "79999999999@c.us", + null, + "https://avatars.mds.yandex.net/get-pdb/477388/77f64197-87d2-42cf-9305-14f49c65f1da/s375", + "horse.png", + "horse" + ); })(); ``` ### Send WhatsApp message and receive webhook -Webhooks are event-based callbacks invoked by green-api server as responses to client API calls. Webhooks support node js and express based apps only. +Webhooks are event-based callbacks invoked by green-api server as responses to client API calls. Webhooks support +Node.js and express based apps only. ```js import whatsAppClient from "@green-api/whatsapp-api-client"; @@ -195,56 +227,58 @@ import express from "express"; import bodyParser from "body-parser"; (async () => { - try { - // Set http url, where webhooks are hosted. - // Url must have public domain address. - await restAPI.settings.setSettings({ - webhookUrl: "MY_HTTP_SERVER:3000/webhooks", - }); - - const app = express(); - app.use(bodyParser.json()); - const webHookAPI = whatsAppClient.webhookAPI(app, "/webhooks"); - - // Subscribe to webhook happened when WhatsApp delivered a message - webHookAPI.onIncomingMessageText( - (data, idInstance, idMessage, sender, typeMessage, textMessage) => { - console.log(`outgoingMessageStatus data ${data.toString()}`); - } - ); - - // Run web server with public domain address - app.listen(3000, async () => { - console.log(`Started. App listening on port 3000!`); - - const restAPI = whatsAppClient.restAPI({ - idInstance: MY_ID_INSTANCE, - apiTokenInstance: MY_API_TOKEN_INSTANCE, - }); - // Send test message that triggers webhook - const response = await restAPI.message.sendMessage( - "79999999999@c.us", - null, - "hello world" - ); - }); - } catch (error) { - console.error(error); - process.exit(1); - } + try { + // Set http url, where webhooks are hosted. + // Url must have public domain address. + await restAPI.settings.setSettings({ + webhookUrl: "MY_HTTP_SERVER:3000/webhooks", + }); + + const app = express(); + app.use(bodyParser.json()); + const webHookAPI = whatsAppClient.webhookAPI(app, "/webhooks"); + + // Subscribe to webhook happened when WhatsApp delivered a message + webHookAPI.onIncomingMessageText( + (data, idInstance, idMessage, sender, typeMessage, textMessage) => { + console.log(`outgoingMessageStatus data ${data.toString()}`); + } + ); + + // Run web server with public domain address + app.listen(3000, async () => { + console.log(`Started. App listening on port 3000!`); + + const restAPI = whatsAppClient.restAPI({ + idInstance: MY_ID_INSTANCE, + apiTokenInstance: MY_API_TOKEN_INSTANCE, + }); + // Send test message that triggers webhook + const response = await restAPI.message.sendMessage( + "79999999999@c.us", + null, + "hello world" + ); + }); + } catch (error) { + console.error(error); + process.exit(1); + } })(); ``` -There's some cool [examples too](examples/). +There's some cool [examples too](examples). ## Deploying development environment -Any help with development and bug fixing is appreciated. In order to deploy test-ready environment please make the steps: +Any help with development and bug fixing is appreciated. In order to deploy test-ready environment please make the +steps: -1. Сlone repo with `git clone` +1. Clone repo with `git clone` 2. Install dependencies with `npm install` 3. Install globally libraries `rollup` for bundled builds. -4. Add webhooks as new dev express via npm `npm install express --save-dev`. Dont forget to delete it before making pull request +4. Add webhooks as new dev express via npm `npm install express --save-dev`. Don't forget to delete it before making + pull request 5. Create .env file in root folder and add environment variables using example file [env.example](env.example) 6. Add `"type": "module"` to the package.json diff --git a/README_RUS.md b/docs/README.md similarity index 63% rename from README_RUS.md rename to docs/README.md index 594b2d9..7c14b78 100644 --- a/README_RUS.md +++ b/docs/README.md @@ -1,59 +1,88 @@ # whatsapp-api-client library for javascript -* [![build](/~https://github.com/green-api/whatsapp-api-client/workflows/build_library/badge.svg)](/~https://github.com/green-api/whatsapp-api-client/actions/workflows/build_library.yml) -[![License](https://img.shields.io/badge/License-MIT-yellow.svg)](/~https://github.com/green-api/whatsapp-api-client/blob/master/LICENSE) -[![GitHub release](https://img.shields.io/github/v/release/green-api/whatsapp-api-client.svg)](/~https://github.com/green-api/whatsapp-api-client/releases) -- [English documentation](README.md) -- [Документация на русском языке](README_RUS.md) +![](https://img.shields.io/badge/license-CC%20BY--ND%204.0-green) +![](https://img.shields.io/npm/v/%40green-api%2Fwhatsapp-api-client) +![](https://img.shields.io/github/actions/workflow/status/green-api/whatsapp-api-client-js/build.yml) +![](https://img.shields.io/npm/dm/%40green-api%2Fwhatsapp-api-client) -Javascript библиотека для интеграции с мессенджером WhatsAPP через API сервиса [green-api.com](https://green-api.com)ю Чтобы воспользоваться библиотекой нужно получить регистрационный токен и id аккаунта в [личном кабинете](https://console.green-api.com/). Есть бесплатный тариф аккаунта разработчика. +## Поддержка + +[![Support](https://img.shields.io/badge/support@green--api.com-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:support@green-api.com) +[![Support](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/greenapi_support_ru_bot) +[![Support](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://wa.me/79993331223) + +## Руководства и новости + +[![Guides](https://img.shields.io/badge/YouTube-%23FF0000.svg?style=for-the-badge&logo=YouTube&logoColor=white)](https://www.youtube.com/@green-api) +[![News](https://img.shields.io/badge/Telegram-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white)](https://t.me/green_api) +[![News](https://img.shields.io/badge/WhatsApp-25D366?style=for-the-badge&logo=whatsapp&logoColor=white)](https://whatsapp.com/channel/0029VaHUM5TBA1f7cG29nO1C) + +Javascript библиотека для интеграции с мессенджером WhatsAPP через API сервиса [green-api.com](https://green-api.com). +Чтобы воспользоваться библиотекой, нужно получить регистрационный токен и id аккаунта +в [личном кабинете](https://console.green-api.com/). Есть бесплатный тариф аккаунта разработчика. ## API -Документация к REST API находится по [ссылке](https://green-api.com/docs/api/). Библиотека является оберткой к REST API, поэтому документация по ссылке выше применима и к самой библиотеке. +Документация к REST API находится по [ссылке](https://green-api.com/docs/api/). Библиотека является оберткой к REST API, +поэтому документация по ссылке выше применима и к самой библиотеке. ## Установка -Билиотека работает как на node >=10, так и на современных версиях браузеров chrome, firefox и др. Для приложений на webpack и npm установка выполняется через команду: +Библиотека работает как на node >=10, так и на современных версиях браузеров chrome, firefox и др. Для приложений на +webpack и npm установка выполняется через команду: + ``` npm i @green-api/whatsapp-api-client ``` -Для чистого html js сайта либу можно подключить в index.html + +Для чистого html js сайта библиотеку можно подключить в index.html + ``` html ``` -## Импорт +## Импорт Есть несколько способов импортировать библиотеку в проект -Используя классический javascript +Используя классический javascript + ``` const whatsAppClient = require("@green-api/whatsapp-api-client"); ``` -Используя ES6 javascript + +Используя ES6 javascript + ``` import whatsAppClient from "@green-api/whatsapp-api-client"; ``` -Используя typescript + +Используя typescript + ``` import * as whatsAppClient from "@green-api/whatsapp-api-client"; ``` -Используя браузерный javascript + +Используя браузерный javascript + ``` ``` -## Авторизация +## Авторизация -Чтобы отправить сообщение или выполнить другой метод Green-API, аккаунт WhatsApp в приложении телефона должен быть в авторизованном состоянии. Для авторизации аккаунта перейдите в [личный кабинет](https://console.green-api.com/) и сканируйте QR-код с использованием прилоения WhatsApp. +Чтобы отправить сообщение или выполнить другой метод Green-API, аккаунт WhatsApp в приложении телефона должен быть в +авторизованном состоянии. Для авторизации аккаунта перейдите в [личный кабинет](https://console.green-api.com/) и +сканируйте QR-код с использованием приложения WhatsApp. ## Примеры -Не испольуйте параметр 'phoneNumber' при вызове методов. Он устарел. Примеры ниже используют параметр 'chatId' +Не используйте параметр 'phoneNumber' при вызове методов. Он устарел. Примеры ниже используют параметр 'chatId' ### Отправка сообщения на номер WhatsApp + Используя common js + ``` js const whatsAppClient = require('@green-api/whatsapp-api-client') @@ -68,7 +97,9 @@ restAPI.message.sendMessage("79999999999@c.us", null, "hello world") }) ; ``` + или используя js script + ``` html ``` -Или можно воспользоваться синтаксисом ES6. Для того, чтобы этот синтаксис сработал в приложении на nodejs, нужно в package.json прописать ключ ``"type": "module"``. Далее все примеры будут на ES6 синтаксисе. + +Или можно воспользоваться синтаксисом ES6. Для того чтобы этот синтаксис сработал в приложении на nodejs, нужно в +package.json прописать ключ ``"type": "module"``. Далее все примеры будут на ES6 синтаксисе. ``` js import whatsAppClient from '@green-api/whatsapp-api-client' @@ -100,12 +133,16 @@ import whatsAppClient from '@green-api/whatsapp-api-client' ### Использование credentials файла для ключей `ID_INSTANCE` или `API_TOKEN_INSTANCE` (только для nodejs) -Вы можете сохранить Ваши авторизационные данные отдельно от кода.. Библиотека позволяет создать файл с произвольным именем и местом в следующем формате: +Вы можете сохранить Ваши авторизационные данные отдельно от кода. Библиотека позволяет создать файл с произвольным +именем и местом в следующем формате: + ``` API_TOKEN_INSTANCE = "MY_API_TOKEN_INSTANCE" ID_INSTANCE = "MY_ID_INSTANCE" ``` + А затем Вы можете передать ключи как показано в коде ниже: + ``` js const restAPI = whatsAppClient.restAPI(({ credentialsPath: "examples\\credentials" @@ -147,6 +184,7 @@ import whatsAppClient from '@green-api/whatsapp-api-client' ``` ### Отправка файла на номер WhatsApp + ``` js import whatsAppClient from '@green-api/whatsapp-api-client' @@ -159,9 +197,9 @@ import whatsAppClient from '@green-api/whatsapp-api-client' })(); ``` -### Пример использования вебхука +### Пример использования веб-хука -Вебхуки работают только в node js с на базе express +Веб-хуки работают только в node js на базе express ``` js import whatsAppClient from '@green-api/whatsapp-api-client' @@ -171,7 +209,7 @@ import bodyParser from 'body-parser'; (async () => { try { - // Устанавливаем http url ссылку, куда будут отправляться вебхуки. + // Устанавливаем http url ссылку, куда будут отправляться веб-хуки. // Ссылка должна иметь публичный адрес. await restAPI.settings.setSettings({ webhookUrl: 'MY_HTTP_SERVER:3000/webhooks' @@ -181,7 +219,7 @@ import bodyParser from 'body-parser'; app.use(bodyParser.json()); const webHookAPI = whatsAppClient.webhookAPI(app, '/webhooks') - // Подписываемся на событие вебхука при получении сообщения + // Подписываемся на событие веб-хука при получении сообщения webHookAPI.onIncomingMessageText((data, idInstance, idMessage, sender, typeMessage, textMessage) => { console.log(`outgoingMessageStatus data ${data.toString()}`) }); @@ -194,7 +232,7 @@ import bodyParser from 'body-parser'; idInstance: MY_ID_INSTANCE, apiTokenInstance: MY_API_TOKEN_INSTANCE })); - // Отправляем тестовое сообщение, для того чтобы сработали события вебхуков + // Отправляем тестовое сообщение, для того чтобы сработали события веб-хуков const response = await restAPI.message.sendMessage("79999999999@c.us", null, "hello world"); }); @@ -206,7 +244,7 @@ import bodyParser from 'body-parser'; ``` -Полный список примеров [здесь](examples). +Полный список примеров [здесь](../examples). ## Разворачивание окружения разработки @@ -215,11 +253,14 @@ import bodyParser from 'body-parser'; 1. Склонируйте репозиторий через git clone 2. Установите зависимости через npm install 3. Установите глобально библиотеку ``rollup`` для сборки. -4. Для вебхуков добавьте `express` как новую зависимость через npm -5. Создайте файл `.env` в рутовом каталоге и пропишите переменные окружения. Образец переменных в файле [env.example](env.example) +4. Для веб-хуков добавьте `express` как новую зависимость через npm +5. Создайте файл `.env` в рутовом каталоге и пропишите переменные окружения. Образец переменных в + файле [env.example](../env.example) ## Сборка -Скомпилировать как browser, так и node/webpack версии либы можно одной командой + +Скомпилировать как browser, так и node/webpack версии библиотеки можно одной командой + ``` npm run build ``` @@ -227,8 +268,8 @@ npm run build ## Сторонние продукты * [axios](/~https://github.com/axios/axios) - для http запросов -* [express](https://www.npmjs.com/package/express) - сервер приложений для вебхуков +* [express](https://www.npmjs.com/package/express) - сервер приложений для веб-хуков ## Лицензия -Лицензировано на условиях MIT. Смотрите файл [LICENSE](LICENSE) +Лицензировано на условиях MIT. Смотрите файл [LICENSE](../LICENSE)