@green-api/greenapi-integration 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -129,7 +129,7 @@ Handles message format conversion between GREEN-API and your platform.
129
129
 
130
130
  ```typescript
131
131
  abstract class MessageTransformer<TPlatformWebhook, TPlatformMessage> {
132
- abstract toPlatformMessage(webhook: IncomingGreenApiWebhook): TPlatformMessage;
132
+ abstract toPlatformMessage(webhook: GreenApiWebhook): TPlatformMessage;
133
133
 
134
134
  abstract toGreenApiMessage(message: TPlatformWebhook): Message;
135
135
  }
@@ -141,7 +141,7 @@ Interface for data persistence operations.
141
141
 
142
142
  ```typescript
143
143
  abstract class StorageProvider<TUser extends BaseUser = BaseUser, TInstance extends BaseInstance = Instance> {
144
- abstract createInstance(instance: BaseInstance, userId: bigint | number, settings?: Settings): Promise<TInstance>;
144
+ abstract createInstance(instance: BaseInstance, userId: bigint | number): Promise<TInstance>;
145
145
 
146
146
  abstract getInstance(idInstance: number | bigint): Promise<TInstance | null>;
147
147
 
@@ -285,11 +285,11 @@ Create a transformer that converts messages between your platform's format and G
285
285
 
286
286
  ```typescript
287
287
  // core/transformer.ts
288
- import { MessageTransformer, Message, IncomingGreenApiWebhook } from '@green-api/greenapi-integration';
288
+ import { MessageTransformer, Message, GreenApiWebhook } from '@green-api/greenapi-integration';
289
289
  import { YourPlatformWebhook, YourPlatformMessage } from '../types/types';
290
290
 
291
291
  export class YourTransformer extends MessageTransformer<YourPlatformWebhook, YourPlatformMessage> {
292
- toPlatformMessage(webhook: IncomingGreenApiWebhook): YourPlatformMessage {
292
+ toPlatformMessage(webhook: GreenApiWebhook): YourPlatformMessage {
293
293
  // Transform GREEN-API webhook to your platform format
294
294
  return {
295
295
  recipient: webhook.senderData.sender,
@@ -314,7 +314,7 @@ Create a storage provider to manage users and instances. You can use any databas
314
314
 
315
315
  ```typescript
316
316
  // core/storage.ts
317
- import { StorageProvider, BaseUser, BaseInstance, Settings } from '@green-api/greenapi-integration';
317
+ import { StorageProvider, BaseUser, Instance, Settings } from '@green-api/greenapi-integration';
318
318
  import { PrismaClient } from '@prisma/client'; // Or your database client
319
319
 
320
320
  export class YourStorage extends StorageProvider {
@@ -324,13 +324,13 @@ export class YourStorage extends StorageProvider {
324
324
  this.db = new PrismaClient();
325
325
  }
326
326
 
327
- async createInstance(instance: BaseInstance, userId: bigint, settings?: Settings) {
327
+ async createInstance(instance: Instance, userId: bigint) {
328
328
  return this.db.instance.create({
329
329
  data: {
330
330
  idInstance: instance.idInstance,
331
331
  apiTokenInstance: instance.apiTokenInstance,
332
332
  userId,
333
- settings: settings || {},
333
+ settings: instance.settings || {},
334
334
  },
335
335
  });
336
336
  }
@@ -357,7 +357,7 @@ export class YourAdapter extends BaseAdapter<YourPlatformWebhook, YourPlatformMe
357
357
  });
358
358
  }
359
359
 
360
- async sendToPlatform(message: YourPlatformMessage, instance: BaseInstance) {
360
+ async sendToPlatform(message: YourPlatformMessage, instance: Instance) {
361
361
  const client = await this.createPlatformClient(instance.config);
362
362
  await client.sendMessage(message);
363
363
  }
@@ -429,11 +429,12 @@ router.post('/instance', async (req, res) => {
429
429
 
430
430
  const instance = await adapter.createInstance({
431
431
  idInstance: Number(idInstance),
432
- apiTokenInstance
433
- }, {
434
- webhookUrl: `${process.env.APP_URL}/webhook/green-api`,
435
- webhookUrlToken: `token_${Date.now()}`, // In production, use a secure token generator
436
- incomingWebhook: 'yes'
432
+ apiTokenInstance,
433
+ settings: {
434
+ webhookUrl: `${process.env.APP_URL}/webhook/green-api`,
435
+ webhookUrlToken: `token_${Date.now()}`,
436
+ incomingWebhook: 'yes'
437
+ }
437
438
  }, userEmail);
438
439
 
439
440
  res.status(200).json({
@@ -509,7 +510,7 @@ bootstrap();
509
510
  "prepublishOnly": "npm run build"
510
511
  },
511
512
  "dependencies": {
512
- "@green-api/greenapi-integration": "^1.0.0",
513
+ "@green-api/greenapi-integration": "^0.4.0",
513
514
  "express": "^4.18.2"
514
515
  // other dependencies
515
516
  }
@@ -593,23 +594,33 @@ interface SimplePlatformMessage {
593
594
  ### simple-transformer.ts
594
595
 
595
596
  ```typescript
596
- import { MessageTransformer, Message, IncomingGreenApiWebhook, formatPhoneNumber } from 'greenapi-integration';
597
+ import {
598
+ MessageTransformer,
599
+ Message,
600
+ GreenApiWebhook,
601
+ formatPhoneNumber,
602
+ IntegrationError,
603
+ } from "@green-api/greenapi-integration";
604
+ import { SimplePlatformMessage, SimplePlatformWebhook } from "./types";
597
605
 
598
606
  export class SimpleTransformer extends MessageTransformer<SimplePlatformWebhook, SimplePlatformMessage> {
599
- toPlatformMessage(webhook: IncomingGreenApiWebhook): SimplePlatformMessage {
600
- if (webhook.messageData.typeMessage !== 'extendedTextMessage') {
601
- throw new Error('Only text messages are supported');
602
- }
607
+ toPlatformMessage(webhook: GreenApiWebhook): SimplePlatformMessage {
608
+ if (webhook.typeWebhook === "incomingMessageReceived") {
609
+ if (webhook.messageData.typeMessage !== "extendedTextMessage") {
610
+ throw new IntegrationError("Only text messages are supported", "BAD_REQUEST_ERROR", 400);
611
+ }
603
612
 
604
- return {
605
- to: webhook.senderData.sender,
606
- content: webhook.messageData.extendedTextMessageData?.text || '',
607
- };
613
+ return {
614
+ to: webhook.senderData.sender,
615
+ content: webhook.messageData.extendedTextMessageData?.text || "",
616
+ };
617
+ }
618
+ throw new IntegrationError("Only incomingMessageReceived type webhooks are supported", "INTEGRATION_ERROR", 500);
608
619
  }
609
620
 
610
621
  toGreenApiMessage(message: SimplePlatformWebhook): Message {
611
622
  return {
612
- type: 'text',
623
+ type: "text",
613
624
  chatId: formatPhoneNumber(message.from),
614
625
  message: message.text,
615
626
  };
@@ -620,25 +631,24 @@ export class SimpleTransformer extends MessageTransformer<SimplePlatformWebhook,
620
631
  ### simple-storage.ts
621
632
 
622
633
  ```typescript
623
- import { StorageProvider, BaseUser, BaseInstance, Settings } from 'greenapi-integration';
634
+ import { StorageProvider, BaseUser, Instance } from '@green-api/greenapi-integration';
624
635
 
625
636
  export class SimpleStorage extends StorageProvider {
626
637
  private users: Map<string, BaseUser> = new Map();
627
- private instances: Map<number, BaseInstance> = new Map();
638
+ private instances: Map<number, Instance> = new Map();
628
639
 
629
- async createInstance(instance: BaseInstance, userId: bigint, settings?: Settings): Promise<BaseInstance> {
640
+ async createInstance(instance: Instance, userId: bigint): Promise<Instance> {
630
641
  this.instances.set(Number(instance.idInstance), {
631
642
  ...instance,
632
- settings: settings || {}
633
643
  });
634
644
  return instance;
635
645
  }
636
646
 
637
- async getInstance(idInstance: number): Promise<BaseInstance | null> {
647
+ async getInstance(idInstance: number): Promise<Instance | null> {
638
648
  return this.instances.get(idInstance) || null;
639
649
  }
640
650
 
641
- async removeInstance(instanceId: number): Promise<BaseInstance> {
651
+ async removeInstance(instanceId: number): Promise<Instance> {
642
652
  const instance = this.instances.get(instanceId);
643
653
  if (!instance) throw new Error('Instance not found');
644
654
  this.instances.delete(instanceId);
@@ -668,7 +678,8 @@ export class SimpleStorage extends StorageProvider {
668
678
  ### simple-adapter.ts
669
679
 
670
680
  ```typescript
671
- import { BaseAdapter, BaseInstance } from "greenapi-integration";
681
+ import { BaseAdapter, Instance } from "@green-api/greenapi-integration";
682
+ import { SimplePlatformMessage, SimplePlatformWebhook } from "./types";
672
683
  import axios from 'axios';
673
684
 
674
685
  export class SimpleAdapter extends BaseAdapter<SimplePlatformWebhook, SimplePlatformMessage> {
@@ -682,7 +693,7 @@ export class SimpleAdapter extends BaseAdapter<SimplePlatformWebhook, SimplePlat
682
693
  });
683
694
  }
684
695
 
685
- async sendToPlatform(message: SimplePlatformMessage, instance: BaseInstance): Promise<void> {
696
+ async sendToPlatform(message: SimplePlatformMessage, instance: Instance): Promise<void> {
686
697
  // In a real implementation, we would send to the platform
687
698
  // For demo, we'll just log and simulate a response
688
699
  console.log('Platform received message:', message);
@@ -712,7 +723,7 @@ export class SimpleAdapter extends BaseAdapter<SimplePlatformWebhook, SimplePlat
712
723
  ```typescript
713
724
  import express from "express";
714
725
  import bodyParser from "body-parser";
715
- import { formatPhoneNumber, GreenApiClient } from "greenapi-integration";
726
+ import { formatPhoneNumber, GreenApiClient } from "@green-api/greenapi-integration";
716
727
  import { SimpleTransformer } from "./simple-transformer";
717
728
  import { SimpleStorage } from "./simple-storage";
718
729
  import { SimpleAdapter } from "./simple-adapter";
@@ -736,6 +747,7 @@ async function main() {
736
747
  idInstance: Number(process.env.AGENT_ID_INSTANCE),
737
748
  apiTokenInstance: process.env.AGENT_API_TOKEN!,
738
749
  };
750
+ console.log(visitorInstance, agentInstance);
739
751
 
740
752
  // Create visitor's GREEN-API client (for sending initial message)
741
753
  const visitorClient = new GreenApiClient(visitorInstance);
@@ -747,10 +759,12 @@ async function main() {
747
759
  name: "Agent",
748
760
  });
749
761
 
750
- const instance = await adapter.createInstance(agentInstance, {
751
- webhookUrl: process.env.WEBHOOK_URL + "/webhook/green-api",
752
- webhookUrlToken: "your-secure-token",
753
- incomingWebhook: "yes",
762
+ const instance = await adapter.createInstance({
763
+ idInstance: agentInstance.idInstance, apiTokenInstance: agentInstance.apiTokenInstance, settings: {
764
+ webhookUrl: process.env.WEBHOOK_URL + "/webhook/green-api",
765
+ webhookUrlToken: "your-secure-token",
766
+ incomingWebhook: "yes",
767
+ },
754
768
  }, user.email);
755
769
 
756
770
  console.log("Waiting 2 minutes for settings to apply...");
@@ -774,7 +788,7 @@ async function main() {
774
788
  });
775
789
 
776
790
  // Start the server
777
- const port = process.env.PORT || 3000;
791
+ const port = Number(process.env.PORT) || 3000;
778
792
  app.listen(port, () => {
779
793
  console.log(`Webhook server listening on port ${port}`);
780
794
  });
@@ -817,7 +831,7 @@ The platform provides several utility functions:
817
831
 
818
832
  ```typescript
819
833
  // Format phone numbers for GREEN-API
820
- formatPhoneNumber('1234567890') // Returns '1234567890@c.us'
834
+ formatPhoneNumber('+1234567890') // Returns '1234567890@c.us'
821
835
 
822
836
  // Generate secure random tokens
823
837
  generateRandomToken(32) // Returns a 32-character random token
@@ -825,6 +839,18 @@ generateRandomToken(32) // Returns a 32-character random token
825
839
  // Extract phone number from vcard
826
840
  const vcard = 'BEGIN:VCARD\nTEL:+1234567890\nEND:VCARD'
827
841
  extractPhoneNumberFromVCard(vcard) // Returns '+1234567890'
842
+
843
+ // Validate settings values
844
+ isValidSettingValue('webhookUrl', 'https://example.com') // Returns true
845
+
846
+ // Clean settings
847
+ const input = {
848
+ webhookUrl: 'https://example.com',
849
+ outgoingWebhook: 'yes',
850
+ invalidKey: 'value',
851
+ delaySendMessagesMilliseconds: 'invalid'
852
+ }
853
+ validateAndCleanSettings(input) // Returns { webhookUrl: 'https://example.com', outgoingWebhook: 'yes' }
828
854
  ```
829
855
 
830
856
  ## License
package/README.ru.md CHANGED
@@ -128,7 +128,7 @@ app.post('/webhook/green-api', async (req, res) => {
128
128
 
129
129
  ```typescript
130
130
  abstract class MessageTransformer<TPlatformWebhook, TPlatformMessage> {
131
- abstract toPlatformMessage(webhook: IncomingGreenApiWebhook): TPlatformMessage;
131
+ abstract toPlatformMessage(webhook: GreenApiWebhook): TPlatformMessage;
132
132
 
133
133
  abstract toGreenApiMessage(message: TPlatformWebhook): Message;
134
134
  }
@@ -140,7 +140,7 @@ abstract class MessageTransformer<TPlatformWebhook, TPlatformMessage> {
140
140
 
141
141
  ```typescript
142
142
  abstract class StorageProvider<TUser extends BaseUser = BaseUser, TInstance extends BaseInstance = Instance> {
143
- abstract createInstance(instance: BaseInstance, userId: bigint | number, settings?: Settings): Promise<TInstance>;
143
+ abstract createInstance(instance: BaseInstance, userId: bigint | number): Promise<TInstance>;
144
144
 
145
145
  abstract getInstance(idInstance: number | bigint): Promise<TInstance | null>;
146
146
 
@@ -285,11 +285,11 @@ export interface YourPlatformMessage {
285
285
 
286
286
  ```typescript
287
287
  // core/transformer.ts
288
- import { MessageTransformer, Message, IncomingGreenApiWebhook } from '@green-api/greenapi-integration';
288
+ import { MessageTransformer, Message, GreenApiWebhook } from '@green-api/greenapi-integration';
289
289
  import { YourPlatformWebhook, YourPlatformMessage } from '../types/types';
290
290
 
291
291
  export class YourTransformer extends MessageTransformer<YourPlatformWebhook, YourPlatformMessage> {
292
- toPlatformMessage(webhook: IncomingGreenApiWebhook): YourPlatformMessage {
292
+ toPlatformMessage(webhook: GreenApiWebhook): YourPlatformMessage {
293
293
  // Преобразование вебхука GREEN-API в формат вашей платформы
294
294
  return {
295
295
  recipient: webhook.senderData.sender,
@@ -315,7 +315,7 @@ ORM:
315
315
 
316
316
  ```typescript
317
317
  // core/storage.ts
318
- import { StorageProvider, BaseUser, BaseInstance, Settings } from '@green-api/greenapi-integration';
318
+ import { StorageProvider, BaseUser, Instance, Settings } from '@green-api/greenapi-integration';
319
319
  import { PrismaClient } from '@prisma/client'; // Or your database client
320
320
 
321
321
  export class YourStorage extends StorageProvider {
@@ -325,13 +325,13 @@ export class YourStorage extends StorageProvider {
325
325
  this.db = new PrismaClient();
326
326
  }
327
327
 
328
- async createInstance(instance: BaseInstance, userId: bigint, settings?: Settings) {
328
+ async createInstance(instance: Instance, userId: bigint) {
329
329
  return this.db.instance.create({
330
330
  data: {
331
331
  idInstance: instance.idInstance,
332
332
  apiTokenInstance: instance.apiTokenInstance,
333
333
  userId,
334
- settings: settings || {},
334
+ settings: instance.settings || {},
335
335
  },
336
336
  });
337
337
  }
@@ -346,7 +346,7 @@ export class YourStorage extends StorageProvider {
346
346
 
347
347
  ```typescript
348
348
  // core/adapter.ts
349
- import { BaseAdapter, BaseInstance } from '@green-api/greenapi-integration';
349
+ import { BaseAdapter, Instance } from '@green-api/greenapi-integration';
350
350
  import { YourPlatformClient } from 'your-platform-sdk';
351
351
  import { YourPlatformWebhook, YourPlatformMessage } from '../types/types';
352
352
 
@@ -358,7 +358,7 @@ export class YourAdapter extends BaseAdapter<YourPlatformWebhook, YourPlatformMe
358
358
  });
359
359
  }
360
360
 
361
- async sendToPlatform(message: YourPlatformMessage, instance: BaseInstance) {
361
+ async sendToPlatform(message: YourPlatformMessage, instance: Instance) {
362
362
  const client = await this.createPlatformClient(instance.config);
363
363
  await client.sendMessage(message);
364
364
  }
@@ -430,11 +430,12 @@ router.post('/instance', async (req, res) => {
430
430
 
431
431
  const instance = await adapter.createInstance({
432
432
  idInstance: Number(idInstance),
433
- apiTokenInstance
434
- }, {
435
- webhookUrl: `${process.env.APP_URL}/webhook/green-api`,
436
- webhookUrlToken: `token_${Date.now()}`, // В продакшене используйте безопасный генератор токенов
437
- incomingWebhook: 'yes'
433
+ apiTokenInstance,
434
+ settings: {
435
+ webhookUrl: `${process.env.APP_URL}/webhook/green-api`,
436
+ webhookUrlToken: `token_${Date.now()}`,
437
+ incomingWebhook: 'yes'
438
+ }
438
439
  }, userEmail);
439
440
 
440
441
  res.status(200).json({
@@ -528,7 +529,7 @@ bootstrap();
528
529
  "prepublishOnly": "npm run build"
529
530
  },
530
531
  "dependencies": {
531
- "@green-api/greenapi-integration": "^1.0.0",
532
+ "@green-api/greenapi-integration": "^0.4.0",
532
533
  "@prisma/client": "^5.0.0",
533
534
  "express": "^4.18.2"
534
535
  // другие зависимости
@@ -614,18 +615,21 @@ interface SimplePlatformMessage {
614
615
  ### simple-transformer.ts
615
616
 
616
617
  ```typescript
617
- import { MessageTransformer, Message, IncomingGreenApiWebhook, formatPhoneNumber } from 'greenapi-integration';
618
+ import { MessageTransformer, Message, GreenApiWebhook, formatPhoneNumber, IntegrationError } from '@green-api/greenapi-integration';
618
619
 
619
620
  export class SimpleTransformer extends MessageTransformer<SimplePlatformWebhook, SimplePlatformMessage> {
620
- toPlatformMessage(webhook: IncomingGreenApiWebhook): SimplePlatformMessage {
621
- if (webhook.messageData.typeMessage !== 'extendedTextMessage') {
622
- throw new Error('Поддерживаются только текстовые сообщения');
623
- }
621
+ toPlatformMessage(webhook: GreenApiWebhook): SimplePlatformMessage {
622
+ if (webhook.typeWebhook === "incomingMessageReceived") {
623
+ if (webhook.messageData.typeMessage !== "extendedTextMessage") {
624
+ throw new IntegrationError("Поддерживаются только текстовые сообщения", "BAD_REQUEST_ERROR", 400);
625
+ }
624
626
 
625
- return {
626
- to: webhook.senderData.sender,
627
- content: webhook.messageData.extendedTextMessageData?.text || '',
628
- };
627
+ return {
628
+ to: webhook.senderData.sender,
629
+ content: webhook.messageData.extendedTextMessageData?.text || "",
630
+ };
631
+ }
632
+ throw new IntegrationError("Поддерживаются только вебхуки вида incomingMessageReceived", "INTEGRATION_ERROR", 500);
629
633
  }
630
634
 
631
635
  toGreenApiMessage(message: SimplePlatformWebhook): Message {
@@ -641,25 +645,24 @@ export class SimpleTransformer extends MessageTransformer<SimplePlatformWebhook,
641
645
  ### simple-storage.ts
642
646
 
643
647
  ```typescript
644
- import { StorageProvider, BaseUser, BaseInstance, Settings } from 'greenapi-integration';
648
+ import { StorageProvider, BaseUser, Instance, Settings } from '@green-api/greenapi-integration';
645
649
 
646
650
  export class SimpleStorage extends StorageProvider {
647
651
  private users: Map<string, BaseUser> = new Map();
648
- private instances: Map<number, BaseInstance> = new Map();
652
+ private instances: Map<number, Instance> = new Map();
649
653
 
650
- async createInstance(instance: BaseInstance, userId: bigint, settings?: Settings): Promise<BaseInstance> {
654
+ async createInstance(instance: Instance, userId: bigint): Promise<Instance> {
651
655
  this.instances.set(Number(instance.idInstance), {
652
656
  ...instance,
653
- settings: settings || {}
654
657
  });
655
658
  return instance;
656
659
  }
657
660
 
658
- async getInstance(idInstance: number): Promise<BaseInstance | null> {
661
+ async getInstance(idInstance: number): Promise<Instance | null> {
659
662
  return this.instances.get(idInstance) || null;
660
663
  }
661
664
 
662
- async removeInstance(instanceId: number): Promise<BaseInstance> {
665
+ async removeInstance(instanceId: number): Promise<Instance> {
663
666
  const instance = this.instances.get(instanceId);
664
667
  if (!instance) throw new Error('Инстанс не найден');
665
668
  this.instances.delete(instanceId);
@@ -689,7 +692,7 @@ export class SimpleStorage extends StorageProvider {
689
692
  ### simple-adapter.ts
690
693
 
691
694
  ```typescript
692
- import { BaseAdapter, BaseInstance } from "greenapi-integration";
695
+ import { BaseAdapter, Instance } from "@green-api/greenapi-integration";
693
696
  import axios from 'axios';
694
697
 
695
698
  export class SimpleAdapter extends BaseAdapter<SimplePlatformWebhook, SimplePlatformMessage> {
@@ -703,7 +706,7 @@ export class SimpleAdapter extends BaseAdapter<SimplePlatformWebhook, SimplePlat
703
706
  });
704
707
  }
705
708
 
706
- async sendToPlatform(message: SimplePlatformMessage, instance: BaseInstance): Promise<void> {
709
+ async sendToPlatform(message: SimplePlatformMessage, instance: Instance): Promise<void> {
707
710
  // В реальной реализации мы бы отправляли сообщение на платформу
708
711
  // Для демонстрации просто логируем и симулируем ответ
709
712
  console.log('Платформа получила сообщение:', message);
@@ -733,7 +736,7 @@ export class SimpleAdapter extends BaseAdapter<SimplePlatformWebhook, SimplePlat
733
736
  ```typescript
734
737
  import express from "express";
735
738
  import bodyParser from "body-parser";
736
- import { formatPhoneNumber, GreenApiClient } from "greenapi-integration";
739
+ import { formatPhoneNumber, GreenApiClient } from "@green-api/greenapi-integration";
737
740
  import { SimpleTransformer } from "./simple-transformer";
738
741
  import { SimpleStorage } from "./simple-storage";
739
742
  import { SimpleAdapter } from "./simple-adapter";
@@ -768,10 +771,12 @@ async function main() {
768
771
  name: "Agent",
769
772
  });
770
773
 
771
- const instance = await adapter.createInstance(agentInstance, {
772
- webhookUrl: process.env.WEBHOOK_URL + "/webhook/green-api",
773
- webhookUrlToken: "your-secure-token",
774
- incomingWebhook: "yes",
774
+ const instance = await adapter.createInstance({
775
+ idInstance: agentInstance.idInstance, apiTokenInstance: agentInstance.apiTokenInstance, settings: {
776
+ webhookUrl: process.env.WEBHOOK_URL + "/webhook/green-api",
777
+ webhookUrlToken: "your-secure-token",
778
+ incomingWebhook: "yes",
779
+ },
775
780
  }, user.email);
776
781
 
777
782
  console.log("Ожидание 2 минуты для применения настроек...");
@@ -795,7 +800,7 @@ async function main() {
795
800
  });
796
801
 
797
802
  // Запуск сервера
798
- const port = process.env.PORT || 3000;
803
+ const port = Number(process.env.PORT) || 3000;
799
804
  app.listen(port, () => {
800
805
  console.log(`Сервер вебхуков запущен на порту ${port}`);
801
806
  });
@@ -838,7 +843,7 @@ PORT=3000
838
843
 
839
844
  ```typescript
840
845
  // Форматирование телефонных номеров для GREEN-API
841
- formatPhoneNumber('1234567890') // Возвращает '1234567890@c.us'
846
+ formatPhoneNumber('+1234567890') // Возвращает '1234567890@c.us'
842
847
 
843
848
  // Генерация безопасных случайных токенов
844
849
  generateRandomToken(32) // Возвращает 32-символьный случайный токен
@@ -846,6 +851,18 @@ generateRandomToken(32) // Возвращает 32-символьный случ
846
851
  // Извлечение номера телефона из vcard
847
852
  const vcard = 'BEGIN:VCARD\nTEL:+1234567890\nEND:VCARD'
848
853
  extractPhoneNumberFromVCard(vcard) // Возвращает '+1234567890'
854
+
855
+ // Проверка значений настроек
856
+ isValidSettingValue('webhookUrl', 'https://example.com') // Возвращает true
857
+
858
+ // Очистка настроек
859
+ const input = {
860
+ webhookUrl: 'https://example.com',
861
+ outgoingWebhook: 'yes',
862
+ invalidKey: 'value',
863
+ delaySendMessagesMilliseconds: 'invalid'
864
+ }
865
+ validateAndCleanSettings(input) // Возвращает { webhookUrl: 'https://example.com', outgoingWebhook: 'yes' }
849
866
  ```
850
867
 
851
868
  ## Лицензия
@@ -1,7 +1,8 @@
1
- import { Instance, Settings, SendMessage, SendFileByUrl, SendFileByUpload, SendPoll, StateInstance, Reboot, Logout, QR, SendResponse, SendFileByUploadResponse, SetSettingsResponse, GetAuthorizationCode, SetProfilePicture, WaSettings, UploadFile, SendLocation, SendContact, ForwardMessages, ForwardMessagesResponse } from "../types/types";
1
+ import { Instance, Settings, SendMessage, SendFileByUrl, SendFileByUpload, SendPoll, StateInstance, Reboot, Logout, QR, SendResponse, SendFileByUploadResponse, SetSettingsResponse, GetAuthorizationCode, SetProfilePicture, WaSettings, UploadFile, SendLocation, SendContact, ForwardMessages, ForwardMessagesResponse, QueueMessage, ClearMessagesQueue, ReadChatResponse, ReadChat, CheckWhatsapp, CheckWhatsappResponse, GetAvatarResponse, GetAvatar, Contact, ContactInfo, ArchiveChat, UnarchiveChat, SetDisappearingChat, SetDisappearingChatResponse, CreateGroupResponse, CreateGroup, UpdateGroupName, UpdateGroupNameResponse, GetGroupData, GroupData, AddGroupParticipant, AddGroupParticipantResponse, RemoveGroupParticipant, RemoveGroupParticipantResponse, SetGroupAdmin, SetGroupAdminResponse, RemoveAdminResponse, RemoveAdmin, SetGroupPicture, SetGroupPictureResponse, LeaveGroup, LeaveGroupResponse, GetMessage, JournalResponse, GetChatHistory, IncomingJournalResponse, OutgoingJournalResponse } from "../types/types";
2
2
  /**
3
3
  * Client for direct interaction with GREEN-API's WhatsApp gateway.
4
4
  * Provides methods for sending messages, managing instances, and handling files.
5
+ * For more information about the methods, refer to https://green-api.com/en/docs
5
6
  *
6
7
  * @category Client
7
8
  *
@@ -213,4 +214,227 @@ export declare class GreenApiClient {
213
214
  * @throws {Error} If phone number is not an integer
214
215
  */
215
216
  getAuthorizationCode(phoneNumber: number): Promise<GetAuthorizationCode>;
217
+ /**
218
+ * Gets the list of messages in the sending queue.
219
+ * Messages are stored for 24 hours and will be sent immediately after phone authorization.
220
+ * The sending speed is regulated by the Message Sending Interval parameter.
221
+ *
222
+ * @returns Promise resolving to an array of queued messages
223
+ *
224
+ * @example
225
+ * ```typescript
226
+ * const queuedMessages = await client.showMessagesQueue();
227
+ * console.log(queuedMessages);
228
+ * ```
229
+ */
230
+ showMessagesQueue(): Promise<QueueMessage[]>;
231
+ /**
232
+ * Clears the queue of messages waiting to be sent.
233
+ * Important when switching phone numbers to prevent sending queued messages with the new number.
234
+ *
235
+ * @returns Promise resolving to queue clearing status
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * const result = await client.clearMessagesQueue();
240
+ * if (result.isCleared) {
241
+ * console.log('Queue successfully cleared');
242
+ * }
243
+ * ```
244
+ */
245
+ clearMessagesQueue(): Promise<ClearMessagesQueue>;
246
+ /**
247
+ * Marks messages in a chat as read.
248
+ * For this to work, "Receive webhooks on incoming messages and files" setting must be enabled.
249
+ * Note: Only messages received after enabling the setting can be marked as read.
250
+ *
251
+ * @param params - Parameters specifying which messages to mark as read
252
+ * @returns Promise resolving to read status
253
+ *
254
+ * @example
255
+ * ```typescript
256
+ * // Mark all messages in chat as read
257
+ * const result = await client.readChat({
258
+ * chatId: "1234567890@c.us"
259
+ * });
260
+ *
261
+ * // Mark specific message as read
262
+ * const result = await client.readChat({
263
+ * chatId: "1234567890@c.us",
264
+ * idMessage: "B275A7AA0D6EF89BB9245169BDF174E6"
265
+ * });
266
+ * ```
267
+ */
268
+ readChat(params: ReadChat): Promise<ReadChatResponse>;
269
+ /**
270
+ * Checks WhatsApp account availability on a phone number.
271
+ *
272
+ * @param params - Parameters containing the phone number to check
273
+ * @returns Promise resolving to WhatsApp availability status
274
+ * @throws {Error} If phone number is not an integer or not 11-12 digits
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * const result = await client.checkWhatsapp({
279
+ * phoneNumber: 11001234567
280
+ * });
281
+ *
282
+ * if (result.existsWhatsapp) {
283
+ * console.log('WhatsApp account exists');
284
+ * }
285
+ * ```
286
+ */
287
+ checkWhatsapp(params: CheckWhatsapp): Promise<CheckWhatsappResponse>;
288
+ /**
289
+ * Gets a user or group chat avatar.
290
+ *
291
+ * @param params - Parameters containing the chat ID
292
+ * @returns Promise resolving to avatar information
293
+ */
294
+ getAvatar(params: GetAvatar): Promise<GetAvatarResponse>;
295
+ /**
296
+ * Gets a list of the current account contacts.
297
+ * Note: Contact information updates can take up to 5 minutes.
298
+ * If an empty array is received, retry the method call.
299
+ *
300
+ * @returns Promise resolving to array of contacts
301
+ */
302
+ getContacts(): Promise<Contact[]>;
303
+ /**
304
+ * Gets detailed information about a contact.
305
+ * Note: This method does not support group chats, use getGroupData for groups.
306
+ *
307
+ * @param params - Parameters containing the chat ID
308
+ * @returns Promise resolving to contact information
309
+ */
310
+ getContactInfo(params: GetAvatar): Promise<ContactInfo>;
311
+ /**
312
+ * Archives a chat. Chat must have at least one incoming message.
313
+ * Note: "Receive webhooks on incoming messages and files" setting must be enabled.
314
+ *
315
+ * @param params - Parameters containing the chat ID to archive
316
+ * @returns Promise resolving to void on success
317
+ */
318
+ archiveChat(params: ArchiveChat): Promise<void>;
319
+ /**
320
+ * Unarchives a chat.
321
+ *
322
+ * @param params - Parameters containing the chat ID to unarchive
323
+ * @returns Promise resolving to void on success
324
+ */
325
+ unarchiveChat(params: UnarchiveChat): Promise<void>;
326
+ /**
327
+ * Changes settings of disappearing messages in chats.
328
+ * Valid expiration times: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)
329
+ *
330
+ * @param params - Parameters containing chat ID and message expiration time
331
+ * @returns Promise resolving to chat disappearing message settings
332
+ */
333
+ setDisappearingChat(params: SetDisappearingChat): Promise<SetDisappearingChatResponse>;
334
+ /**
335
+ * Creates a group chat.
336
+ * Note: Limited to creating 1 group per 5 minutes to simulate human behavior.
337
+ *
338
+ * @param params - Parameters containing group name and participant IDs
339
+ * @returns Promise resolving to group creation result
340
+ */
341
+ createGroup(params: CreateGroup): Promise<CreateGroupResponse>;
342
+ /**
343
+ * Changes a group chat name.
344
+ *
345
+ * @param params - Parameters containing group ID and new name
346
+ * @returns Promise resolving to update status
347
+ */
348
+ updateGroupName(params: UpdateGroupName): Promise<UpdateGroupNameResponse>;
349
+ /**
350
+ * Gets group chat data.
351
+ * Note: groupInviteLink will be empty if user is not an admin or owner.
352
+ *
353
+ * @param params - Parameters containing group ID
354
+ * @returns Promise resolving to group data
355
+ */
356
+ getGroupData(params: GetGroupData): Promise<GroupData>;
357
+ /**
358
+ * Adds a participant to a group chat.
359
+ * Note: Only group administrators can add members.
360
+ * The participant's number should be saved in the phonebook for reliable addition.
361
+ *
362
+ * @param params - Parameters containing group ID and participant ID
363
+ * @returns Promise resolving to addition status
364
+ */
365
+ addGroupParticipant(params: AddGroupParticipant): Promise<AddGroupParticipantResponse>;
366
+ /**
367
+ * Removes a participant from a group chat.
368
+ *
369
+ * @param params - Parameters containing group ID and participant ID to remove
370
+ * @returns Promise resolving to removal status
371
+ */
372
+ removeGroupParticipant(params: RemoveGroupParticipant): Promise<RemoveGroupParticipantResponse>;
373
+ /**
374
+ * Sets a group chat participant as an administrator.
375
+ *
376
+ * @param params - Parameters containing group ID and participant ID to promote
377
+ * @returns Promise resolving to admin status change result
378
+ */
379
+ setGroupAdmin(params: SetGroupAdmin): Promise<SetGroupAdminResponse>;
380
+ /**
381
+ * Removes administrator rights from a group chat participant.
382
+ *
383
+ * @param params - Parameters containing group ID and participant ID to demote
384
+ * @returns Promise resolving to admin removal status
385
+ */
386
+ removeAdmin(params: RemoveAdmin): Promise<RemoveAdminResponse>;
387
+ /**
388
+ * Sets a group chat picture.
389
+ *
390
+ * @param params - Parameters containing group ID and picture file (jpg)
391
+ * @returns Promise resolving to picture update status
392
+ */
393
+ setGroupPicture(params: SetGroupPicture): Promise<SetGroupPictureResponse>;
394
+ /**
395
+ * Makes the current account leave a group chat.
396
+ *
397
+ * @param params - Parameters containing the group ID to leave
398
+ * @returns Promise resolving to leave status
399
+ */
400
+ leaveGroup(params: LeaveGroup): Promise<LeaveGroupResponse>;
401
+ /**
402
+ * Gets details of a specific message.
403
+ * Note: To receive incoming webhooks, requires "Receive webhooks on incoming messages and files" setting to be enabled.
404
+ * Note: To receive statuses of sent messsages, requires "Receive notifications about the statuses of sent messages" to be enabled.
405
+ * Messages can take up to 2 minutes to appear in the journal.
406
+ *
407
+ * @param params - Parameters containing chat ID and message ID
408
+ * @returns Promise resolving to message details
409
+ */
410
+ getMessage(params: GetMessage): Promise<JournalResponse>;
411
+ /**
412
+ * Gets chat message history.
413
+ * Note: Requires "Receive webhooks" setting to be enabled.
414
+ * Messages can take up to 2 minutes to appear in history.
415
+ *
416
+ * @param params - Parameters containing chat ID and optional message count
417
+ * @returns Promise resolving to array of messages
418
+ */
419
+ getChatHistory(params: GetChatHistory): Promise<JournalResponse[]>;
420
+ /**
421
+ * Gets last incoming messages for the specified time period.
422
+ * Default is 24 hours (1440 minutes).
423
+ * Note: Requires "Receive webhooks" setting to be enabled.
424
+ * Messages can take up to 2 minutes to appear in history.
425
+ *
426
+ * @param minutes - Optional time period in minutes
427
+ * @returns Promise resolving to array of incoming messages
428
+ */
429
+ lastIncomingMessages(minutes?: number): Promise<IncomingJournalResponse[]>;
430
+ /**
431
+ * Gets last outgoing messages for the specified time period.
432
+ * Default is 24 hours (1440 minutes).
433
+ * Note: Requires "Receive webhooks" setting to be enabled.
434
+ * Messages can take up to 2 minutes to appear in history.
435
+ *
436
+ * @param minutes - Optional time period in minutes
437
+ * @returns Promise resolving to array of outgoing messages
438
+ */
439
+ lastOutgoingMessages(minutes?: number): Promise<OutgoingJournalResponse[]>;
216
440
  }
@@ -8,6 +8,7 @@ const axios_1 = __importDefault(require("axios"));
8
8
  /**
9
9
  * Client for direct interaction with GREEN-API's WhatsApp gateway.
10
10
  * Provides methods for sending messages, managing instances, and handling files.
11
+ * For more information about the methods, refer to https://green-api.com/en/docs
11
12
  *
12
13
  * @category Client
13
14
  *
@@ -43,11 +44,12 @@ class GreenApiClient {
43
44
  buildEndpoint(endpoint) {
44
45
  return `/${endpoint}/${this.instance.apiTokenInstance}`;
45
46
  }
46
- async makeRequest(method, endpoint, data, config) {
47
+ async makeRequest(method, endpoint, data, queryParams, config) {
47
48
  try {
49
+ const url = this.buildEndpoint(endpoint) + (queryParams ? "?" + new URLSearchParams(Object.entries(queryParams).map(([key, value]) => [key, value.toString()])).toString() : "");
48
50
  const response = await (method === "get"
49
- ? this.client.get(this.buildEndpoint(endpoint), config)
50
- : this.client.post(this.buildEndpoint(endpoint), data, config));
51
+ ? this.client.get(url, config)
52
+ : this.client.post(url, data, config));
51
53
  return response.data;
52
54
  }
53
55
  catch (error) {
@@ -55,7 +57,7 @@ class GreenApiClient {
55
57
  }
56
58
  }
57
59
  async makeFileUploadRequest(endpoint, formData, headers) {
58
- return this.makeRequest("post", endpoint, formData, {
60
+ return this.makeRequest("post", endpoint, formData, undefined, {
59
61
  headers: { "Content-Type": "multipart/form-data" },
60
62
  ...headers,
61
63
  });
@@ -334,5 +336,284 @@ class GreenApiClient {
334
336
  }
335
337
  return this.makeRequest("post", "getAuthorizationCode", { phoneNumber });
336
338
  }
339
+ /**
340
+ * Gets the list of messages in the sending queue.
341
+ * Messages are stored for 24 hours and will be sent immediately after phone authorization.
342
+ * The sending speed is regulated by the Message Sending Interval parameter.
343
+ *
344
+ * @returns Promise resolving to an array of queued messages
345
+ *
346
+ * @example
347
+ * ```typescript
348
+ * const queuedMessages = await client.showMessagesQueue();
349
+ * console.log(queuedMessages);
350
+ * ```
351
+ */
352
+ async showMessagesQueue() {
353
+ return this.makeRequest("get", "showMessagesQueue");
354
+ }
355
+ /**
356
+ * Clears the queue of messages waiting to be sent.
357
+ * Important when switching phone numbers to prevent sending queued messages with the new number.
358
+ *
359
+ * @returns Promise resolving to queue clearing status
360
+ *
361
+ * @example
362
+ * ```typescript
363
+ * const result = await client.clearMessagesQueue();
364
+ * if (result.isCleared) {
365
+ * console.log('Queue successfully cleared');
366
+ * }
367
+ * ```
368
+ */
369
+ async clearMessagesQueue() {
370
+ return this.makeRequest("get", "clearMessagesQueue");
371
+ }
372
+ /**
373
+ * Marks messages in a chat as read.
374
+ * For this to work, "Receive webhooks on incoming messages and files" setting must be enabled.
375
+ * Note: Only messages received after enabling the setting can be marked as read.
376
+ *
377
+ * @param params - Parameters specifying which messages to mark as read
378
+ * @returns Promise resolving to read status
379
+ *
380
+ * @example
381
+ * ```typescript
382
+ * // Mark all messages in chat as read
383
+ * const result = await client.readChat({
384
+ * chatId: "1234567890@c.us"
385
+ * });
386
+ *
387
+ * // Mark specific message as read
388
+ * const result = await client.readChat({
389
+ * chatId: "1234567890@c.us",
390
+ * idMessage: "B275A7AA0D6EF89BB9245169BDF174E6"
391
+ * });
392
+ * ```
393
+ */
394
+ async readChat(params) {
395
+ return this.makeRequest("post", "readChat", params);
396
+ }
397
+ /**
398
+ * Checks WhatsApp account availability on a phone number.
399
+ *
400
+ * @param params - Parameters containing the phone number to check
401
+ * @returns Promise resolving to WhatsApp availability status
402
+ * @throws {Error} If phone number is not an integer or not 11-12 digits
403
+ *
404
+ * @example
405
+ * ```typescript
406
+ * const result = await client.checkWhatsapp({
407
+ * phoneNumber: 11001234567
408
+ * });
409
+ *
410
+ * if (result.existsWhatsapp) {
411
+ * console.log('WhatsApp account exists');
412
+ * }
413
+ * ```
414
+ */
415
+ async checkWhatsapp(params) {
416
+ const phoneStr = params.phoneNumber.toString();
417
+ if (!Number.isInteger(params.phoneNumber)) {
418
+ throw new Error("Phone number must contain only digits");
419
+ }
420
+ if (phoneStr.length < 11 || phoneStr.length > 12) {
421
+ throw new Error("Phone number must be 11 or 12 digits");
422
+ }
423
+ return this.makeRequest("post", "checkWhatsapp", params);
424
+ }
425
+ /**
426
+ * Gets a user or group chat avatar.
427
+ *
428
+ * @param params - Parameters containing the chat ID
429
+ * @returns Promise resolving to avatar information
430
+ */
431
+ async getAvatar(params) {
432
+ return this.makeRequest("post", "getAvatar", params);
433
+ }
434
+ /**
435
+ * Gets a list of the current account contacts.
436
+ * Note: Contact information updates can take up to 5 minutes.
437
+ * If an empty array is received, retry the method call.
438
+ *
439
+ * @returns Promise resolving to array of contacts
440
+ */
441
+ async getContacts() {
442
+ return this.makeRequest("get", "getContacts");
443
+ }
444
+ /**
445
+ * Gets detailed information about a contact.
446
+ * Note: This method does not support group chats, use getGroupData for groups.
447
+ *
448
+ * @param params - Parameters containing the chat ID
449
+ * @returns Promise resolving to contact information
450
+ */
451
+ async getContactInfo(params) {
452
+ return this.makeRequest("post", "getContactInfo", params);
453
+ }
454
+ /**
455
+ * Archives a chat. Chat must have at least one incoming message.
456
+ * Note: "Receive webhooks on incoming messages and files" setting must be enabled.
457
+ *
458
+ * @param params - Parameters containing the chat ID to archive
459
+ * @returns Promise resolving to void on success
460
+ */
461
+ async archiveChat(params) {
462
+ return this.makeRequest("post", "archiveChat", params);
463
+ }
464
+ /**
465
+ * Unarchives a chat.
466
+ *
467
+ * @param params - Parameters containing the chat ID to unarchive
468
+ * @returns Promise resolving to void on success
469
+ */
470
+ async unarchiveChat(params) {
471
+ return this.makeRequest("post", "unarchiveChat", params);
472
+ }
473
+ /**
474
+ * Changes settings of disappearing messages in chats.
475
+ * Valid expiration times: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)
476
+ *
477
+ * @param params - Parameters containing chat ID and message expiration time
478
+ * @returns Promise resolving to chat disappearing message settings
479
+ */
480
+ async setDisappearingChat(params) {
481
+ return this.makeRequest("post", "setDisappearingChat", params);
482
+ }
483
+ /**
484
+ * Creates a group chat.
485
+ * Note: Limited to creating 1 group per 5 minutes to simulate human behavior.
486
+ *
487
+ * @param params - Parameters containing group name and participant IDs
488
+ * @returns Promise resolving to group creation result
489
+ */
490
+ async createGroup(params) {
491
+ return this.makeRequest("post", "createGroup", params);
492
+ }
493
+ /**
494
+ * Changes a group chat name.
495
+ *
496
+ * @param params - Parameters containing group ID and new name
497
+ * @returns Promise resolving to update status
498
+ */
499
+ async updateGroupName(params) {
500
+ return this.makeRequest("post", "updateGroupName", params);
501
+ }
502
+ /**
503
+ * Gets group chat data.
504
+ * Note: groupInviteLink will be empty if user is not an admin or owner.
505
+ *
506
+ * @param params - Parameters containing group ID
507
+ * @returns Promise resolving to group data
508
+ */
509
+ async getGroupData(params) {
510
+ return this.makeRequest("post", "getGroupData", params);
511
+ }
512
+ /**
513
+ * Adds a participant to a group chat.
514
+ * Note: Only group administrators can add members.
515
+ * The participant's number should be saved in the phonebook for reliable addition.
516
+ *
517
+ * @param params - Parameters containing group ID and participant ID
518
+ * @returns Promise resolving to addition status
519
+ */
520
+ async addGroupParticipant(params) {
521
+ return this.makeRequest("post", "addGroupParticipant", params);
522
+ }
523
+ /**
524
+ * Removes a participant from a group chat.
525
+ *
526
+ * @param params - Parameters containing group ID and participant ID to remove
527
+ * @returns Promise resolving to removal status
528
+ */
529
+ async removeGroupParticipant(params) {
530
+ return this.makeRequest("post", "removeGroupParticipant", params);
531
+ }
532
+ /**
533
+ * Sets a group chat participant as an administrator.
534
+ *
535
+ * @param params - Parameters containing group ID and participant ID to promote
536
+ * @returns Promise resolving to admin status change result
537
+ */
538
+ async setGroupAdmin(params) {
539
+ return this.makeRequest("post", "setGroupAdmin", params);
540
+ }
541
+ /**
542
+ * Removes administrator rights from a group chat participant.
543
+ *
544
+ * @param params - Parameters containing group ID and participant ID to demote
545
+ * @returns Promise resolving to admin removal status
546
+ */
547
+ async removeAdmin(params) {
548
+ return this.makeRequest("post", "removeAdmin", params);
549
+ }
550
+ /**
551
+ * Sets a group chat picture.
552
+ *
553
+ * @param params - Parameters containing group ID and picture file (jpg)
554
+ * @returns Promise resolving to picture update status
555
+ */
556
+ async setGroupPicture(params) {
557
+ const formData = new FormData();
558
+ formData.append("file", params.file);
559
+ formData.append("groupId", params.groupId);
560
+ return this.makeFileUploadRequest("setGroupPicture", formData);
561
+ }
562
+ /**
563
+ * Makes the current account leave a group chat.
564
+ *
565
+ * @param params - Parameters containing the group ID to leave
566
+ * @returns Promise resolving to leave status
567
+ */
568
+ async leaveGroup(params) {
569
+ return this.makeRequest("post", "leaveGroup", params);
570
+ }
571
+ /**
572
+ * Gets details of a specific message.
573
+ * Note: To receive incoming webhooks, requires "Receive webhooks on incoming messages and files" setting to be enabled.
574
+ * Note: To receive statuses of sent messsages, requires "Receive notifications about the statuses of sent messages" to be enabled.
575
+ * Messages can take up to 2 minutes to appear in the journal.
576
+ *
577
+ * @param params - Parameters containing chat ID and message ID
578
+ * @returns Promise resolving to message details
579
+ */
580
+ async getMessage(params) {
581
+ return this.makeRequest("post", "getMessage", params);
582
+ }
583
+ /**
584
+ * Gets chat message history.
585
+ * Note: Requires "Receive webhooks" setting to be enabled.
586
+ * Messages can take up to 2 minutes to appear in history.
587
+ *
588
+ * @param params - Parameters containing chat ID and optional message count
589
+ * @returns Promise resolving to array of messages
590
+ */
591
+ async getChatHistory(params) {
592
+ return this.makeRequest("post", "getChatHistory", params);
593
+ }
594
+ /**
595
+ * Gets last incoming messages for the specified time period.
596
+ * Default is 24 hours (1440 minutes).
597
+ * Note: Requires "Receive webhooks" setting to be enabled.
598
+ * Messages can take up to 2 minutes to appear in history.
599
+ *
600
+ * @param minutes - Optional time period in minutes
601
+ * @returns Promise resolving to array of incoming messages
602
+ */
603
+ async lastIncomingMessages(minutes) {
604
+ return this.makeRequest("get", "lastIncomingMessages", undefined, minutes ? { minutes } : undefined);
605
+ }
606
+ /**
607
+ * Gets last outgoing messages for the specified time period.
608
+ * Default is 24 hours (1440 minutes).
609
+ * Note: Requires "Receive webhooks" setting to be enabled.
610
+ * Messages can take up to 2 minutes to appear in history.
611
+ *
612
+ * @param minutes - Optional time period in minutes
613
+ * @returns Promise resolving to array of outgoing messages
614
+ */
615
+ async lastOutgoingMessages(minutes) {
616
+ return this.makeRequest("get", "lastOutgoingMessages", undefined, minutes ? { minutes } : undefined);
617
+ }
337
618
  }
338
619
  exports.GreenApiClient = GreenApiClient;
@@ -2,7 +2,7 @@
2
2
  * Base interface for GREEN-API WhatsApp instances.
3
3
  * Contains the essential credentials needed to interact with the API.
4
4
  */
5
- interface BaseInstance {
5
+ export interface BaseInstance {
6
6
  idInstance: number | bigint;
7
7
  apiTokenInstance: string;
8
8
  stateInstance?: InstanceState;
@@ -22,6 +22,7 @@ export interface Instance extends BaseInstance {
22
22
  export type Message = ({
23
23
  type: "text";
24
24
  message: string;
25
+ linkPreview?: boolean;
25
26
  } & BaseMessage) | ({
26
27
  type: "upload-file";
27
28
  caption?: string;
@@ -97,7 +98,57 @@ export type SendPoll = Extract<Message, {
97
98
  export type ForwardMessages = Extract<Message, {
98
99
  type: "forward";
99
100
  }>;
100
- export type MessageType = "textMessage" | "extendedTextMessage" | "imageMessage" | "videoMessage" | "documentMessage" | "audioMessage" | "contactMessage" | "locationMessage" | "pollMessage";
101
+ export type QueueMessageType = "sendMessage" | "sendPoll" | "sendFileByUrl" | "sendLocation" | "sendContact" | "ForwardMessages";
102
+ export type QueueMessageBody = SendMessage | SendPoll | SendFileByUrl | SendLocation | SendContact | ForwardMessages;
103
+ export interface QueueMessage {
104
+ messageID?: string;
105
+ messagesIDs?: string[];
106
+ type: QueueMessageType;
107
+ body: QueueMessageBody;
108
+ }
109
+ export interface ClearMessagesQueue {
110
+ isCleared: boolean;
111
+ }
112
+ export type MessageType = "textMessage" | "extendedTextMessage" | "imageMessage" | "videoMessage" | "documentMessage" | "audioMessage" | "contactMessage" | "locationMessage" | "pollMessage" | "reactionMessage" | "pollUpdateMessage" | "quotedMessage" | "stickerMessage";
113
+ export interface GetMessage {
114
+ chatId: string;
115
+ idMessage: string;
116
+ }
117
+ export interface GetChatHistory {
118
+ chatId: string;
119
+ count?: number;
120
+ }
121
+ export interface BaseJournalMessage {
122
+ idMessage: string;
123
+ timestamp: number;
124
+ typeMessage: MessageType;
125
+ chatId: string;
126
+ isForwarded: boolean;
127
+ forwardingScore: number;
128
+ }
129
+ export interface IncomingJournalFields {
130
+ type: "incoming";
131
+ senderId: string;
132
+ senderName: string;
133
+ senderContactName: string;
134
+ }
135
+ export interface OutgoingJournalFields {
136
+ type: "outgoing";
137
+ statusMessage: OutgoingMessageStatus;
138
+ sendByApi: boolean;
139
+ }
140
+ export type BaseIncomingJournalMessage = BaseJournalMessage & IncomingJournalFields;
141
+ export type BaseOutgoingJournalMessage = BaseJournalMessage & OutgoingJournalFields;
142
+ export type BaseJournalResponse = BaseIncomingJournalMessage | BaseOutgoingJournalMessage;
143
+ export type OutgoingJournalResponse = BaseOutgoingJournalMessage & WebhookMessageData & {
144
+ quotedMessage?: QuotedMessage;
145
+ };
146
+ export type IncomingJournalResponse = BaseIncomingJournalMessage & WebhookMessageData & {
147
+ quotedMessage?: QuotedMessage;
148
+ };
149
+ export type JournalResponse = BaseJournalResponse & WebhookMessageData & {
150
+ quotedMessage?: QuotedMessage;
151
+ };
101
152
  export interface ForwardableMessage {
102
153
  forwardingScore: number;
103
154
  isForwarded: boolean;
@@ -274,6 +325,83 @@ export interface Reboot {
274
325
  export interface Logout {
275
326
  isLogout: boolean;
276
327
  }
328
+ export interface ReadChat {
329
+ chatId: string;
330
+ idMessage?: string;
331
+ }
332
+ export interface ReadChatResponse {
333
+ setRead: boolean;
334
+ }
335
+ export interface CheckWhatsapp {
336
+ phoneNumber: number;
337
+ }
338
+ export interface CheckWhatsappResponse {
339
+ existsWhatsapp: boolean;
340
+ }
341
+ export interface GetAvatar {
342
+ chatId: string;
343
+ }
344
+ export interface GetAvatarResponse {
345
+ urlAvatar: string;
346
+ available: boolean;
347
+ }
348
+ export type ContactType = "user" | "group";
349
+ export interface Contact {
350
+ id: string;
351
+ name: string;
352
+ contactName: string;
353
+ type: ContactType;
354
+ }
355
+ export interface ProductImageUrls {
356
+ requested: string;
357
+ original: string;
358
+ }
359
+ export interface ProductReviewStatus {
360
+ whatsapp: string;
361
+ }
362
+ export interface Product {
363
+ id: string;
364
+ imageUrls: ProductImageUrls;
365
+ reviewStatus: ProductReviewStatus;
366
+ availability: string;
367
+ name: string;
368
+ description?: string;
369
+ price: string | null;
370
+ isHidden: boolean;
371
+ }
372
+ export interface ContactInfo {
373
+ avatar: string;
374
+ name: string;
375
+ contactName: string;
376
+ email: string;
377
+ category: string;
378
+ description: string;
379
+ products: Product[];
380
+ chatId: string;
381
+ lastSeen: string | null;
382
+ isArchive: boolean;
383
+ isDisappearing: boolean;
384
+ isMute: boolean;
385
+ messageExpiration: number;
386
+ muteExpiration: number | null;
387
+ isBusiness: boolean;
388
+ }
389
+ export interface ArchiveChat {
390
+ chatId: string;
391
+ }
392
+ export interface UnarchiveChat {
393
+ chatId: string;
394
+ }
395
+ export type EphemeralExpiration = 0 | 86400 | 604800 | 7776000;
396
+ export interface SetDisappearingChat {
397
+ chatId: string;
398
+ ephemeralExpiration: EphemeralExpiration;
399
+ }
400
+ export interface SetDisappearingChatResponse {
401
+ chatId: string;
402
+ disappearingMessagesInChat: boolean;
403
+ ephemeralExpiration: EphemeralExpiration;
404
+ }
277
405
  /**
278
406
  * Represents an instance state in the GREEN-API system.
279
407
  */
@@ -313,6 +441,84 @@ export interface SetProfilePicture {
313
441
  urlAvatar: string;
314
442
  setProfilePicture: boolean;
315
443
  }
444
+ export interface CreateGroup {
445
+ groupName: string;
446
+ chatIds: string[];
447
+ }
448
+ export interface CreateGroupResponse {
449
+ created: boolean;
450
+ chatId: string;
451
+ groupInviteLink: string;
452
+ }
453
+ export interface UpdateGroupName {
454
+ groupId: string;
455
+ groupName: string;
456
+ }
457
+ export interface UpdateGroupNameResponse {
458
+ updateGroupName: boolean;
459
+ }
460
+ export interface GroupParticipant {
461
+ id: string;
462
+ isAdmin: boolean;
463
+ isSuperAdmin: boolean;
464
+ }
465
+ export interface GroupData {
466
+ groupId: string;
467
+ owner: string;
468
+ subject: string;
469
+ creation: number;
470
+ participants: GroupParticipant[];
471
+ subjectTime: number;
472
+ subjectOwner: string;
473
+ groupInviteLink: string;
474
+ }
475
+ export interface GetGroupData {
476
+ groupId: string;
477
+ }
478
+ export interface AddGroupParticipant {
479
+ groupId: string;
480
+ participantChatId: string;
481
+ }
482
+ export interface AddGroupParticipantResponse {
483
+ addParticipant: boolean;
484
+ }
485
+ export interface RemoveGroupParticipant {
486
+ groupId: string;
487
+ participantChatId: string;
488
+ }
489
+ export interface RemoveGroupParticipantResponse {
490
+ removeParticipant: boolean;
491
+ }
492
+ export interface SetGroupAdmin {
493
+ groupId: string;
494
+ participantChatId: string;
495
+ }
496
+ export interface SetGroupAdminResponse {
497
+ setGroupAdmin: boolean;
498
+ }
499
+ export interface RemoveAdmin {
500
+ groupId: string;
501
+ participantChatId: string;
502
+ }
503
+ export interface RemoveAdminResponse {
504
+ removeAdmin: boolean;
505
+ }
506
+ export interface SetGroupPicture {
507
+ groupId: string;
508
+ file: Blob | File;
509
+ }
510
+ export interface SetGroupPictureResponse {
511
+ setGroupPicture: boolean;
512
+ urlAvatar: string | null;
513
+ reason: string;
514
+ }
515
+ export interface LeaveGroup {
516
+ groupId: string;
517
+ }
518
+ export interface LeaveGroupResponse {
519
+ leaveGroup?: boolean;
520
+ removeAdmin?: boolean;
521
+ }
316
522
  export interface BaseRequest {
317
523
  headers: Record<string, any>;
318
524
  body: any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@green-api/greenapi-integration",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "GREEN-API Integration library",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",