@andrey4emk/npm-app-back-b24 0.5.36 → 0.6.1

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/sendMessage/wappi.js +114 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrey4emk/npm-app-back-b24",
3
- "version": "0.5.36",
3
+ "version": "0.6.1",
4
4
  "description": "Bitrix24 OAuth helpers for Node.js projects",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -15,9 +15,10 @@
15
15
  */
16
16
 
17
17
  export class Wappi {
18
- constructor(tokenParam, profileIdParam) {
19
- this.token = tokenParam;
20
- this.profile_id = profileIdParam;
18
+ constructor(maxAuth, telegaAuth, whatsAppAuth) {
19
+ this.maxAuth = maxAuth;
20
+ this.telegaAuth = telegaAuth;
21
+ this.whatsAppAuth = whatsAppAuth;
21
22
  }
22
23
 
23
24
  async sendMessageWappi(messangerType, messageData) {
@@ -30,6 +31,8 @@ export class Wappi {
30
31
  let phone = messageData.phone;
31
32
  let message = messageData.message;
32
33
  let url;
34
+ let token;
35
+ let profile_id;
33
36
  if (messangerType === "whatsApp") {
34
37
  url = ``;
35
38
  }
@@ -38,12 +41,14 @@ export class Wappi {
38
41
  }
39
42
  if (messangerType === "max") {
40
43
  url = `https://wappi.pro/maxapi/sync/message/send`;
44
+ token = this.maxAuth.token;
45
+ profile_id = this.maxAuth.profile_id;
41
46
  }
42
- let res = await fetch(url + `?profile_id=${this.profile_id}`, {
47
+ let res = await fetch(url + `?profile_id=${profile_id}`, {
43
48
  method: "POST",
44
49
  headers: {
45
50
  "Content-Type": "application/json",
46
- Authorization: this.token,
51
+ Authorization: token,
47
52
  },
48
53
 
49
54
  body: JSON.stringify({
@@ -71,6 +76,8 @@ export class Wappi {
71
76
  let fileUrl = messageData.fileUrl;
72
77
  let fileName = messageData.fileName;
73
78
  let url;
79
+ let token;
80
+ let profile_id;
74
81
  if (messangerType === "whatsApp") {
75
82
  url = ``;
76
83
  }
@@ -79,17 +86,19 @@ export class Wappi {
79
86
  }
80
87
  if (messangerType === "max") {
81
88
  url = `https://wappi.pro/maxapi/async/message/file/url/send`;
89
+ token = this.maxAuth.token;
90
+ profile_id = this.maxAuth.profile_id;
82
91
  }
83
92
 
84
93
  // Max при отправке pdf не прикрепляет сообщение caption: message, поэтому отправляем его отдельно
85
94
  if (fileName.includes(".pdf")) {
86
95
  await this.sendMessageWappi(messangerType, { phone: phone, message: message });
87
96
  }
88
- let res = await fetch(url + `?profile_id=${this.profile_id}`, {
97
+ let res = await fetch(url + `?profile_id=${profile_id}`, {
89
98
  method: "POST",
90
99
  headers: {
91
100
  "Content-Type": "application/json",
92
- Authorization: this.token,
101
+ Authorization: token,
93
102
  },
94
103
 
95
104
  body: JSON.stringify({
@@ -115,20 +124,43 @@ export class Wappi {
115
124
  return { error: true, message: "Отсутствует phone ", data: null };
116
125
  }
117
126
  let url;
127
+ let token;
128
+ let profile_id;
118
129
  if (messangerType === "whatsApp") {
119
130
  url = ``;
120
131
  }
121
132
  if (messangerType === "telegram") {
122
- url = ``;
133
+ // 1 Проверяем существует контакт или нет.
134
+ let contactCheck = await this.getContactTelegramWappi(phone);
135
+
136
+ // 2 Если существует, то номер в телеге есть, можем отправлять сообщение
137
+ if (!contactCheck.error && contactCheck.data.haveContact) {
138
+ contactCheck.data.check = true;
139
+ return { error: false, message: `Номер ${phone} проверен для мессенджера ${messangerType}`, data: contactCheck.data };
140
+ }
141
+
142
+ // 3 Если не существует, то номера в телеге нет, пробуем создать
143
+ let addContactResult = await this.addContactTelegramWappi(phone);
144
+
145
+ if (!addContactResult.error) {
146
+ // Если получается создать, отправляем информацию
147
+ addContactResult.data.check = true;
148
+ return { error: false, message: `Номер ${phone} успешно добавлен и проверен для мессенджера ${messangerType}`, data: addContactResult.data };
149
+ } else {
150
+ // Если не получается, то отправляем информацию об ошибке
151
+ return { error: true, message: `Не удалось проверить и добавить номер ${phone} в Telegram: ${addContactResult.message}`, data: addContactResult.data };
152
+ }
123
153
  }
124
154
  if (messangerType === "max") {
125
- url = `https://wappi.pro/maxapi/sync/contact/check`;
155
+ token = this.maxAuth.token;
156
+ profile_id = this.maxAuth.profile_id;
157
+ url = `https://wappi.pro/maxapi/sync/contact/check?profile_id=${profile_id}&phone=${phone}`;
126
158
  }
127
- let res = await fetch(url + `?profile_id=${this.profile_id}&phone=${phone}`, {
128
- method: "get",
159
+ let res = await fetch(url, {
160
+ method: "GET",
129
161
  headers: {
130
162
  "Content-Type": "application/json",
131
- Authorization: this.token,
163
+ Authorization: token,
132
164
  },
133
165
  });
134
166
  let data = await res.json();
@@ -143,4 +175,74 @@ export class Wappi {
143
175
  return { error: false, message: `Номер ${phone} проверен для мессенджера ${messangerType}`, data: data };
144
176
  }
145
177
  }
178
+ async getContactTelegramWappi(phone) {
179
+ if (!phone) {
180
+ return { error: true, message: "Отсутствует phone", data: null };
181
+ }
182
+ let token = this.telegaAuth.token;
183
+ let profile_id = this.telegaAuth.profile_id;
184
+ let url = `https://wappi.pro/tapi/sync/contact/get?profile_id=${profile_id}&phone=${phone}`;
185
+
186
+ try {
187
+ let res = await fetch(url, {
188
+ method: "GET",
189
+ headers: {
190
+ "Content-Type": "application/json",
191
+ Authorization: token,
192
+ },
193
+ });
194
+
195
+ let data = await res.json();
196
+
197
+ if (data.status !== "done") {
198
+ return { error: true, message: `Ошибка получения контакта ${phone} из Telegram`, data: data };
199
+ } else {
200
+ // Проверяем найден ли контакт
201
+ data.haveContact = data.contact ? true : false;
202
+
203
+ return { error: false, message: `Контакт ${phone} получен из Telegram`, data: data };
204
+ }
205
+ } catch (error) {
206
+ return { error: true, message: `Ошибка при запросе контакта: ${error.message}`, data: null };
207
+ }
208
+ }
209
+
210
+ async addContactTelegramWappi(phone) {
211
+ if (!phone) {
212
+ return { error: true, message: "Отсутствует phone", data: null };
213
+ }
214
+
215
+ // Генерируем случайную строку из четырех символов
216
+ const randomString = Math.random().toString(36).substring(2, 6).toUpperCase();
217
+ const contactName = `${phone}_${randomString}`;
218
+
219
+ let token = this.telegaAuth.token;
220
+ let profile_id = this.telegaAuth.profile_id;
221
+ let url = `https://wappi.pro/tapi/sync/contact/add?profile_id=${profile_id}`;
222
+
223
+ try {
224
+ let res = await fetch(url, {
225
+ method: "POST",
226
+ headers: {
227
+ "Content-Type": "application/json",
228
+ Authorization: token,
229
+ },
230
+ body: JSON.stringify({
231
+ phone: phone,
232
+ name: contactName,
233
+ }),
234
+ });
235
+
236
+ let data = await res.json();
237
+
238
+ if (data.status !== "done") {
239
+ return { error: true, message: `Ошибка создания контакта ${phone} в Telegram`, data: data };
240
+ } else {
241
+ data.haveContact = true;
242
+ return { error: false, message: `Контакт ${phone} успешно создан в Telegram`, data: data };
243
+ }
244
+ } catch (error) {
245
+ return { error: true, message: `Ошибка при создании контакта: ${error.message}`, data: null };
246
+ }
247
+ }
146
248
  }