@badzz88/baileys 8.5.2 → 8.5.4

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 (110) hide show
  1. package/README.md +1 -1
  2. package/WAProto/WAProto.proto +1256 -75
  3. package/WAProto/index.d.ts +36042 -19649
  4. package/WAProto/index.js +181990 -135645
  5. package/engine-requirements.js +7 -15
  6. package/lib/Defaults/index.js +22 -17
  7. package/lib/Signal/Group/group_cipher.js +5 -5
  8. package/lib/Signal/Group/keyhelper.js +4 -4
  9. package/lib/Signal/Group/sender-chain-key.js +2 -2
  10. package/lib/Signal/Group/sender-key-distribution-message.js +1 -1
  11. package/lib/Signal/Group/sender-key-message.js +3 -3
  12. package/lib/Signal/Group/sender-key-record.js +1 -1
  13. package/lib/Signal/Group/sender-message-key.js +5 -5
  14. package/lib/Signal/libsignal.js +39 -59
  15. package/lib/Signal/lid-mapping.js +28 -10
  16. package/lib/Socket/aigroups.js +5 -5
  17. package/lib/Socket/business.js +3 -11
  18. package/lib/Socket/chats.js +668 -319
  19. package/lib/Socket/communities.js +85 -89
  20. package/lib/Socket/graphql.js +435 -228
  21. package/lib/Socket/groups.js +132 -211
  22. package/lib/Socket/index.js +9 -7
  23. package/lib/Socket/interactive-handler.js +117 -60
  24. package/lib/Socket/interop.js +56 -175
  25. package/lib/Socket/managed-account.js +79 -48
  26. package/lib/Socket/messages-recv.js +898 -340
  27. package/lib/Socket/messages-send.js +462 -160
  28. package/lib/Socket/mex.js +40 -53
  29. package/lib/Socket/newsletter.js +291 -291
  30. package/lib/Socket/privacy.js +77 -265
  31. package/lib/Socket/registration.js +164 -157
  32. package/lib/Socket/socket.js +181 -199
  33. package/lib/Socket/username.js +144 -227
  34. package/lib/Store/make-cache-manager-store.js +2 -2
  35. package/lib/Store/make-in-memory-store.js +25 -141
  36. package/lib/Types/Auth.js +3 -3
  37. package/lib/Types/Label.js +1 -1
  38. package/lib/Types/LabelAssociation.js +1 -1
  39. package/lib/Types/Newsletter.js +96 -65
  40. package/lib/Types/State.js +4 -4
  41. package/lib/Types/index.js +1 -1
  42. package/lib/Utils/auth-utils.js +52 -57
  43. package/lib/Utils/browser-utils.js +1 -1
  44. package/lib/Utils/business.js +2 -6
  45. package/lib/Utils/chat-utils.js +102 -38
  46. package/lib/Utils/crypto.js +54 -84
  47. package/lib/Utils/decode-wa-message.js +316 -83
  48. package/lib/Utils/event-buffer.js +37 -61
  49. package/lib/Utils/generics.js +157 -103
  50. package/lib/Utils/group-history.js +3 -12
  51. package/lib/Utils/history.js +15 -15
  52. package/lib/Utils/index.js +1 -5
  53. package/lib/Utils/link-preview.js +3 -8
  54. package/lib/Utils/lt-hash.js +2 -35
  55. package/lib/Utils/make-mutex.js +1 -1
  56. package/lib/Utils/message-inspect.js +393 -0
  57. package/lib/Utils/message-retry-manager.js +27 -92
  58. package/lib/Utils/messages-media.js +159 -130
  59. package/lib/Utils/messages.js +144 -566
  60. package/lib/Utils/meta-ai-msmsg.js +62 -202
  61. package/lib/Utils/noise-handler.js +19 -21
  62. package/lib/Utils/offline-node-processor.js +3 -8
  63. package/lib/Utils/pre-key-manager.js +13 -23
  64. package/lib/Utils/process-message.js +197 -106
  65. package/lib/Utils/reporting-utils.js +2 -2
  66. package/lib/Utils/signal.js +28 -63
  67. package/lib/Utils/stanza-ack.js +39 -12
  68. package/lib/Utils/sync-action-utils.js +4 -7
  69. package/lib/Utils/tc-token-utils.js +20 -25
  70. package/lib/Utils/use-multi-file-auth-state.js +30 -14
  71. package/lib/Utils/validate-connection.js +59 -19
  72. package/lib/WABinary/decode.js +50 -16
  73. package/lib/WABinary/encode.js +54 -224
  74. package/lib/WABinary/generic-utils.js +7 -97
  75. package/lib/WABinary/jid-utils.js +27 -14
  76. package/lib/WAM/encode.js +7 -7
  77. package/lib/WAUSync/Protocols/USyncBusinessProtocol.js +58 -1
  78. package/lib/WAUSync/Protocols/USyncContactProtocol.js +7 -1
  79. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +13 -5
  80. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +1 -4
  81. package/lib/WAUSync/Protocols/USyncFeatureProtocol.js +20 -7
  82. package/lib/WAUSync/Protocols/USyncNewsletterProtocol.js +865 -0
  83. package/lib/WAUSync/Protocols/USyncPictureProtocol.js +1 -1
  84. package/lib/WAUSync/Protocols/USyncSidelistProtocol.js +2 -2
  85. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +7 -2
  86. package/lib/WAUSync/Protocols/USyncTextStatusProtocol.js +1 -1
  87. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +2 -1
  88. package/lib/WAUSync/Protocols/index.js +1 -0
  89. package/lib/WAUSync/USyncBackoff.js +26 -0
  90. package/lib/WAUSync/USyncQuery.js +77 -6
  91. package/lib/WAUSync/USyncUser.js +16 -8
  92. package/lib/WAUSync/index.js +1 -0
  93. package/lib/antiban.js +608 -854
  94. package/lib/index.js +3 -3
  95. package/package.json +16 -19
  96. package/lib/Socket/luxu.js +0 -387
  97. package/lib/Socket/text-router.js +0 -83
  98. package/lib/Store/keyed-db.js +0 -108
  99. package/lib/Types/Mex.js +0 -112
  100. package/lib/Utils/command-loader.d.ts +0 -31
  101. package/lib/Utils/command-loader.js +0 -100
  102. package/lib/Utils/companion-reg-client-utils.js +0 -42
  103. package/lib/Utils/curve25519-js.js +0 -275
  104. package/lib/Utils/native-bridge.js +0 -82
  105. package/lib/Utils/session-pool.d.ts +0 -16
  106. package/lib/Utils/session-pool.js +0 -94
  107. package/lib/Utils/sticker.d.ts +0 -17
  108. package/lib/Utils/sticker.js +0 -145
  109. package/lib/Utils/view-once-cache.d.ts +0 -9
  110. package/lib/Utils/view-once-cache.js +0 -79
package/lib/index.js CHANGED
@@ -57,12 +57,12 @@ console.log(chalk.bold.cyan(`
57
57
  ¤═―— ⎧ 𝐁𝐀𝐃𝐙𝐙 𝐁𝐀𝐈𝐋𝐄𝐘𝐒 ⎭ ⊱―—═¤
58
58
  Information:
59
59
  Developer: @badzzne2
60
- Version: 12.0
60
+ Version: 12.1
61
61
  Status: Baileys Berhasil Terinstall
62
- Update date: 09/08/26
62
+ Update date: 14/08/26
63
63
  `));
64
+ console.log(chalk.bold.cyan("Follow us at: t.me/FoxsSql to see the next update"));
64
65
  console.log(chalk.bold.gray("--------------------------------------------\n"));
65
- console.log(chalk.bold.cyan("Follow Our Telegram Channel To See Update Information: t.me/FoxsSql\n"));
66
66
  const index_1 = __importDefault(require('./Socket/index'))
67
67
  exports.makeWASocket = index_1.default
68
68
  __exportStar(require('../WAProto/index.js'), exports)
package/package.json CHANGED
@@ -1,21 +1,18 @@
1
1
  {
2
2
  "name": "@badzz88/baileys",
3
- "version": "8.5.2",
3
+ "version": "8.5.4",
4
4
  "description": "Baileys Whatsapp Api Modification By Badzz88",
5
5
  "keywords": [
6
6
  "whatsapp",
7
7
  "whatsapp-web",
8
8
  "whatsapp-api",
9
9
  "baileys",
10
- "multi-device",
11
10
  "wasm",
12
- "rust",
13
- "automation",
14
- "md"
11
+ "rust"
15
12
  ],
16
13
  "homepage": "https://www.npmjs.com/package/@badzz88/baileys",
17
14
  "repository": {
18
- "url": "https://github.com/package/Badzz88/baileys.giy"
15
+ "url": "https://github.com/Badzz88/baileys.git"
19
16
  },
20
17
  "license": "MIT",
21
18
  "author": "Badzz88",
@@ -28,9 +25,10 @@
28
25
  "scripts": {
29
26
  "ncu": "npm-check-updates",
30
27
  "format": "prettier --write \"lib/**/*.{js,json,md}\"",
31
- "lint": "tsc && eslint src --ext .js",
28
+ "lint": "tsc && eslint lib --ext .js",
32
29
  "lint:fix": "npm run format && npm run lint -- --fix",
33
- "test": "jest --runInBand"
30
+ "test": "jest --runInBand",
31
+ "preinstall": "node ./engine-requirements.js"
34
32
  },
35
33
  "dependencies": {
36
34
  "@adiwajshing/keyed-db": "^0.2.4",
@@ -44,9 +42,14 @@
44
42
  "p-queue": "^9.3.0",
45
43
  "pino": "^10.3.1",
46
44
  "protobufjs": "^7.6.1",
45
+ "qrcode-terminal": "^0.12.0",
46
+ "whatsapp-rust-bridge": "github:7ucg/whatsapp-rust-bridge",
47
47
  "ws": "^8.21.0",
48
- "whatsapp-rust-bridge": "0.5.4",
49
- "jimp": "^1.6.0"
48
+ "jimp": "^1.6.1",
49
+ "chalk": "^4.1.2",
50
+ "sharp": "^0.32.5",
51
+ "link-preview-js": "^3.2.0",
52
+ "audio-decode": "^2.1.3"
50
53
  },
51
54
  "devDependencies": {
52
55
  "@eslint/eslintrc": "^3.3.1",
@@ -61,7 +64,7 @@
61
64
  "eslint-config-prettier": "^10.1.8",
62
65
  "eslint-plugin-prettier": "^5.4.1",
63
66
  "jest": "^30.0.5",
64
- "jimp": "^1.6.0",
67
+ "jimp": "^1.6.1",
65
68
  "jiti": "^2.4.2",
66
69
  "json": "^11.0.0",
67
70
  "link-preview-js": "^3.2.0",
@@ -74,8 +77,8 @@
74
77
  },
75
78
  "peerDependencies": {
76
79
  "audio-decode": "^2.1.3",
80
+ "jimp": "^1.6.1",
77
81
  "link-preview-js": "^3.2.0",
78
- "@img/sharp-wasm32": "^0.35.1",
79
82
  "sharp": "^0.32.5"
80
83
  },
81
84
  "peerDependenciesMeta": {
@@ -88,18 +91,12 @@
88
91
  "link-preview-js": {
89
92
  "optional": true
90
93
  },
91
- "@img/sharp-wasm32": {
92
- "optional": true
93
- },
94
94
  "sharp": {
95
95
  "optional": true
96
- },
97
- "whatsapp-rust-bridge": {
98
- "optional": true
99
96
  }
100
97
  },
101
98
  "packageManager": "yarn@4.9.2",
102
99
  "engines": {
103
100
  "node": ">=20.0.0"
104
101
  }
105
- }
102
+ }
@@ -1,387 +0,0 @@
1
- import { proto } from '../../WAProto/index.js'
2
- import * as Utils from '../Utils/index.js'
3
- import crypto from 'crypto'
4
-
5
- export default class imup {
6
- constructor(utils, waUploadToServer, relayMessageFn) {
7
- this.utils = utils
8
- this.relayMessage = relayMessageFn
9
- this.waUploadToServer = waUploadToServer
10
- }
11
-
12
- detectType(content) {
13
- if (content.requestPaymentMessage) return 'PAYMENT'
14
- if (content.productMessage) return 'PRODUCT'
15
- if (content.albumMessage) return 'ALBUM'
16
- if (content.eventMessage) return 'EVENT'
17
- if (content.pollResultMessage) return 'POLL_RESULT'
18
- if (content.orderMessage) return 'ORDER'
19
- if (content.groupStatus) return 'GROUP_STATUS'
20
- if (content.groupLabel) return 'GROUP_LABEL'
21
- return null
22
- }
23
-
24
- async handlePayment(content, quoted) {
25
- const data = content.requestPaymentMessage
26
- let notes = {}
27
-
28
- if (data.sticker?.stickerMessage) {
29
- notes = {
30
- stickerMessage: {
31
- ...data.sticker.stickerMessage,
32
- contextInfo: {
33
- stanzaId: quoted?.key?.id,
34
- participant: quoted?.key?.participant || content.sender,
35
- quotedMessage: quoted?.message
36
- }
37
- }
38
- }
39
- } else if (data.note) {
40
- notes = {
41
- extendedTextMessage: {
42
- text: data.note,
43
- contextInfo: {
44
- stanzaId: quoted?.key?.id,
45
- participant: quoted?.key?.participant || content.sender,
46
- quotedMessage: quoted?.message
47
- }
48
- }
49
- }
50
- }
51
-
52
- return {
53
- requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({
54
- expiryTimestamp: data.expiry || 0,
55
- amount1000: data.amount || 0,
56
- currencyCodeIso4217: data.currency || "IDR",
57
- requestFrom: data.from || "0@s.whatsapp.net",
58
- noteMessage: notes,
59
- background: data.background?? {
60
- id: "DEFAULT",
61
- placeholderArgb: 0xFFF0F0F0
62
- }
63
- })
64
- }
65
- }
66
-
67
- async handleProduct(content, jid, quoted) {
68
- const {
69
- title,
70
- description,
71
- thumbnail,
72
- productId,
73
- retailerId,
74
- url,
75
- body = "",
76
- footer = "",
77
- buttons = [],
78
- priceAmount1000 = null,
79
- currencyCode = "IDR"
80
- } = content.productMessage
81
-
82
- let productImage
83
-
84
- if (Buffer.isBuffer(thumbnail)) {
85
- const { imageMessage } = await this.utils.generateWAMessageContent(
86
- { image: thumbnail },
87
- { upload: this.waUploadToServer }
88
- )
89
- productImage = imageMessage
90
- } else if (typeof thumbnail === 'object' && thumbnail.url) {
91
- const { imageMessage } = await this.utils.generateWAMessageContent(
92
- { image: { url: thumbnail.url } },
93
- { upload: this.waUploadToServer }
94
- )
95
- productImage = imageMessage
96
- }
97
-
98
- return {
99
- viewOnceMessage: {
100
- message: {
101
- interactiveMessage: {
102
- body: { text: body },
103
- footer: { text: footer },
104
- header: {
105
- title,
106
- hasMediaAttachment: true,
107
- productMessage: {
108
- product: {
109
- productImage,
110
- productId,
111
- title,
112
- description,
113
- currencyCode,
114
- priceAmount1000,
115
- retailerId,
116
- url,
117
- productImageCount: 1
118
- },
119
- businessOwnerJid: "0@s.whatsapp.net"
120
- }
121
- },
122
- nativeFlowMessage: { buttons }
123
- }
124
- }
125
- }
126
- }
127
- }
128
-
129
- async handleAlbum(content, jid, quoted) {
130
- const array = content.albumMessage
131
- const album = await this.utils.generateWAMessageFromContent(jid, {
132
- messageContextInfo: {
133
- messageSecret: crypto.randomBytes(32),
134
- },
135
- albumMessage: {
136
- expectedImageCount: array.filter((a) => a.hasOwnProperty("image")).length,
137
- expectedVideoCount: array.filter((a) => a.hasOwnProperty("video")).length,
138
- },
139
- }, {
140
- userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
141
- quoted,
142
- upload: this.waUploadToServer
143
- })
144
-
145
- await this.relayMessage(jid, album.message, {
146
- messageId: album.key.id,
147
- })
148
-
149
- for (let content of array) {
150
- const img = await this.utils.generateWAMessage(jid, content, {
151
- upload: this.waUploadToServer,
152
- })
153
-
154
- img.message.messageContextInfo = {
155
- messageSecret: crypto.randomBytes(32),
156
- messageAssociation: {
157
- associationType: 1,
158
- parentMessageKey: album.key,
159
- },
160
- participant: "0@s.whatsapp.net",
161
- remoteJid: "status@broadcast",
162
- forwardingScore: 99999,
163
- isForwarded: true,
164
- mentionedJid: [jid],
165
- starred: true,
166
- labels: ["Y", "Important"],
167
- isHighlighted: true,
168
- businessMessageForwardInfo: {
169
- businessOwnerJid: jid,
170
- },
171
- dataSharingContext: {
172
- showMmDisclosure: true,
173
- },
174
- }
175
-
176
- img.message.forwardedNewsletterMessageInfo = {
177
- newsletterJid: "0@newsletter",
178
- serverMessageId: 1,
179
- newsletterName: `WhatsApp`,
180
- contentType: 1,
181
- timestamp: new Date().toISOString(),
182
- senderName: "7-Yuukey",
183
- contentType: "UPDATE_CARD",
184
- priority: "high",
185
- status: "sent",
186
- }
187
-
188
- img.message.disappearingMode = {
189
- initiator: 3,
190
- trigger: 4,
191
- initiatorDeviceJid: jid,
192
- initiatedByExternalService: true,
193
- initiatedByUserDevice: true,
194
- initiatedBySystem: true,
195
- initiatedByServer: true,
196
- initiatedByAdmin: true,
197
- initiatedByUser: true,
198
- initiatedByApp: true,
199
- initiatedByBot: true,
200
- initiatedByMe: true,
201
- }
202
-
203
- await this.relayMessage(jid, img.message, {
204
- messageId: img.key.id,
205
- quoted: {
206
- key: {
207
- remoteJid: album.key.remoteJid,
208
- id: album.key.id,
209
- fromMe: true,
210
- participant: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
211
- },
212
- message: album.message,
213
- },
214
- })
215
- }
216
- return album
217
- }
218
-
219
- async handleEvent(content, jid, quoted) {
220
- const eventData = content.eventMessage
221
-
222
- const msg = await this.utils.generateWAMessageFromContent(jid, {
223
- viewOnceMessage: {
224
- message: {
225
- messageContextInfo: {
226
- deviceListMetadata: {},
227
- deviceListMetadataVersion: 2,
228
- messageSecret: crypto.randomBytes(32),
229
- supportPayload: JSON.stringify({
230
- version: 2,
231
- is_ai_message: true,
232
- should_show_system_message: true,
233
- ticket_id: crypto.randomBytes(16).toString('hex')
234
- })
235
- },
236
- eventMessage: {
237
- contextInfo: {
238
- mentionedJid: [jid],
239
- participant: jid,
240
- remoteJid: "status@broadcast",
241
- forwardedNewsletterMessageInfo: {
242
- newsletterName: "D | 7eppeli-Exloration",
243
- newsletterJid: "120363421563597486@newsletter",
244
- serverMessageId: 1
245
- }
246
- },
247
- isCanceled: eventData.isCanceled || false,
248
- name: eventData.name,
249
- description: eventData.description,
250
- location: eventData.location || {
251
- degreesLatitude: 0,
252
- degreesLongitude: 0,
253
- name: "Location"
254
- },
255
- joinLink: eventData.joinLink || '',
256
- startTime: typeof eventData.startTime === 'string'? parseInt(eventData.startTime) : eventData.startTime || Date.now(),
257
- endTime: typeof eventData.endTime === 'string'? parseInt(eventData.endTime) : eventData.endTime || Date.now() + 3600000,
258
- extraGuestsAllowed: eventData.extraGuestsAllowed!== false
259
- }
260
- }
261
- }
262
- }, { quoted })
263
-
264
- await this.relayMessage(jid, msg.message, {
265
- messageId: msg.key.id
266
- })
267
- return msg
268
- }
269
-
270
- async handlePollResult(content, jid, quoted) {
271
- const pollData = content.pollResultMessage
272
- const msg = await this.utils.generateWAMessageFromContent(jid, {
273
- pollResultSnapshotMessage: {
274
- name: pollData.name,
275
- pollVotes: pollData.pollVotes.map(vote => ({
276
- optionName: vote.optionName,
277
- optionVoteCount: typeof vote.optionVoteCount === 'number'
278
- ? vote.optionVoteCount.toString()
279
- : vote.optionVoteCount
280
- })),
281
- contextInfo: {
282
- isForwarded: true,
283
- forwardingScore: 1,
284
- forwardedNewsletterMessageInfo: {
285
- newsletterName: pollData.newsletter.newsletterName || "120363399602691477@newsletter",
286
- newsletterJid: pollData.newsletter.newsletterJid || "Newsletter",
287
- serverMessageId: 1000,
288
- contentType: "UPDATE"
289
- }
290
- }
291
- }
292
- }, {
293
- userJid: this.utils.generateMessageID().split('@')[0] + '@s.whatsapp.net',
294
- quoted
295
- })
296
-
297
- await this.relayMessage(jid, msg.message, {
298
- messageId: msg.key.id
299
- })
300
-
301
- return msg
302
- }
303
-
304
- async handleOrderMessage(content, jid, quoted) {
305
- const orderData = content.orderMessage
306
-
307
- const Haha = await this.utils.generateWAMessageFromContent(jid, {
308
- orderMessage: {
309
- orderId: "7EPPELI25022008",
310
- thumbnail: orderData.thumbnail || null,
311
- itemCount: orderData.itemCount || 0,
312
- status: "ACCEPTED",
313
- surface: "CATALOG",
314
- message: orderData.message,
315
- orderTitle: orderData.orderTitle,
316
- sellerJid: "0@whatsapp.net",
317
- token: "7EPPELI_EXAMPLE_TOKEN",
318
- totalAmount1000: orderData.totalAmount1000 || 0,
319
- totalCurrencyCode: orderData.totalCurrencyCode || "IDR",
320
- messageVersion: 2
321
- }
322
- }, { quoted: quoted })
323
-
324
- await this.relayMessage(jid, Haha.message, {})
325
- return Haha
326
- }
327
-
328
- async handleGroupStory(content, jid, quoted) {
329
- const storyData = content.groupStatus
330
- let messageContent
331
-
332
- if (storyData.message) {
333
- messageContent = storyData
334
- } else {
335
- if (typeof this.utils?.generateWAMessageContent === "function") {
336
- messageContent = await this.utils.generateWAMessageContent(storyData, {
337
- upload: this.waUploadToServer
338
- })
339
- } else {
340
- messageContent = await Utils.generateWAMessageContent(storyData, {
341
- upload: this.waUploadToServer
342
- })
343
- }
344
- }
345
-
346
- let msg = {
347
- message: {
348
- groupStatusMessageV2: {
349
- message: messageContent.message || messageContent
350
- }
351
- }
352
- }
353
-
354
- return await this.relayMessage(jid, msg.message, {
355
- messageId: this.utils.generateMessageID()
356
- })
357
- }
358
-
359
- async handleGbLabel(content, jid) {
360
- const x = content.groupLabel
361
- if (!jid.endsWith('@g.us')) {
362
- throw new Error('group required!')
363
- }
364
-
365
- const msg = this.utils.generateWAMessageFromContent(jid, {
366
- protocolMessage: {
367
- type: "GROUP_MEMBER_LABEL_CHANGE",
368
- memberLabel: {
369
- label: x.labelText.slice(0, 30)
370
- }
371
- }
372
- }, {})
373
-
374
- await this.relayMessage(jid, msg.message, {
375
- additionalNodes: [
376
- {
377
- tag: 'meta',
378
- attrs: {
379
- tag_reason: 'user_update',
380
- appdata: 'member_tag'
381
- },
382
- content: undefined
383
- }
384
- ]
385
- })
386
- }
387
- }
@@ -1,83 +0,0 @@
1
- 'use strict'
2
- Object.defineProperty(exports, '__esModule', { value: true })
3
- exports.attachTextRouter = void 0
4
-
5
- const extractText = message => {
6
- if (!message) return ''
7
- return (
8
- message.conversation ||
9
- message.extendedTextMessage?.text ||
10
- message.imageMessage?.caption ||
11
- message.videoMessage?.caption ||
12
- message.documentMessage?.caption ||
13
- ''
14
- )
15
- }
16
-
17
- const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
18
-
19
- /**
20
- * Attaches Telegraf text routing to a socket:
21
- * `sock.onText(pattern, handler)`, `sock.hears(pattern, handler)` (alias), and
22
- * `sock.command(name, handler)`, instead of manually parsing every
23
- * `messages.upsert` event by hand.
24
- *
25
- * - `pattern` as a RegExp: handler gets called as `handler(msg, match)` where
26
- * `match` is the result of `pattern.exec(text)` (or null if only testing).
27
- * - `pattern` as a string: matched literally (exact match) against the message
28
- * text; `handler(msg, [text])` is called on match.
29
- * - `sock.command('start', handler)`: matches `/start`, `/start@BotName`, and
30
- * `/start extra args`, calling `handler(msg, match)` where `match[1]` is the
31
- * text after the command (or undefined).
32
- *
33
- * All three return an unsubscribe function. Only one `messages.upsert`
34
- * listener is registered regardless of how many routes are added.
35
- */
36
- const attachTextRouter = sock => {
37
- const routes = []
38
-
39
- const addRoute = (pattern, handler) => {
40
- const route = { pattern, handler }
41
- routes.push(route)
42
- return () => {
43
- const idx = routes.indexOf(route)
44
- if (idx !== -1) routes.splice(idx, 1)
45
- }
46
- }
47
-
48
- const dispatch = async ({ messages, type }) => {
49
- if (type !== 'notify' && type !== 'append') return
50
- for (const msg of messages) {
51
- if (!msg.message || msg.key.fromMe) continue
52
- const text = extractText(msg.message)
53
- if (!text) continue
54
- for (const route of routes.slice()) {
55
- let match = null
56
- if (route.pattern instanceof RegExp) {
57
- route.pattern.lastIndex = 0
58
- match = route.pattern.exec(text)
59
- } else if (typeof route.pattern === 'string') {
60
- match = text === route.pattern ? [text] : null
61
- }
62
- if (!match) continue
63
- try {
64
- await route.handler(msg, match)
65
- } catch (error) {
66
- sock.logger?.error?.({ error, text }, 'onText/hears handler threw')
67
- }
68
- }
69
- }
70
- }
71
- sock.ev.on('messages.upsert', dispatch)
72
-
73
- sock.onText = addRoute
74
- sock.hears = addRoute
75
- sock.command = (name, handler) => {
76
- const names = (Array.isArray(name) ? name : [name]).map(escapeRegExp)
77
- const pattern = new RegExp(`^/(?:${names.join('|')})(?:@\\S+)?(?:\\s+([\\s\\S]*))?$`, 'i')
78
- return addRoute(pattern, handler)
79
- }
80
-
81
- return sock
82
- }
83
- exports.attachTextRouter = attachTextRouter
@@ -1,108 +0,0 @@
1
- export default class KeyedDB {
2
- constructor(compareFn, idGetter) {
3
- if (typeof compareFn !== "function" || typeof idGetter !== "function") {
4
- throw new Error("KeyedDB requires compare and idGetter functions");
5
- }
6
- this._compare = compareFn;
7
- this._idGetter = idGetter;
8
- this._array = [];
9
- this._dict = {};
10
- }
11
- get length() {
12
- return this._array.length;
13
- }
14
- get(id) {
15
- return this._dict[id];
16
- }
17
- insert(entry, mode = "insert") {
18
- const id = this._idGetter(entry);
19
- const existing = this._dict[id];
20
- if (existing && mode === "insert") {
21
- return false;
22
- }
23
- this._dict[id] = entry;
24
- let inserted = false;
25
- for (let i = 0; i < this._array.length; i++) {
26
- const cmp = this._compare(this._idGetter(this._array[i]), id);
27
- if (cmp < 0) {
28
- this._array.splice(i, 0, entry);
29
- inserted = true;
30
- break;
31
- }
32
- }
33
- if (!inserted) this._array.push(entry);
34
- return true;
35
- }
36
- insertIfAbsent(...entries) {
37
- const added = [];
38
- for (const entry of entries) {
39
- if (!this._dict[this._idGetter(entry)]) {
40
- this.insert(entry);
41
- added.push(entry);
42
- }
43
- }
44
- return added;
45
- }
46
- upsert(...entries) {
47
- const added = [];
48
- for (const entry of entries) {
49
- const id = this._idGetter(entry);
50
- if (this._dict[id]) {
51
- const idx = this._array.findIndex(e => this._idGetter(e) === id);
52
- if (idx >= 0) this._array[idx] = entry;
53
- this._dict[id] = entry;
54
- } else {
55
- this.insert(entry);
56
- added.push(entry);
57
- }
58
- }
59
- return added;
60
- }
61
- update(id, updater) {
62
- const item = this._dict[id];
63
- if (!item) return false;
64
- updater(item);
65
- const idx = this._array.findIndex(e => this._idGetter(e) === id);
66
- if (idx >= 0) this._array[idx] = item;
67
- return true;
68
- }
69
- updateAssign(id, update) {
70
- const item = this._dict[id];
71
- if (!item) return false;
72
- Object.assign(item, update);
73
- const idx = this._array.findIndex(e => this._idGetter(e) === id);
74
- if (idx >= 0) this._array[idx] = item;
75
- return true;
76
- }
77
- deleteById(id) {
78
- if (!this._dict[id]) return false;
79
- delete this._dict[id];
80
- const idx = this._array.findIndex(e => this._idGetter(e) === id);
81
- if (idx >= 0) this._array.splice(idx, 1);
82
- return true;
83
- }
84
- clear() {
85
- this._array = [];
86
- this._dict = {};
87
- }
88
- all() {
89
- return [...this._array];
90
- }
91
- filter(predicate) {
92
- this._array = this._array.filter(predicate);
93
- this._dict = {};
94
- for (const entry of this._array) {
95
- this._dict[this._idGetter(entry)] = entry;
96
- }
97
- }
98
- count() {
99
- return this._array.length;
100
- }
101
- toJSON() {
102
- return this._array;
103
- }
104
- fromJSON(array) {
105
- this.clear();
106
- for (const entry of array) this.insert(entry);
107
- }
108
- }