lordceaser-baileys 3.3.8 → 3.3.9

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 (445) hide show
  1. package/index.js +5 -16
  2. package/package.json +6 -2
  3. package/WAProto/GenerateStatics.sh +0 -3
  4. package/WAProto/V +0 -1
  5. package/WAProto/WAProto.proto +0 -8423
  6. package/WAProto/_orig.js +0 -300786
  7. package/WAProto/fix-imports.js +0 -85
  8. package/WAProto/index.d.ts +0 -99320
  9. package/WAProto/index.js +0 -3
  10. package/lib/Defaults/index.d.ts +0 -75
  11. package/lib/Defaults/index.d.ts.map +0 -1
  12. package/lib/Defaults/index.js +0 -129
  13. package/lib/Defaults/index.js.map +0 -1
  14. package/lib/Signal/Group/ciphertext-message.d.ts +0 -10
  15. package/lib/Signal/Group/ciphertext-message.d.ts.map +0 -1
  16. package/lib/Signal/Group/ciphertext-message.js +0 -12
  17. package/lib/Signal/Group/ciphertext-message.js.map +0 -1
  18. package/lib/Signal/Group/group-session-builder.d.ts +0 -15
  19. package/lib/Signal/Group/group-session-builder.d.ts.map +0 -1
  20. package/lib/Signal/Group/group-session-builder.js +0 -30
  21. package/lib/Signal/Group/group-session-builder.js.map +0 -1
  22. package/lib/Signal/Group/group_cipher.d.ts +0 -17
  23. package/lib/Signal/Group/group_cipher.d.ts.map +0 -1
  24. package/lib/Signal/Group/group_cipher.js +0 -82
  25. package/lib/Signal/Group/group_cipher.js.map +0 -1
  26. package/lib/Signal/Group/index.d.ts +0 -12
  27. package/lib/Signal/Group/index.d.ts.map +0 -1
  28. package/lib/Signal/Group/index.js +0 -12
  29. package/lib/Signal/Group/index.js.map +0 -1
  30. package/lib/Signal/Group/keyhelper.d.ts +0 -11
  31. package/lib/Signal/Group/keyhelper.d.ts.map +0 -1
  32. package/lib/Signal/Group/keyhelper.js +0 -18
  33. package/lib/Signal/Group/keyhelper.js.map +0 -1
  34. package/lib/Signal/Group/sender-chain-key.d.ts +0 -14
  35. package/lib/Signal/Group/sender-chain-key.d.ts.map +0 -1
  36. package/lib/Signal/Group/sender-chain-key.js +0 -26
  37. package/lib/Signal/Group/sender-chain-key.js.map +0 -1
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts +0 -17
  39. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +0 -1
  40. package/lib/Signal/Group/sender-key-distribution-message.js +0 -63
  41. package/lib/Signal/Group/sender-key-distribution-message.js.map +0 -1
  42. package/lib/Signal/Group/sender-key-message.d.ts +0 -19
  43. package/lib/Signal/Group/sender-key-message.d.ts.map +0 -1
  44. package/lib/Signal/Group/sender-key-message.js +0 -66
  45. package/lib/Signal/Group/sender-key-message.js.map +0 -1
  46. package/lib/Signal/Group/sender-key-name.d.ts +0 -18
  47. package/lib/Signal/Group/sender-key-name.d.ts.map +0 -1
  48. package/lib/Signal/Group/sender-key-name.js +0 -48
  49. package/lib/Signal/Group/sender-key-name.js.map +0 -1
  50. package/lib/Signal/Group/sender-key-record.d.ts +0 -31
  51. package/lib/Signal/Group/sender-key-record.d.ts.map +0 -1
  52. package/lib/Signal/Group/sender-key-record.js +0 -41
  53. package/lib/Signal/Group/sender-key-record.js.map +0 -1
  54. package/lib/Signal/Group/sender-key-state.d.ts +0 -39
  55. package/lib/Signal/Group/sender-key-state.d.ts.map +0 -1
  56. package/lib/Signal/Group/sender-key-state.js +0 -84
  57. package/lib/Signal/Group/sender-key-state.js.map +0 -1
  58. package/lib/Signal/Group/sender-message-key.d.ts +0 -12
  59. package/lib/Signal/Group/sender-message-key.d.ts.map +0 -1
  60. package/lib/Signal/Group/sender-message-key.js +0 -26
  61. package/lib/Signal/Group/sender-message-key.js.map +0 -1
  62. package/lib/Signal/libsignal.d.ts +0 -5
  63. package/lib/Signal/libsignal.d.ts.map +0 -1
  64. package/lib/Signal/libsignal.js +0 -431
  65. package/lib/Signal/libsignal.js.map +0 -1
  66. package/lib/Signal/lid-mapping.d.ts +0 -23
  67. package/lib/Signal/lid-mapping.d.ts.map +0 -1
  68. package/lib/Signal/lid-mapping.js +0 -277
  69. package/lib/Signal/lid-mapping.js.map +0 -1
  70. package/lib/Socket/Client/index.d.ts +0 -3
  71. package/lib/Socket/Client/index.d.ts.map +0 -1
  72. package/lib/Socket/Client/index.js +0 -3
  73. package/lib/Socket/Client/index.js.map +0 -1
  74. package/lib/Socket/Client/types.d.ts +0 -16
  75. package/lib/Socket/Client/types.d.ts.map +0 -1
  76. package/lib/Socket/Client/types.js +0 -11
  77. package/lib/Socket/Client/types.js.map +0 -1
  78. package/lib/Socket/Client/websocket.d.ts +0 -13
  79. package/lib/Socket/Client/websocket.d.ts.map +0 -1
  80. package/lib/Socket/Client/websocket.js +0 -54
  81. package/lib/Socket/Client/websocket.js.map +0 -1
  82. package/lib/Socket/Socket/Client/index.js +0 -2
  83. package/lib/Socket/Socket/Client/types.js +0 -10
  84. package/lib/Socket/Socket/Client/websocket.js +0 -53
  85. package/lib/Socket/Socket/aigroups.js +0 -315
  86. package/lib/Socket/Socket/ban-checker.js +0 -153
  87. package/lib/Socket/Socket/business.js +0 -407
  88. package/lib/Socket/Socket/chats.js +0 -1908
  89. package/lib/Socket/Socket/chats.js[old] +0 -1227
  90. package/lib/Socket/Socket/communities.js +0 -431
  91. package/lib/Socket/Socket/graphql.js +0 -899
  92. package/lib/Socket/Socket/groups.js +0 -549
  93. package/lib/Socket/Socket/groups.js[old] +0 -347
  94. package/lib/Socket/Socket/index.js +0 -37
  95. package/lib/Socket/Socket/interactive-handler.js +0 -600
  96. package/lib/Socket/Socket/interop.js +0 -563
  97. package/lib/Socket/Socket/managed-account.js +0 -208
  98. package/lib/Socket/Socket/messages-recv.js +0 -2144
  99. package/lib/Socket/Socket/messages-send.js +0 -3177
  100. package/lib/Socket/Socket/mex.js +0 -41
  101. package/lib/Socket/Socket/newsletter.js +0 -260
  102. package/lib/Socket/Socket/privacy.js +0 -446
  103. package/lib/Socket/Socket/registration.js +0 -428
  104. package/lib/Socket/Socket/socket.js +0 -1017
  105. package/lib/Socket/Socket/username.js +0 -229
  106. package/lib/Socket/business.d.ts +0 -217
  107. package/lib/Socket/business.d.ts.map +0 -1
  108. package/lib/Socket/business.js +0 -379
  109. package/lib/Socket/business.js.map +0 -1
  110. package/lib/Socket/chats.d.ts +0 -125
  111. package/lib/Socket/chats.d.ts.map +0 -1
  112. package/lib/Socket/chats.js +0 -1198
  113. package/lib/Socket/chats.js.map +0 -1
  114. package/lib/Socket/communities.d.ts +0 -273
  115. package/lib/Socket/communities.d.ts.map +0 -1
  116. package/lib/Socket/communities.js +0 -431
  117. package/lib/Socket/communities.js.map +0 -1
  118. package/lib/Socket/groups.d.ts +0 -161
  119. package/lib/Socket/groups.d.ts.map +0 -1
  120. package/lib/Socket/groups.js +0 -347
  121. package/lib/Socket/groups.js.map +0 -1
  122. package/lib/Socket/index.d.ts +0 -260
  123. package/lib/Socket/index.d.ts.map +0 -1
  124. package/lib/Socket/index.js +0 -12
  125. package/lib/Socket/index.js.map +0 -1
  126. package/lib/Socket/messages-recv.d.ts +0 -203
  127. package/lib/Socket/messages-recv.d.ts.map +0 -1
  128. package/lib/Socket/messages-recv.js +0 -1772
  129. package/lib/Socket/messages-recv.js.map +0 -1
  130. package/lib/Socket/messages-send.d.ts +0 -199
  131. package/lib/Socket/messages-send.d.ts.map +0 -1
  132. package/lib/Socket/messages-send.js +0 -1145
  133. package/lib/Socket/messages-send.js.map +0 -1
  134. package/lib/Socket/mex.d.ts +0 -3
  135. package/lib/Socket/mex.d.ts.map +0 -1
  136. package/lib/Socket/mex.js +0 -42
  137. package/lib/Socket/mex.js.map +0 -1
  138. package/lib/Socket/newsletter.d.ts +0 -170
  139. package/lib/Socket/newsletter.d.ts.map +0 -1
  140. package/lib/Socket/newsletter.js +0 -181
  141. package/lib/Socket/newsletter.js.map +0 -1
  142. package/lib/Socket/package.json +0 -1
  143. package/lib/Socket/socket.d.ts +0 -59
  144. package/lib/Socket/socket.d.ts.map +0 -1
  145. package/lib/Socket/socket.js +0 -970
  146. package/lib/Socket/socket.js.map +0 -1
  147. package/lib/Types/Auth.d.ts +0 -117
  148. package/lib/Types/Auth.d.ts.map +0 -1
  149. package/lib/Types/Auth.js +0 -2
  150. package/lib/Types/Auth.js.map +0 -1
  151. package/lib/Types/Bussines.d.ts +0 -25
  152. package/lib/Types/Bussines.d.ts.map +0 -1
  153. package/lib/Types/Bussines.js +0 -2
  154. package/lib/Types/Bussines.js.map +0 -1
  155. package/lib/Types/Call.d.ts +0 -15
  156. package/lib/Types/Call.d.ts.map +0 -1
  157. package/lib/Types/Call.js +0 -2
  158. package/lib/Types/Call.js.map +0 -1
  159. package/lib/Types/Chat.d.ts +0 -124
  160. package/lib/Types/Chat.d.ts.map +0 -1
  161. package/lib/Types/Chat.js +0 -8
  162. package/lib/Types/Chat.js.map +0 -1
  163. package/lib/Types/Contact.d.ts +0 -26
  164. package/lib/Types/Contact.d.ts.map +0 -1
  165. package/lib/Types/Contact.js +0 -2
  166. package/lib/Types/Contact.js.map +0 -1
  167. package/lib/Types/Events.d.ts +0 -256
  168. package/lib/Types/Events.d.ts.map +0 -1
  169. package/lib/Types/Events.js +0 -2
  170. package/lib/Types/Events.js.map +0 -1
  171. package/lib/Types/GroupMetadata.d.ts +0 -71
  172. package/lib/Types/GroupMetadata.d.ts.map +0 -1
  173. package/lib/Types/GroupMetadata.js +0 -2
  174. package/lib/Types/GroupMetadata.js.map +0 -1
  175. package/lib/Types/Label.d.ts +0 -47
  176. package/lib/Types/Label.d.ts.map +0 -1
  177. package/lib/Types/Label.js +0 -25
  178. package/lib/Types/Label.js.map +0 -1
  179. package/lib/Types/LabelAssociation.d.ts +0 -30
  180. package/lib/Types/LabelAssociation.d.ts.map +0 -1
  181. package/lib/Types/LabelAssociation.js +0 -7
  182. package/lib/Types/LabelAssociation.js.map +0 -1
  183. package/lib/Types/Message.d.ts +0 -320
  184. package/lib/Types/Message.d.ts.map +0 -1
  185. package/lib/Types/Message.js +0 -11
  186. package/lib/Types/Message.js.map +0 -1
  187. package/lib/Types/Mex.d.ts +0 -141
  188. package/lib/Types/Mex.d.ts.map +0 -1
  189. package/lib/Types/Mex.js +0 -37
  190. package/lib/Types/Mex.js.map +0 -1
  191. package/lib/Types/Product.d.ts +0 -79
  192. package/lib/Types/Product.d.ts.map +0 -1
  193. package/lib/Types/Product.js +0 -2
  194. package/lib/Types/Product.js.map +0 -1
  195. package/lib/Types/Signal.d.ts +0 -87
  196. package/lib/Types/Signal.d.ts.map +0 -1
  197. package/lib/Types/Signal.js +0 -2
  198. package/lib/Types/Signal.js.map +0 -1
  199. package/lib/Types/Socket.d.ts +0 -136
  200. package/lib/Types/Socket.d.ts.map +0 -1
  201. package/lib/Types/Socket.js +0 -3
  202. package/lib/Types/Socket.js.map +0 -1
  203. package/lib/Types/State.d.ts +0 -97
  204. package/lib/Types/State.d.ts.map +0 -1
  205. package/lib/Types/State.js +0 -56
  206. package/lib/Types/State.js.map +0 -1
  207. package/lib/Types/USync.d.ts +0 -26
  208. package/lib/Types/USync.d.ts.map +0 -1
  209. package/lib/Types/USync.js +0 -2
  210. package/lib/Types/USync.js.map +0 -1
  211. package/lib/Types/index.d.ts +0 -66
  212. package/lib/Types/index.d.ts.map +0 -1
  213. package/lib/Types/index.js +0 -26
  214. package/lib/Types/index.js.map +0 -1
  215. package/lib/Utils/_crypto_orig.js +0 -118
  216. package/lib/Utils/auth-utils.d.ts +0 -24
  217. package/lib/Utils/auth-utils.d.ts.map +0 -1
  218. package/lib/Utils/auth-utils.js +0 -302
  219. package/lib/Utils/auth-utils.js.map +0 -1
  220. package/lib/Utils/browser-utils.d.ts +0 -4
  221. package/lib/Utils/browser-utils.d.ts.map +0 -1
  222. package/lib/Utils/browser-utils.js +0 -29
  223. package/lib/Utils/browser-utils.js.map +0 -1
  224. package/lib/Utils/business.d.ts +0 -23
  225. package/lib/Utils/business.d.ts.map +0 -1
  226. package/lib/Utils/business.js +0 -231
  227. package/lib/Utils/business.js.map +0 -1
  228. package/lib/Utils/chat-utils.d.ts +0 -100
  229. package/lib/Utils/chat-utils.d.ts.map +0 -1
  230. package/lib/Utils/chat-utils.js +0 -872
  231. package/lib/Utils/chat-utils.js.map +0 -1
  232. package/lib/Utils/companion-reg-client-utils.d.ts +0 -17
  233. package/lib/Utils/companion-reg-client-utils.d.ts.map +0 -1
  234. package/lib/Utils/companion-reg-client-utils.js +0 -35
  235. package/lib/Utils/companion-reg-client-utils.js.map +0 -1
  236. package/lib/Utils/crypto.d.ts +0 -37
  237. package/lib/Utils/crypto.d.ts.map +0 -1
  238. package/lib/Utils/crypto.js +0 -5
  239. package/lib/Utils/crypto.js.map +0 -1
  240. package/lib/Utils/decode-wa-message.d.ts +0 -66
  241. package/lib/Utils/decode-wa-message.d.ts.map +0 -1
  242. package/lib/Utils/decode-wa-message.js +0 -317
  243. package/lib/Utils/decode-wa-message.js.map +0 -1
  244. package/lib/Utils/event-buffer.d.ts +0 -36
  245. package/lib/Utils/event-buffer.d.ts.map +0 -1
  246. package/lib/Utils/event-buffer.js +0 -622
  247. package/lib/Utils/event-buffer.js.map +0 -1
  248. package/lib/Utils/generics.d.ts +0 -92
  249. package/lib/Utils/generics.d.ts.map +0 -1
  250. package/lib/Utils/generics.js +0 -393
  251. package/lib/Utils/generics.js.map +0 -1
  252. package/lib/Utils/history.d.ts +0 -24
  253. package/lib/Utils/history.d.ts.map +0 -1
  254. package/lib/Utils/history.js +0 -134
  255. package/lib/Utils/history.js.map +0 -1
  256. package/lib/Utils/identity-change-handler.d.ts +0 -44
  257. package/lib/Utils/identity-change-handler.d.ts.map +0 -1
  258. package/lib/Utils/identity-change-handler.js +0 -50
  259. package/lib/Utils/identity-change-handler.js.map +0 -1
  260. package/lib/Utils/index.d.ts +0 -22
  261. package/lib/Utils/index.d.ts.map +0 -1
  262. package/lib/Utils/index.js +0 -22
  263. package/lib/Utils/index.js.map +0 -1
  264. package/lib/Utils/link-preview.d.ts +0 -21
  265. package/lib/Utils/link-preview.d.ts.map +0 -1
  266. package/lib/Utils/link-preview.js +0 -85
  267. package/lib/Utils/link-preview.js.map +0 -1
  268. package/lib/Utils/logger.d.ts +0 -12
  269. package/lib/Utils/logger.d.ts.map +0 -1
  270. package/lib/Utils/logger.js +0 -3
  271. package/lib/Utils/logger.js.map +0 -1
  272. package/lib/Utils/lt-hash.d.ts +0 -8
  273. package/lib/Utils/lt-hash.d.ts.map +0 -1
  274. package/lib/Utils/lt-hash.js +0 -8
  275. package/lib/Utils/lt-hash.js.map +0 -1
  276. package/lib/Utils/make-mutex.d.ts +0 -9
  277. package/lib/Utils/make-mutex.d.ts.map +0 -1
  278. package/lib/Utils/make-mutex.js +0 -33
  279. package/lib/Utils/make-mutex.js.map +0 -1
  280. package/lib/Utils/message-retry-manager.d.ts +0 -115
  281. package/lib/Utils/message-retry-manager.d.ts.map +0 -1
  282. package/lib/Utils/message-retry-manager.js +0 -265
  283. package/lib/Utils/message-retry-manager.js.map +0 -1
  284. package/lib/Utils/messages-media.d.ts +0 -133
  285. package/lib/Utils/messages-media.d.ts.map +0 -1
  286. package/lib/Utils/messages-media.js +0 -788
  287. package/lib/Utils/messages-media.js.map +0 -1
  288. package/lib/Utils/messages.d.ts +0 -91
  289. package/lib/Utils/messages.d.ts.map +0 -1
  290. package/lib/Utils/messages.js +0 -893
  291. package/lib/Utils/messages.js.map +0 -1
  292. package/lib/Utils/noise-handler.d.ts +0 -20
  293. package/lib/Utils/noise-handler.d.ts.map +0 -1
  294. package/lib/Utils/noise-handler.js +0 -201
  295. package/lib/Utils/noise-handler.js.map +0 -1
  296. package/lib/Utils/offline-node-processor.d.ts +0 -17
  297. package/lib/Utils/offline-node-processor.d.ts.map +0 -1
  298. package/lib/Utils/offline-node-processor.js +0 -40
  299. package/lib/Utils/offline-node-processor.js.map +0 -1
  300. package/lib/Utils/package.json +0 -1
  301. package/lib/Utils/pre-key-manager.d.ts +0 -28
  302. package/lib/Utils/pre-key-manager.d.ts.map +0 -1
  303. package/lib/Utils/pre-key-manager.js +0 -106
  304. package/lib/Utils/pre-key-manager.js.map +0 -1
  305. package/lib/Utils/process-message.d.ts +0 -60
  306. package/lib/Utils/process-message.d.ts.map +0 -1
  307. package/lib/Utils/process-message.js +0 -630
  308. package/lib/Utils/process-message.js.map +0 -1
  309. package/lib/Utils/reporting-utils.d.ts +0 -11
  310. package/lib/Utils/reporting-utils.d.ts.map +0 -1
  311. package/lib/Utils/reporting-utils.js +0 -258
  312. package/lib/Utils/reporting-utils.js.map +0 -1
  313. package/lib/Utils/signal.d.ts +0 -47
  314. package/lib/Utils/signal.d.ts.map +0 -1
  315. package/lib/Utils/signal.js +0 -201
  316. package/lib/Utils/signal.js.map +0 -1
  317. package/lib/Utils/stanza-ack.d.ts +0 -11
  318. package/lib/Utils/stanza-ack.d.ts.map +0 -1
  319. package/lib/Utils/stanza-ack.js +0 -38
  320. package/lib/Utils/stanza-ack.js.map +0 -1
  321. package/lib/Utils/sync-action-utils.d.ts +0 -19
  322. package/lib/Utils/sync-action-utils.d.ts.map +0 -1
  323. package/lib/Utils/sync-action-utils.js +0 -49
  324. package/lib/Utils/sync-action-utils.js.map +0 -1
  325. package/lib/Utils/tc-token-utils.d.ts +0 -37
  326. package/lib/Utils/tc-token-utils.d.ts.map +0 -1
  327. package/lib/Utils/tc-token-utils.js +0 -164
  328. package/lib/Utils/tc-token-utils.js.map +0 -1
  329. package/lib/Utils/use-multi-file-auth-state.d.ts +0 -13
  330. package/lib/Utils/use-multi-file-auth-state.d.ts.map +0 -1
  331. package/lib/Utils/use-multi-file-auth-state.js +0 -121
  332. package/lib/Utils/use-multi-file-auth-state.js.map +0 -1
  333. package/lib/Utils/validate-connection.d.ts +0 -11
  334. package/lib/Utils/validate-connection.d.ts.map +0 -1
  335. package/lib/Utils/validate-connection.js +0 -210
  336. package/lib/Utils/validate-connection.js.map +0 -1
  337. package/lib/WABinary/constants.d.ts +0 -28
  338. package/lib/WABinary/constants.d.ts.map +0 -1
  339. package/lib/WABinary/constants.js +0 -1301
  340. package/lib/WABinary/constants.js.map +0 -1
  341. package/lib/WABinary/decode.d.ts +0 -7
  342. package/lib/WABinary/decode.d.ts.map +0 -1
  343. package/lib/WABinary/decode.js +0 -262
  344. package/lib/WABinary/decode.js.map +0 -1
  345. package/lib/WABinary/encode.d.ts +0 -3
  346. package/lib/WABinary/encode.d.ts.map +0 -1
  347. package/lib/WABinary/encode.js +0 -220
  348. package/lib/WABinary/encode.js.map +0 -1
  349. package/lib/WABinary/generic-utils.d.ts +0 -15
  350. package/lib/WABinary/generic-utils.d.ts.map +0 -1
  351. package/lib/WABinary/generic-utils.js +0 -113
  352. package/lib/WABinary/generic-utils.js.map +0 -1
  353. package/lib/WABinary/index.d.ts +0 -6
  354. package/lib/WABinary/index.d.ts.map +0 -1
  355. package/lib/WABinary/index.js +0 -6
  356. package/lib/WABinary/index.js.map +0 -1
  357. package/lib/WABinary/jid-utils.d.ts +0 -48
  358. package/lib/WABinary/jid-utils.d.ts.map +0 -1
  359. package/lib/WABinary/jid-utils.js +0 -96
  360. package/lib/WABinary/jid-utils.js.map +0 -1
  361. package/lib/WABinary/types.d.ts +0 -19
  362. package/lib/WABinary/types.d.ts.map +0 -1
  363. package/lib/WABinary/types.js +0 -2
  364. package/lib/WABinary/types.js.map +0 -1
  365. package/lib/WAM/BinaryInfo.d.ts +0 -9
  366. package/lib/WAM/BinaryInfo.d.ts.map +0 -1
  367. package/lib/WAM/BinaryInfo.js +0 -10
  368. package/lib/WAM/BinaryInfo.js.map +0 -1
  369. package/lib/WAM/constants.d.ts +0 -40
  370. package/lib/WAM/constants.d.ts.map +0 -1
  371. package/lib/WAM/constants.js +0 -22853
  372. package/lib/WAM/constants.js.map +0 -1
  373. package/lib/WAM/encode.d.ts +0 -3
  374. package/lib/WAM/encode.d.ts.map +0 -1
  375. package/lib/WAM/encode.js +0 -150
  376. package/lib/WAM/encode.js.map +0 -1
  377. package/lib/WAM/index.d.ts +0 -4
  378. package/lib/WAM/index.d.ts.map +0 -1
  379. package/lib/WAM/index.js +0 -4
  380. package/lib/WAM/index.js.map +0 -1
  381. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +0 -10
  382. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +0 -1
  383. package/lib/WAUSync/Protocols/USyncContactProtocol.js +0 -52
  384. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +0 -1
  385. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +0 -23
  386. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +0 -1
  387. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +0 -54
  388. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +0 -1
  389. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +0 -13
  390. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +0 -1
  391. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -27
  392. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +0 -1
  393. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +0 -13
  394. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +0 -1
  395. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +0 -38
  396. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +0 -1
  397. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +0 -10
  398. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +0 -1
  399. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +0 -25
  400. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +0 -1
  401. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +0 -26
  402. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +0 -1
  403. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -51
  404. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +0 -1
  405. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +0 -10
  406. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +0 -1
  407. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +0 -29
  408. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +0 -1
  409. package/lib/WAUSync/Protocols/index.d.ts +0 -6
  410. package/lib/WAUSync/Protocols/index.d.ts.map +0 -1
  411. package/lib/WAUSync/Protocols/index.js +0 -6
  412. package/lib/WAUSync/Protocols/index.js.map +0 -1
  413. package/lib/WAUSync/USyncQuery.d.ts +0 -30
  414. package/lib/WAUSync/USyncQuery.d.ts.map +0 -1
  415. package/lib/WAUSync/USyncQuery.js +0 -98
  416. package/lib/WAUSync/USyncQuery.js.map +0 -1
  417. package/lib/WAUSync/USyncUser.d.ts +0 -17
  418. package/lib/WAUSync/USyncUser.d.ts.map +0 -1
  419. package/lib/WAUSync/USyncUser.js +0 -31
  420. package/lib/WAUSync/USyncUser.js.map +0 -1
  421. package/lib/WAUSync/WAUSync/Protocols/USyncBusinessProtocol.js +0 -96
  422. package/lib/WAUSync/WAUSync/Protocols/USyncContactProtocol.js +0 -56
  423. package/lib/WAUSync/WAUSync/Protocols/USyncDeviceProtocol.js +0 -53
  424. package/lib/WAUSync/WAUSync/Protocols/USyncDisappearingModeProtocol.js +0 -26
  425. package/lib/WAUSync/WAUSync/Protocols/USyncFeatureProtocol.js +0 -70
  426. package/lib/WAUSync/WAUSync/Protocols/USyncPictureProtocol.js +0 -28
  427. package/lib/WAUSync/WAUSync/Protocols/USyncSidelistProtocol.js +0 -25
  428. package/lib/WAUSync/WAUSync/Protocols/USyncStatusProtocol.js +0 -37
  429. package/lib/WAUSync/WAUSync/Protocols/USyncTextStatusProtocol.js +0 -34
  430. package/lib/WAUSync/WAUSync/Protocols/USyncUsernameProtocol.js +0 -24
  431. package/lib/WAUSync/WAUSync/Protocols/UsyncBotProfileProtocol.js +0 -50
  432. package/lib/WAUSync/WAUSync/Protocols/UsyncLIDProtocol.js +0 -28
  433. package/lib/WAUSync/WAUSync/Protocols/index.js +0 -12
  434. package/lib/WAUSync/WAUSync/USyncQuery.js +0 -201
  435. package/lib/WAUSync/WAUSync/USyncUser.js +0 -54
  436. package/lib/WAUSync/WAUSync/index.js +0 -3
  437. package/lib/WAUSync/index.d.ts +0 -4
  438. package/lib/WAUSync/index.d.ts.map +0 -1
  439. package/lib/WAUSync/index.js +0 -4
  440. package/lib/WAUSync/index.js.map +0 -1
  441. package/lib/index.d.ts +0 -12
  442. package/lib/index.d.ts.map +0 -1
  443. package/lib/index.js +0 -11
  444. package/lib/index.js.map +0 -1
  445. package/lib/package.json +0 -1
@@ -1,3177 +0,0 @@
1
- import NodeCache from '@cacheable/node-cache';
2
- import { Boom } from '@hapi/boom';
3
- import { randomBytes, randomUUID } from 'crypto';
4
- import { proto } from '../../WAProto/index.js';
5
- import { BIZ_BOT_SUPPORT_PAYLOAD, DEFAULT_CACHE_TTLS, WA_DEFAULT_EPHEMERAL } from '../Defaults/index.js';
6
- import { aggregateMessageKeysNotFromMe, assertMediaContent, assertMeId, bindWaitForEvent, buildLinkPreview, decryptMediaRetryData, DEF_MEDIA_HOST, delay, encodeNewsletterMessage, encodeSignedDeviceIdentity, encodeWAMessage, encryptMediaRetryRequest, extractDeviceJids, extractImageThumb, generateMessageIDV2, generateParticipantHashV2, generateWAMessage, generateWAMessageFromContent, getStatusCodeForMediaRetry, makeWhatsAppFlowButton, getUrlFromDirectPath, getWAUploadToServer, MessageRetryManager, normalizeMessageContent, parseAndInjectE2ESessions, prepareWAMessageMedia, shouldIncludeBizBinaryNode, unixTimestampSeconds } from '../Utils/index.js';
7
- import { getUrlInfo } from '../Utils/link-preview.js';
8
- import { prepareRichMenuMessage, prepareA2UIMessage, prepareA2UICommandMenu, prepareAIRichCommandMenu, prepareSocialEntityMessage, prepareInstagramProfileMessage, prepareRichResponseMessage, prepareRichGenerationMessage, prepareCopyToClipboardMessage, prepareRichTextMessage, prepareRichQuoteMessage, prepareRichImageMessage, prepareRichLinkMessage, prepareSocialProfileMessage, prepareUnifiedResponseMessage, prepareRichMapMessage, prepareBotPromptSuggestionsMessage, prepareBotSourcesMessage, prepareRichDynamicMediaMessage, prepareBotPttTranscriptMessage, prepareGridImageMessage, prepareVerticalAlbumMessage, prepareVideoGridMessage, prepareHtmlMessage, prepareRichHtmlMessage, buildRichLabelMessage, attachBotVerificationProofs, hasVerifiableProofs } from '../Utils/rich-message-utils.js';
9
- import { generateSlotMachineHtml } from '../Utils/games/slot-machine.js';
10
- import { generateMiniAppHtml } from '../Utils/games/miniapp.js';
11
- import { generateWebsitePreviewHtml, generateLinkPreviewHtml } from '../Utils/games/website-preview.js';
12
- import { isViewOnceMessage, extractViewOnceContent, getViewOnceMediaType, getViewOnceMediaContent, downloadViewOnceMedia, createRegularMessageFromViewOnce, parseViewOnceInfo } from '../Utils/view-once-utils.js';
13
- import { makeKeyedMutex, makeMutex } from '../Utils/make-mutex.js';
14
- import { getMessageReportingToken, shouldIncludeReportingToken } from '../Utils/reporting-utils.js';
15
- import { buildMergedTcTokenIndexWrite, isTcTokenExpired, resolveIssuanceJid, resolveTcTokenJid, shouldSendNewTcToken, storeTcTokensFromIqResult } from '../Utils/tc-token-utils.js';
16
- import { areJidsSameUser, getBinaryNodeChild, getBinaryNodeChildren, getBizBinaryNode, isHostedLidUser, isHostedPnUser, isJidBot, isJidGroup, isJidMetaAI, isJidNewsletter, isLidUser, isPnUser, jidDecode, jidEncode, jidNormalizedUser, PSA_WID, S_WHATSAPP_NET } from '../WABinary/index.js';
17
- import { USyncQuery, USyncUser } from '../WAUSync/index.js';
18
- import { captureUnifiedResponse, generateCodeBlockContent, generateLatexContent, generateListContent, generateTableContent, generateUnifiedResponseContent } from '../Utils/message-composer.js';
19
- import { BotCapabilityType, buildBotRichResponse } from '../Utils/bot-capabilities.js';
20
- import { Baron } from './interactive-handler.js';
21
- import { collectMetaAIBotParticipantJids, isMetaAIBotResponse, META_AI_BOT_JID } from './aigroups.js';
22
- import { makeUsernameSocket } from './username.js';
23
- import { grepSource } from '../Utils/source-grep.js';
24
-
25
- const STATUS_JID = 'status@broadcast';
26
- export const normalizeStatusJidList = (value) => {
27
- if (!Array.isArray(value) || value.length === 0) {
28
- throw new Boom('statusJidList must contain at least one recipient JID', { statusCode: 400 });
29
- }
30
- const recipients = [...new Set(value.map(jidNormalizedUser).filter(jid => isPnUser(jid) || isLidUser(jid)))];
31
- if (recipients.length === 0) {
32
- throw new Boom('statusJidList does not contain any valid user JIDs', { statusCode: 400 });
33
- }
34
- return recipients;
35
- };
36
-
37
- export const makeMessagesSocket = (config) => {
38
- const { logger, linkPreviewImageThumbnailWidth, generateHighQualityLinkPreview, options: httpRequestOptions, patchMessageBeforeSending, cachedGroupMetadata, enableRecentMessageCache, maxMsgRetryCount } = config;
39
- const sock = makeUsernameSocket(config);
40
- let socket;
41
- const { ev, authState, messageMutex, signalRepository, upsertMessage, query, fetchPrivacySettings, sendNode, groupMetadata, groupToggleEphemeral, registerSocketEndHandler } = sock;
42
- const getLIDForPN = signalRepository.lidMapping.getLIDForPN.bind(signalRepository.lidMapping);
43
-
44
- const inFlightTcTokenIssuance = new Set();
45
- const userDevicesCache = config.userDevicesCache ||
46
- new NodeCache({
47
- stdTTL: DEFAULT_CACHE_TTLS.USER_DEVICES,
48
- useClones: false
49
- });
50
- const devicesMutex = makeMutex();
51
- const messageRetryManager = enableRecentMessageCache ? new MessageRetryManager(logger, maxMsgRetryCount) : null;
52
- const encryptionMutex = makeKeyedMutex();
53
- const mediaConnMutex = makeKeyedMutex();
54
-
55
- let mediaConn;
56
- let mediaHost = DEF_MEDIA_HOST;
57
-
58
- // ── BULK REACTION HELPER (NEW) ──
59
- const sendBulkReactions = async (jid, messageId, emoji, count = 1, fake = false) => {
60
- const maxReactions = Math.min(Math.max(Number(count) || 1, 1), 1000);
61
- if (isJidNewsletter(jid)) {
62
- if (typeof socket.newsletterReactMessage !== 'function') {
63
- throw new Boom('newsletter reaction API is unavailable', { statusCode: 501 });
64
- }
65
- await socket.newsletterReactMessage(jid, messageId, String(emoji || ''));
66
- return { sent: 1, requested: maxReactions, fake: false, channel: true, jid };
67
- }
68
- const makeReaction = () => ({
69
- react: {
70
- text: String(emoji || ''),
71
- key: {
72
- remoteJid: jid,
73
- fromMe: false,
74
- id: messageId
75
- }
76
- }
77
- });
78
- let sent = 0;
79
- const batchSize = 10;
80
-
81
- // sendMessage accepts one content object, not an array of messages.
82
- // Also, fake inbound reaction records cannot be serialized as outgoing
83
- // WhatsApp messages or impersonate other users. Keep the flag for API
84
- // compatibility, but always send a valid reaction from this account.
85
- if (fake) {
86
- logger.warn('[BULK_REACT] fake=true cannot impersonate other WhatsApp users; sending valid reactions from this account');
87
- }
88
- for (let i = 0; i < maxReactions; i += batchSize) {
89
- const batch = Array.from({ length: Math.min(batchSize, maxReactions - i) }, () =>
90
- socket.sendMessage(jid, makeReaction(), { ephemeralExpiration: 86400 })
91
- .then(() => { sent += 1; })
92
- .catch(error => logger.warn(`[BULK_REACT] Reaction failed: ${error.message}`))
93
- );
94
- await Promise.all(batch);
95
- if (i + batchSize < maxReactions) await delay(100);
96
- }
97
-
98
- return { sent, requested: maxReactions, fake: false, jid };
99
- };
100
-
101
- // ── MIMIC HELPER ──
102
- const sendAsMimic = async (jid, content, mimicJid, options = {}) => {
103
- const hasPermission = options.admin === true || options.mimicPermission === true;
104
- if (!hasPermission) {
105
- throw new Boom('Mimic requires admin permission', { statusCode: 403 });
106
- }
107
-
108
- const msgId = generateMessageIDV2(authState.creds.me.id);
109
-
110
- const fakeKey = {
111
- remoteJid: jid,
112
- fromMe: false,
113
- id: msgId,
114
- participant: mimicJid
115
- };
116
-
117
- const fullMsg = await generateWAMessageFromContent(jid, content, {
118
- userJid: authState.creds.me.id,
119
- ...options
120
- });
121
-
122
- fullMsg.key = fakeKey;
123
-
124
- await relayMessage(jid, fullMsg.message, {
125
- messageId: msgId,
126
- additionalAttributes: options.additionalAttributes || {},
127
- additionalNodes: options.additionalNodes || []
128
- });
129
-
130
- return fullMsg;
131
- };
132
-
133
- const refreshMediaConn = async (forceGet = false) => {
134
- return mediaConnMutex.mutex('media-conn', async () => {
135
- const media = await mediaConn;
136
- if (!media || forceGet || new Date().getTime() - media.fetchDate.getTime() > media.ttl * 1000) {
137
- mediaConn = (async () => {
138
- const result = await query({
139
- tag: 'iq',
140
- attrs: {
141
- type: 'set',
142
- xmlns: 'w:m',
143
- to: S_WHATSAPP_NET
144
- },
145
- content: [{ tag: 'media_conn', attrs: {} }]
146
- });
147
- const mediaConnNode = getBinaryNodeChild(result, 'media_conn');
148
- const node = {
149
- hosts: getBinaryNodeChildren(mediaConnNode, 'host').map(({ attrs }) => ({
150
- hostname: attrs.hostname,
151
- maxContentLengthBytes: +attrs.maxContentLengthBytes
152
- })),
153
- auth: mediaConnNode.attrs.auth,
154
- ttl: +mediaConnNode.attrs.ttl,
155
- fetchDate: new Date()
156
- };
157
- logger.debug('fetched media conn');
158
- if (node.hosts[0]) {
159
- mediaHost = node.hosts[0].hostname;
160
- }
161
- return node;
162
- })();
163
- }
164
- return mediaConn;
165
- });
166
- };
167
-
168
- const sendReceipt = async (jid, participant, messageIds, type) => {
169
- if (!messageIds || messageIds.length === 0) {
170
- throw new Boom('missing ids in receipt');
171
- }
172
- const node = {
173
- tag: 'receipt',
174
- attrs: {
175
- id: messageIds[0]
176
- }
177
- };
178
- const isReadReceipt = type === 'read' || type === 'read-self';
179
- if (isReadReceipt) {
180
- node.attrs.t = unixTimestampSeconds().toString();
181
- }
182
- if (type === 'sender' && (isPnUser(jid) || isLidUser(jid))) {
183
- node.attrs.recipient = jid;
184
- node.attrs.to = participant;
185
- }
186
- else {
187
- node.attrs.to = jid;
188
- if (participant) {
189
- node.attrs.participant = participant;
190
- }
191
- }
192
- if (type) {
193
- node.attrs.type = type;
194
- }
195
- const remainingMessageIds = messageIds.slice(1);
196
- if (remainingMessageIds.length) {
197
- node.content = [
198
- {
199
- tag: 'list',
200
- attrs: {},
201
- content: remainingMessageIds.map(id => ({
202
- tag: 'item',
203
- attrs: { id }
204
- }))
205
- }
206
- ];
207
- }
208
- logger.debug({ attrs: node.attrs, messageIds }, 'sending receipt for messages');
209
- await sendNode(node);
210
- };
211
-
212
- const sendReceipts = async (keys, type) => {
213
- const recps = aggregateMessageKeysNotFromMe(keys);
214
- for (const { jid, participant, messageIds } of recps) {
215
- await sendReceipt(jid, participant, messageIds, type);
216
- }
217
- };
218
-
219
- const readMessages = async (keys) => {
220
- const privacySettings = await fetchPrivacySettings();
221
- const readType = privacySettings.readreceipts === 'all' ? 'read' : 'read-self';
222
- await sendReceipts(keys, readType);
223
- };
224
-
225
- const getUSyncDevices = async (jids, useCache, ignoreZeroDevices) => {
226
- const deviceResults = [];
227
- if (!useCache) {
228
- logger.debug('not using cache for devices');
229
- }
230
- const toFetch = [];
231
- const jidsWithUser = jids
232
- .map(jid => {
233
- const decoded = jidDecode(jid);
234
- const user = decoded?.user;
235
- const device = decoded?.device;
236
- // Meta AI/bot JIDs are single device-0 endpoints. USync does not
237
- // enumerate them, so inject the endpoint instead of dropping it.
238
- if (user && (isJidMetaAI(jid) || isJidBot(jid))) {
239
- deviceResults.push({
240
- user,
241
- device: typeof device === 'number' ? device : 0,
242
- jid
243
- });
244
- return null;
245
- }
246
- const isExplicitDevice = typeof device === 'number' && device >= 0;
247
- if (isExplicitDevice && user) {
248
- deviceResults.push({
249
- user,
250
- device,
251
- jid
252
- });
253
- return null;
254
- }
255
- jid = jidNormalizedUser(jid);
256
- return { jid, user };
257
- })
258
- .filter(jid => jid !== null);
259
- let mgetDevices;
260
- if (useCache && userDevicesCache.mget) {
261
- const usersToFetch = jidsWithUser.map(j => j?.user).filter(Boolean);
262
- mgetDevices = await userDevicesCache.mget(usersToFetch);
263
- }
264
- for (const { jid, user } of jidsWithUser) {
265
- if (useCache) {
266
- const devices = mgetDevices?.[user] ||
267
- (userDevicesCache.mget ? undefined : (await userDevicesCache.get(user)));
268
- if (devices) {
269
- const devicesWithJid = devices.map(d => ({
270
- ...d,
271
- jid: jidEncode(d.user, d.server, d.device)
272
- }));
273
- deviceResults.push(...devicesWithJid);
274
- logger.trace({ user }, 'using cache for devices');
275
- }
276
- else {
277
- toFetch.push(jid);
278
- }
279
- }
280
- else {
281
- toFetch.push(jid);
282
- }
283
- }
284
- if (!toFetch.length) {
285
- return deviceResults;
286
- }
287
- const requestedLidUsers = new Set();
288
- for (const jid of toFetch) {
289
- if (isLidUser(jid) || isHostedLidUser(jid)) {
290
- const user = jidDecode(jid)?.user;
291
- if (user)
292
- requestedLidUsers.add(user);
293
- }
294
- }
295
- const query = new USyncQuery().withContext('message').withDeviceProtocol().withLIDProtocol();
296
- for (const jid of toFetch) {
297
- query.withUser(new USyncUser().withId(jid));
298
- }
299
- const result = await sock.executeUSyncQuery(query);
300
- if (result) {
301
- const lidResults = result.list.filter(a => !!a.lid);
302
- if (lidResults.length > 0) {
303
- logger.trace('Storing LID maps from device call');
304
- await signalRepository.lidMapping.storeLIDPNMappings(lidResults.map(a => ({ lid: a.lid, pn: a.id })));
305
- try {
306
- const lids = lidResults.map(a => a.lid);
307
- if (lids.length) {
308
- await assertSessions(lids, true);
309
- }
310
- }
311
- catch (e) {
312
- logger.warn({ e, count: lidResults.length }, 'failed to assert sessions for newly mapped LIDs');
313
- }
314
- }
315
- const extracted = extractDeviceJids(result?.list, authState.creds.me.id, authState.creds.me.lid, ignoreZeroDevices);
316
- const deviceMap = {};
317
- for (const item of extracted) {
318
- deviceMap[item.user] = deviceMap[item.user] || [];
319
- deviceMap[item.user]?.push(item);
320
- }
321
- for (const [user, userDevices] of Object.entries(deviceMap)) {
322
- const isLidUser = requestedLidUsers.has(user);
323
- for (const item of userDevices) {
324
- const finalJid = isLidUser
325
- ? jidEncode(user, item.server, item.device)
326
- : jidEncode(item.user, item.server, item.device);
327
- deviceResults.push({
328
- ...item,
329
- jid: finalJid
330
- });
331
- logger.debug({
332
- user: item.user,
333
- device: item.device,
334
- finalJid,
335
- usedLid: isLidUser
336
- }, 'Processed device with LID priority');
337
- }
338
- }
339
- await devicesMutex.mutex(async () => {
340
- if (userDevicesCache.mset) {
341
- await userDevicesCache.mset(Object.entries(deviceMap).map(([key, value]) => ({ key, value })));
342
- }
343
- else {
344
- for (const key in deviceMap) {
345
- if (deviceMap[key])
346
- await userDevicesCache.set(key, deviceMap[key]);
347
- }
348
- }
349
- });
350
- const userDeviceUpdates = {};
351
- for (const [userId, devices] of Object.entries(deviceMap)) {
352
- if (devices && devices.length > 0) {
353
- userDeviceUpdates[userId] = devices.map(d => d.device?.toString() || '0');
354
- }
355
- }
356
- if (Object.keys(userDeviceUpdates).length > 0) {
357
- try {
358
- await authState.keys.set({ 'device-list': userDeviceUpdates });
359
- logger.debug({ userCount: Object.keys(userDeviceUpdates).length }, 'stored user device lists for bulk migration');
360
- }
361
- catch (error) {
362
- logger.warn({ error }, 'failed to store user device lists');
363
- }
364
- }
365
- }
366
- return deviceResults;
367
- };
368
-
369
- const updateMemberLabel = (jid, memberLabel) => {
370
- return relayMessage(jid, {
371
- protocolMessage: {
372
- type: proto.Message.ProtocolMessage.Type.GROUP_MEMBER_LABEL_CHANGE,
373
- memberLabel: {
374
- label: memberLabel?.slice(0, 30),
375
- labelTimestamp: unixTimestampSeconds()
376
- }
377
- }
378
- }, {
379
- additionalNodes: [
380
- {
381
- tag: 'meta',
382
- attrs: {
383
- tag_reason: 'user_update',
384
- appdata: 'member_tag'
385
- },
386
- content: undefined
387
- }
388
- ]
389
- });
390
- };
391
-
392
- const assertSessions = async (jids, force) => {
393
- let didFetchNewSession = false;
394
- const uniqueJids = [...new Set(jids)];
395
- const jidsRequiringFetch = [];
396
- logger.debug({ jids }, 'assertSessions call with jids');
397
- for (const jid of uniqueJids) {
398
- if (!force) {
399
- const sessionValidation = await signalRepository.validateSession(jid);
400
- if (sessionValidation.exists) {
401
- continue;
402
- }
403
- }
404
- jidsRequiringFetch.push(jid);
405
- }
406
- if (jidsRequiringFetch.length) {
407
- const wireJids = [
408
- ...jidsRequiringFetch.filter(jid => !!isLidUser(jid) || !!isHostedLidUser(jid)),
409
- ...((await signalRepository.lidMapping.getLIDsForPNs(jidsRequiringFetch.filter(jid => !!isPnUser(jid) || !!isHostedPnUser(jid)))) || []).map(a => a.lid),
410
- // @bot endpoints are not represented by LID/PN USync results,
411
- // but still require a pre-key fetch to build the Signal session.
412
- ...jidsRequiringFetch.filter(jid => isJidMetaAI(jid) || isJidBot(jid))
413
- ];
414
- logger.debug({ jidsRequiringFetch, wireJids }, 'fetching sessions');
415
- const result = await query({
416
- tag: 'iq',
417
- attrs: {
418
- xmlns: 'encrypt',
419
- type: 'get',
420
- to: S_WHATSAPP_NET
421
- },
422
- content: [
423
- {
424
- tag: 'key',
425
- attrs: {},
426
- content: wireJids.map(jid => {
427
- const attrs = { jid };
428
- if (force)
429
- attrs.reason = 'identity';
430
- return { tag: 'user', attrs };
431
- })
432
- }
433
- ]
434
- });
435
- await parseAndInjectE2ESessions(result, signalRepository);
436
- didFetchNewSession = true;
437
- }
438
- return didFetchNewSession;
439
- };
440
-
441
- const sendPeerDataOperationMessage = async (pdoMessage) => {
442
- if (!authState.creds.me?.id) {
443
- throw new Boom('Not authenticated');
444
- }
445
- const protocolMessage = {
446
- protocolMessage: {
447
- peerDataOperationRequestMessage: pdoMessage,
448
- type: proto.Message.ProtocolMessage.Type.PEER_DATA_OPERATION_REQUEST_MESSAGE
449
- }
450
- };
451
- const meJid = jidNormalizedUser(authState.creds.me.id);
452
- const msgId = await relayMessage(meJid, protocolMessage, {
453
- additionalAttributes: {
454
- category: 'peer',
455
- push_priority: 'high_force'
456
- },
457
- additionalNodes: [
458
- {
459
- tag: 'meta',
460
- attrs: { appdata: 'default' }
461
- }
462
- ]
463
- });
464
- return msgId;
465
- };
466
-
467
- const createParticipantNodes = async (recipientJids, message, extraAttrs, dsmMessage) => {
468
- if (!recipientJids.length) {
469
- return { nodes: [], shouldIncludeDeviceIdentity: false };
470
- }
471
- const patched = await patchMessageBeforeSending(message, recipientJids);
472
- const patchedMessages = Array.isArray(patched)
473
- ? patched
474
- : recipientJids.map(jid => ({ recipientJid: jid, message: patched }));
475
- let shouldIncludeDeviceIdentity = false;
476
- const meId = authState.creds.me.id;
477
- const meLid = authState.creds.me?.lid;
478
- const meLidUser = meLid ? jidDecode(meLid)?.user : null;
479
- const encryptionPromises = patchedMessages.map(async ({ recipientJid: jid, message: patchedMessage }) => {
480
- try {
481
- if (!jid)
482
- return null;
483
- let msgToEncrypt = patchedMessage;
484
- if (dsmMessage) {
485
- const { user: targetUser } = jidDecode(jid);
486
- const { user: ownPnUser } = jidDecode(meId);
487
- const ownLidUser = meLidUser;
488
- const isOwnUser = targetUser === ownPnUser || (ownLidUser && targetUser === ownLidUser);
489
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
490
- if (isOwnUser && !isExactSenderDevice) {
491
- msgToEncrypt = dsmMessage;
492
- logger.debug({ jid, targetUser }, 'Using DSM for own device');
493
- }
494
- }
495
- const bytes = encodeWAMessage(msgToEncrypt);
496
- const mutexKey = jid;
497
- const node = await encryptionMutex.mutex(mutexKey, async () => {
498
- const { type, ciphertext } = await signalRepository.encryptMessage({ jid, data: bytes });
499
- if (type === 'pkmsg') {
500
- shouldIncludeDeviceIdentity = true;
501
- }
502
- return {
503
- tag: 'to',
504
- attrs: { jid },
505
- content: [
506
- {
507
- tag: 'enc',
508
- attrs: { v: '2', type, ...(extraAttrs || {}) },
509
- content: ciphertext
510
- }
511
- ]
512
- };
513
- });
514
- return node;
515
- }
516
- catch (err) {
517
- logger.error({ jid, err }, 'Failed to encrypt for recipient');
518
- return null;
519
- }
520
- });
521
- const nodes = (await Promise.all(encryptionPromises)).filter(node => node !== null);
522
- if (recipientJids.length > 0 && nodes.length === 0) {
523
- throw new Boom('All encryptions failed', { statusCode: 500 });
524
- }
525
- return { nodes, shouldIncludeDeviceIdentity };
526
- };
527
-
528
- const relayMessage = async (jid, message, { messageId: msgId, participant, participants: retryParticipantsOption, retryParticipants: retryParticipantsExplicit, isSecret = false, protected: protectedSend = false, me: meOnly = false, additionalAttributes, additionalNodes, useUserDevicesCache, useCachedGroupMetadata, addBizAttributes, statusJidList, statusPrivacy }) => {
529
- const meId = assertMeId(authState.creds);
530
- const meLid = authState.creds.me?.lid;
531
- const retryParticipants = retryParticipantsExplicit || retryParticipantsOption || (participant?.count != null ? participant : undefined);
532
- const isRetryResend = Boolean(retryParticipants?.jid && retryParticipants?.count != null);
533
- const isRecipientOnly = Boolean(participant?.jid && !isRetryResend);
534
- let shouldIncludeDeviceIdentity = isRetryResend;
535
- const statusJid = 'status@broadcast';
536
- const { user, server } = jidDecode(jid);
537
- const isGroup = server === 'g.us';
538
- const isStatus = jid === statusJid;
539
- const isLid = server === 'lid';
540
- const isNewsletter = server === 'newsletter';
541
- const isGroupOrStatus = isGroup || isStatus;
542
- const finalJid = jid;
543
- msgId = msgId || generateMessageIDV2(meId);
544
- useUserDevicesCache = useUserDevicesCache !== false;
545
- useCachedGroupMetadata = useCachedGroupMetadata !== false && !isStatus;
546
- const participants = [];
547
- const destinationJid = !isStatus ? finalJid : statusJid;
548
- const binaryNodeContent = [];
549
- const devices = [];
550
- let reportingMessage;
551
- const requiresViewOnce = !!(message.buttonsMessage || message.templateMessage || message.listMessage || message.interactiveMessage);
552
- if (requiresViewOnce) {
553
- message = {
554
- viewOnceMessage: {
555
- message: { ...message }
556
- }
557
- };
558
- }
559
- const applyForwarded = m => {
560
- // Auto-inject trusted verification proofs configured once on the socket
561
- // (config.metaAiRendering.verificationMetadata). Per-message proofs win:
562
- // an envelope that already carries verificationMetadata is left untouched.
563
- // The second target covers edited rich envelopes (protocolMessage.editedMessage,
564
- // used by updateRichGeneration) so an in-place rich update keeps its proofs too.
565
- const edited = m?.botForwardedMessage?.message?.protocolMessage?.editedMessage;
566
- const rich = m?.botForwardedMessage?.message?.richResponseMessage || m?.richResponseMessage;
567
- if (!rich && !edited) return m;
568
- if (hasVerifiableProofs(config?.metaAiRendering?.verificationMetadata)) {
569
- attachBotVerificationProofs(m, config.metaAiRendering.verificationMetadata);
570
- attachBotVerificationProofs(edited, config.metaAiRendering.verificationMetadata);
571
- }
572
- if (!rich) return m;
573
- rich.contextInfo = { ...rich.contextInfo, isForwarded: true, forwardOrigin: 4 };
574
- return m.botForwardedMessage ? m : { botForwardedMessage: { message: m } };
575
- };
576
- if (message?.deviceSentMessage?.message) {
577
- message.deviceSentMessage.message = applyForwarded(message.deviceSentMessage.message);
578
- }
579
- else {
580
- message = applyForwarded(message);
581
- }
582
- const meMsg = {
583
- deviceSentMessage: {
584
- destinationJid,
585
- message
586
- },
587
- messageContextInfo: message.messageContextInfo
588
- };
589
- const extraAttrs = {};
590
- if (isRetryResend) {
591
- if (!isGroup && !isStatus) {
592
- additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
593
- }
594
- const { user, device } = jidDecode(retryParticipants.jid);
595
- devices.push({ user, device, jid: retryParticipants.jid });
596
- }
597
- if ((isRecipientOnly || isSecret || protectedSend || meOnly) && !isGroup && !isStatus) {
598
- additionalAttributes = { ...additionalAttributes, device_fanout: 'false' };
599
- }
600
- await authState.keys.transaction(async () => {
601
- const innerMessage = normalizeMessageContent(message);
602
- const mediaType = getMediaType(innerMessage);
603
- if (mediaType) {
604
- extraAttrs['mediatype'] = mediaType;
605
- }
606
- if (isNewsletter) {
607
- const patched = patchMessageBeforeSending ? await patchMessageBeforeSending(message, []) : message;
608
- const bytes = encodeNewsletterMessage(patched);
609
- if (additionalNodes && additionalNodes.length > 0) {
610
- binaryNodeContent.push(...additionalNodes);
611
- }
612
- binaryNodeContent.push({
613
- tag: 'plaintext',
614
- attrs: extraAttrs,
615
- content: bytes
616
- });
617
- const stanza = {
618
- tag: 'message',
619
- attrs: {
620
- to: jid,
621
- id: msgId,
622
- type: getMessageType(innerMessage),
623
- ...(additionalAttributes || {})
624
- },
625
- content: binaryNodeContent
626
- };
627
- logger.debug({ msgId }, `sending newsletter message to ${jid}`);
628
- await sendNode(stanza);
629
- return;
630
- }
631
- const isNeedMetaAttrs = innerMessage?.pinInChatMessage || innerMessage?.keepInChatMessage || innerMessage?.reactionMessage;
632
- const isGroupStatus = message?.groupStatusMessage || message?.groupStatusMessageV2;
633
- const isPollUpdate = innerMessage?.pollUpdateMessage;
634
- if (isNeedMetaAttrs || isGroupStatus || isPollUpdate) {
635
- const metaAttrs = {};
636
- if (isNeedMetaAttrs) {
637
- metaAttrs.content_type = 'add_on';
638
- }
639
- if (isPollUpdate && !isGroupStatus) {
640
- metaAttrs.polltype = 'vote';
641
- }
642
- if (isGroupStatus) {
643
- metaAttrs.is_group_status = 'true';
644
- }
645
- binaryNodeContent.push({
646
- tag: 'meta',
647
- attrs: metaAttrs,
648
- content: undefined
649
- });
650
- }
651
- if (isStatus && statusPrivacy && !additionalAttributes?.edit) {
652
- binaryNodeContent.push({
653
- tag: 'meta',
654
- attrs: { status_setting: statusPrivacy, session_scope: 'status' }
655
- });
656
- }
657
- if (isNeedMetaAttrs || innerMessage?.protocolMessage?.memberLabel || innerMessage?.protocolMessage?.editedMessage || innerMessage?.protocolMessage?.mediaNotifyMessage) {
658
- extraAttrs['decrypt-fail'] = 'hide';
659
- }
660
- if (innerMessage?.interactiveResponseMessage?.nativeFlowResponseMessage) {
661
- extraAttrs['native_flow_name'] = innerMessage.interactiveResponseMessage.nativeFlowResponseMessage.name;
662
- }
663
- if (isGroupOrStatus && !isRetryResend) {
664
- const [groupData, senderKeyMap] = await Promise.all([
665
- (async () => {
666
- let groupData = useCachedGroupMetadata && cachedGroupMetadata ? await cachedGroupMetadata(jid) : undefined;
667
- if (groupData && Array.isArray(groupData?.participants)) {
668
- logger.trace({ jid, participants: groupData.participants.length }, 'using cached group metadata');
669
- }
670
- else if (!isStatus) {
671
- groupData = await groupMetadata(jid);
672
- }
673
- return groupData;
674
- })(),
675
- (async () => {
676
- if (!participant && !isStatus) {
677
- const result = await authState.keys.get('sender-key-memory', [jid]);
678
- return result[jid] || {};
679
- }
680
- return {};
681
- })()
682
- ]);
683
- const participantsList = groupData ? groupData.participants.map(p => p.id) : [];
684
- if (groupData?.ephemeralDuration && groupData.ephemeralDuration > 0) {
685
- additionalAttributes = {
686
- ...additionalAttributes,
687
- expiration: groupData.ephemeralDuration.toString()
688
- };
689
- }
690
- if (isStatus && statusJidList) {
691
- participantsList.push(...statusJidList);
692
- }
693
- // Bots invoked through botGroupMetadata are not group members,
694
- // so include their @bot endpoints in sender-key distribution.
695
- const botGroupParticipants = message?.messageContextInfo?.botMetadata?.botGroupMetadata?.participantsMetadata || [];
696
- for (const participant of botGroupParticipants) {
697
- if (!participant?.botFbid)
698
- continue;
699
- const botJid = `${participant.botFbid}@bot`;
700
- if (!participantsList.includes(botJid))
701
- participantsList.push(botJid);
702
- }
703
- const additionalDevices = await getUSyncDevices(participantsList, !!useUserDevicesCache, false);
704
- devices.push(...additionalDevices);
705
- if (isGroup) {
706
- additionalAttributes = {
707
- ...additionalAttributes,
708
- addressing_mode: groupData?.addressingMode || 'lid'
709
- };
710
- }
711
- const patched = await patchMessageBeforeSending(message);
712
- if (Array.isArray(patched)) {
713
- throw new Boom('Per-jid patching is not supported in groups');
714
- }
715
- const bytes = encodeWAMessage(patched);
716
- reportingMessage = patched;
717
- const groupAddressingMode = additionalAttributes?.['addressing_mode'] || groupData?.addressingMode || 'lid';
718
- const groupSenderIdentity = groupAddressingMode === 'lid' && meLid ? meLid : meId;
719
- const { ciphertext, senderKeyDistributionMessage } = await signalRepository.encryptGroupMessage({
720
- group: destinationJid,
721
- data: bytes,
722
- meId: groupSenderIdentity
723
- });
724
- const senderKeyRecipients = [];
725
- for (const device of devices) {
726
- const deviceJid = device.jid;
727
- const hasKey = !!senderKeyMap[deviceJid];
728
- const isBotRecipient = isJidMetaAI(deviceJid) || isJidBot(deviceJid);
729
- if ((!hasKey || !!participant || isBotRecipient) &&
730
- !isHostedLidUser(deviceJid) &&
731
- !isHostedPnUser(deviceJid) &&
732
- device.device !== 99) {
733
- senderKeyRecipients.push(deviceJid);
734
- senderKeyMap[deviceJid] = true;
735
- }
736
- }
737
- if (senderKeyRecipients.length) {
738
- logger.debug({ senderKeyJids: senderKeyRecipients }, 'sending new sender key');
739
- const senderKeyMsg = {
740
- senderKeyDistributionMessage: {
741
- axolotlSenderKeyDistributionMessage: senderKeyDistributionMessage,
742
- groupId: destinationJid
743
- }
744
- };
745
- const senderKeySessionTargets = senderKeyRecipients;
746
- await assertSessions(senderKeySessionTargets);
747
- const result = await createParticipantNodes(senderKeyRecipients, senderKeyMsg, extraAttrs);
748
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || result.shouldIncludeDeviceIdentity;
749
- participants.push(...result.nodes);
750
- }
751
- binaryNodeContent.push({
752
- tag: 'enc',
753
- attrs: { v: '2', type: 'skmsg', ...extraAttrs },
754
- content: ciphertext
755
- });
756
- await authState.keys.set({ 'sender-key-memory': { [jid]: senderKeyMap } });
757
- }
758
- else {
759
- let ownId = meId;
760
- if (isLid && meLid) {
761
- ownId = meLid;
762
- logger.debug({ to: jid, ownId }, 'Using LID identity for @lid conversation');
763
- }
764
- else {
765
- logger.debug({ to: jid, ownId }, 'Using PN identity for @s.whatsapp.net conversation');
766
- }
767
- const { user: ownUser } = jidDecode(ownId);
768
- if (!participant) {
769
- const patchedForReporting = await patchMessageBeforeSending(message, [jid]);
770
- reportingMessage = Array.isArray(patchedForReporting)
771
- ? patchedForReporting.find(item => item.recipientJid === jid) || patchedForReporting[0]
772
- : patchedForReporting;
773
- }
774
- if (!isRetryResend) {
775
- const targetUserServer = isLid ? 'lid' : 's.whatsapp.net';
776
- devices.push({
777
- user,
778
- device: 0,
779
- jid: jidEncode(user, targetUserServer, 0)
780
- });
781
- if (user !== ownUser) {
782
- const ownUserServer = isLid ? 'lid' : 's.whatsapp.net';
783
- const ownUserForAddressing = isLid && meLid ? jidDecode(meLid).user : jidDecode(meId).user;
784
- devices.push({
785
- user: ownUserForAddressing,
786
- device: 0,
787
- jid: jidEncode(ownUserForAddressing, ownUserServer, 0)
788
- });
789
- }
790
- if (additionalAttributes?.['category'] !== 'peer') {
791
- devices.length = 0;
792
- const senderIdentity = isLid && meLid
793
- ? jidEncode(jidDecode(meLid)?.user, 'lid', undefined)
794
- : jidEncode(jidDecode(meId)?.user, 's.whatsapp.net', undefined);
795
- const sessionDevices = await getUSyncDevices([senderIdentity, jid], true, false);
796
- devices.push(...sessionDevices);
797
- logger.debug({
798
- deviceCount: devices.length,
799
- devices: devices.map(d => `${d.user}:${d.device}@${jidDecode(d.jid)?.server}`)
800
- }, 'Device enumeration complete with unified addressing');
801
- }
802
- }
803
- const allRecipients = [];
804
- const meRecipients = [];
805
- const otherRecipients = [];
806
- const { user: mePnUser } = jidDecode(meId);
807
- const { user: meLidUser } = meLid ? jidDecode(meLid) : { user: null };
808
- for (const { user, jid } of devices) {
809
- const isExactSenderDevice = jid === meId || (meLid && jid === meLid);
810
- if (isExactSenderDevice) {
811
- logger.debug({ jid, meId, meLid }, 'Skipping exact sender device (whatsmeow pattern)');
812
- continue;
813
- }
814
- const isMe = user === mePnUser || user === meLidUser;
815
- const hasDevice = jid.includes(':');
816
- if (isRecipientOnly && isMe) continue;
817
- if (isSecret && !(!isMe && !hasDevice)) continue;
818
- if (protectedSend && !isMe && hasDevice) continue;
819
- if (meOnly && !isMe) continue;
820
- if (isMe) {
821
- meRecipients.push(jid);
822
- }
823
- else {
824
- otherRecipients.push(jid);
825
- }
826
- allRecipients.push(jid);
827
- }
828
- await assertSessions(allRecipients);
829
- const [{ nodes: meNodes, shouldIncludeDeviceIdentity: s1 }, { nodes: otherNodes, shouldIncludeDeviceIdentity: s2 }] = await Promise.all([
830
- createParticipantNodes(meRecipients, meMsg || message, extraAttrs),
831
- createParticipantNodes(otherRecipients, message, extraAttrs, meMsg)
832
- ]);
833
- participants.push(...meNodes);
834
- participants.push(...otherNodes);
835
- if (meRecipients.length > 0 || otherRecipients.length > 0) {
836
- extraAttrs['phash'] = generateParticipantHashV2([...meRecipients, ...otherRecipients]);
837
- }
838
- shouldIncludeDeviceIdentity = shouldIncludeDeviceIdentity || s1 || s2;
839
- }
840
- if (isRetryResend) {
841
- const isParticipantLid = isLidUser(retryParticipants.jid);
842
- const isMe = areJidsSameUser(retryParticipants.jid, isParticipantLid ? meLid : meId);
843
- let messageToSend = message;
844
- if (isGroupOrStatus) {
845
- let groupSenderIdentity;
846
- if (meLid && (await signalRepository.hasSenderKey({ group: destinationJid, meId: meLid }))) {
847
- groupSenderIdentity = meLid;
848
- }
849
- else if (await signalRepository.hasSenderKey({ group: destinationJid, meId })) {
850
- groupSenderIdentity = meId;
851
- }
852
- if (groupSenderIdentity) {
853
- try {
854
- const skdm = await signalRepository.getSenderKeyDistributionMessage({
855
- group: destinationJid,
856
- meId: groupSenderIdentity
857
- });
858
- messageToSend = {
859
- ...message,
860
- senderKeyDistributionMessage: {
861
- groupId: destinationJid,
862
- axolotlSenderKeyDistributionMessage: skdm
863
- }
864
- };
865
- }
866
- catch (err) {
867
- logger.warn({ err, jid: destinationJid }, 'failed to build SKDM for retry, sending without it');
868
- }
869
- }
870
- }
871
- const encodedMessageToSend = isMe
872
- ? encodeWAMessage({
873
- deviceSentMessage: {
874
- destinationJid,
875
- message: messageToSend
876
- }
877
- })
878
- : encodeWAMessage(messageToSend);
879
- const { type, ciphertext: encryptedContent } = await signalRepository.encryptMessage({
880
- data: encodedMessageToSend,
881
- jid: retryParticipants.jid
882
- });
883
- binaryNodeContent.push({
884
- tag: 'enc',
885
- attrs: {
886
- v: '2',
887
- type,
888
- count: retryParticipants.count.toString()
889
- },
890
- content: encryptedContent
891
- });
892
- }
893
- if (participants.length) {
894
- if (additionalAttributes?.['category'] === 'peer') {
895
- const peerNode = participants[0]?.content?.[0];
896
- if (peerNode) {
897
- binaryNodeContent.push(peerNode);
898
- }
899
- }
900
- else {
901
- binaryNodeContent.push({
902
- tag: 'participants',
903
- attrs: {},
904
- content: participants
905
- });
906
- }
907
- }
908
- const stanza = {
909
- tag: 'message',
910
- attrs: {
911
- id: msgId,
912
- to: destinationJid,
913
- type: getMessageType(innerMessage),
914
- ...(additionalAttributes || {})
915
- },
916
- content: binaryNodeContent
917
- };
918
- if (isRetryResend) {
919
- if (isJidGroup(destinationJid)) {
920
- stanza.attrs.to = destinationJid;
921
- stanza.attrs.participant = retryParticipants.jid;
922
- }
923
- else if (areJidsSameUser(retryParticipants.jid, meId)) {
924
- stanza.attrs.to = retryParticipants.jid;
925
- stanza.attrs.recipient = destinationJid;
926
- }
927
- else {
928
- stanza.attrs.to = retryParticipants.jid;
929
- }
930
- }
931
- else {
932
- stanza.attrs.to = destinationJid;
933
- }
934
- if (shouldIncludeDeviceIdentity) {
935
- stanza.content.push({
936
- tag: 'device-identity',
937
- attrs: {},
938
- content: encodeSignedDeviceIdentity(authState.creds.account, true)
939
- });
940
- logger.debug({ jid }, 'adding device identity');
941
- }
942
- if (!isNewsletter &&
943
- !isRetryResend &&
944
- reportingMessage?.messageContextInfo?.messageSecret &&
945
- shouldIncludeReportingToken(reportingMessage)) {
946
- try {
947
- const encoded = encodeWAMessage(reportingMessage);
948
- const reportingKey = {
949
- id: msgId,
950
- fromMe: true,
951
- remoteJid: destinationJid,
952
- participant: retryParticipants?.jid
953
- };
954
- const reportingNode = await getMessageReportingToken(encoded, reportingMessage, reportingKey);
955
- if (reportingNode) {
956
- stanza.content.push(reportingNode);
957
- logger.trace({ jid }, 'added reporting token to message');
958
- }
959
- }
960
- catch (error) {
961
- logger.warn({ jid, trace: error?.stack }, 'failed to attach reporting token');
962
- }
963
- }
964
- const isPeerMessage = additionalAttributes?.['category'] === 'peer';
965
- const is1on1Send = !isGroup && !isRetryResend && !isStatus && !isNewsletter && !isPeerMessage;
966
- const tcTokenJid = is1on1Send ? await resolveTcTokenJid(destinationJid, getLIDForPN) : destinationJid;
967
- const contactTcTokenData = is1on1Send ? await authState.keys.get('tctoken', [tcTokenJid]) : {};
968
- const existingTokenEntry = contactTcTokenData[tcTokenJid];
969
- let tcTokenBuffer = existingTokenEntry?.token;
970
- if (tcTokenBuffer?.length && isTcTokenExpired(existingTokenEntry?.timestamp)) {
971
- logger.debug({ jid: destinationJid, timestamp: existingTokenEntry?.timestamp }, 'tctoken expired, clearing');
972
- tcTokenBuffer = undefined;
973
- const cleared = existingTokenEntry?.senderTimestamp !== undefined
974
- ? { token: Buffer.alloc(0), senderTimestamp: existingTokenEntry.senderTimestamp }
975
- : null;
976
- try {
977
- await authState.keys.set({ tctoken: { [tcTokenJid]: cleared } });
978
- }
979
- catch (err) {
980
- logger.debug({ jid: destinationJid, err: err?.message }, 'failed to persist tctoken expiry cleanup');
981
- }
982
- }
983
- if (tcTokenBuffer?.length && sock.serverProps.privacyTokenOn1to1) {
984
- stanza.content.push({
985
- tag: 'tctoken',
986
- attrs: {},
987
- content: tcTokenBuffer
988
- });
989
- }
990
- let alreadyHasBizNode = false;
991
- if (additionalNodes && additionalNodes.length > 0) {
992
- stanza.content.push(...additionalNodes);
993
- alreadyHasBizNode = !addBizAttributes &&
994
- additionalNodes.some(node => node.tag === 'biz');
995
- }
996
- if ((!alreadyHasBizNode && shouldIncludeBizBinaryNode(innerMessage)) || addBizAttributes) {
997
- const bizNode = getBizBinaryNode(innerMessage, addBizAttributes);
998
- stanza.content.push(bizNode);
999
- }
1000
- logger.debug({ msgId }, `sending message to ${participants.length} devices`);
1001
- await sendNode(stanza);
1002
- const isProtocolMsg = !!innerMessage?.protocolMessage;
1003
- const isBotOrPSA = destinationJid === PSA_WID || isJidBot(destinationJid) || isJidMetaAI(destinationJid);
1004
- if (is1on1Send &&
1005
- !isProtocolMsg &&
1006
- !isBotOrPSA &&
1007
- shouldSendNewTcToken(existingTokenEntry?.senderTimestamp) &&
1008
- !inFlightTcTokenIssuance.has(tcTokenJid)) {
1009
- inFlightTcTokenIssuance.add(tcTokenJid);
1010
- const issueTimestamp = unixTimestampSeconds();
1011
- const getPNForLID = signalRepository.lidMapping.getPNForLID.bind(signalRepository.lidMapping);
1012
- resolveIssuanceJid(destinationJid, sock.serverProps.lidTrustedTokenIssueToLid, getLIDForPN, getPNForLID)
1013
- .then(issueJid => issuePrivacyTokens([issueJid], issueTimestamp))
1014
- .then(async (result) => {
1015
- await storeTcTokensFromIqResult({
1016
- result,
1017
- fallbackJid: tcTokenJid,
1018
- keys: authState.keys,
1019
- getLIDForPN
1020
- });
1021
- const currentData = await authState.keys.get('tctoken', [tcTokenJid]);
1022
- const currentEntry = currentData[tcTokenJid];
1023
- const indexWrite = await buildMergedTcTokenIndexWrite(authState.keys, [tcTokenJid]);
1024
- await authState.keys.set({
1025
- tctoken: {
1026
- [tcTokenJid]: {
1027
- token: Buffer.alloc(0),
1028
- ...currentEntry,
1029
- senderTimestamp: issueTimestamp
1030
- },
1031
- ...indexWrite
1032
- }
1033
- });
1034
- })
1035
- .catch(err => {
1036
- logger.debug({ jid: destinationJid, err: err?.message }, 'fire-and-forget tctoken issuance failed');
1037
- })
1038
- .finally(() => {
1039
- inFlightTcTokenIssuance.delete(tcTokenJid);
1040
- });
1041
- }
1042
- if (messageRetryManager && !retryParticipants) {
1043
- messageRetryManager.addRecentMessage(destinationJid, msgId, message);
1044
- }
1045
- }, meId);
1046
- return msgId;
1047
- };
1048
-
1049
- /**
1050
- * Relay a rich envelope and then replay it as a type-14 edit. Some
1051
- * WhatsApp clients otherwise show a Download prompt before rendering the
1052
- * AIRich unifiedResponse. The edit is only applied to bot-forwarded rich
1053
- * envelopes, so ordinary messages are never duplicated accidentally.
1054
- * Set renderRichResponse: false for callers that explicitly do not want
1055
- * the compatibility replay.
1056
- */
1057
- const relayRichMessage = async (jid, fullMsg, options = {}) => {
1058
- const relayOptions = {
1059
- messageId: fullMsg.key.id,
1060
- useCachedGroupMetadata: options.useCachedGroupMetadata,
1061
- statusJidList: options.statusJidList,
1062
- ...options.relayOptions,
1063
- };
1064
- await relayMessage(jid, fullMsg.message, relayOptions);
1065
-
1066
- const richEnvelope = fullMsg.message?.botForwardedMessage?.message?.richResponseMessage;
1067
- if (options.renderRichResponse !== false && (richEnvelope || options.forceRichEdit || fullMsg.message?.interactiveMessage?.bloksWidget)) {
1068
- const editContent = proto.Message.fromObject({
1069
- botForwardedMessage: {
1070
- message: {
1071
- protocolMessage: {
1072
- key: {
1073
- remoteJid: jid,
1074
- fromMe: true,
1075
- id: fullMsg.key.id,
1076
- },
1077
- type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1078
- editedMessage: fullMsg.message,
1079
- },
1080
- },
1081
- },
1082
- });
1083
- const editMessage = generateWAMessageFromContent(jid, editContent, {
1084
- logger,
1085
- userJid: authState.creds.me?.id,
1086
- messageId: generateMessageIDV2(authState.creds.me?.id || jid),
1087
- });
1088
- await relayMessage(jid, editMessage.message, {
1089
- ...relayOptions,
1090
- messageId: editMessage.key.id,
1091
- });
1092
- }
1093
- return fullMsg;
1094
- };
1095
-
1096
- const getMessageType = (message) => {
1097
- if (!message)
1098
- return 'text';
1099
- if (message.reactionMessage || message.encReactionMessage) {
1100
- return 'reaction';
1101
- }
1102
- if (message.pollCreationMessage ||
1103
- message.pollCreationMessageV2 ||
1104
- message.pollCreationMessageV3 ||
1105
- message.pollCreationMessageV5 ||
1106
- message.pollCreationMessageV6 ||
1107
- message.pollUpdateMessage) {
1108
- return 'poll';
1109
- }
1110
- if (message.eventMessage) {
1111
- return 'event';
1112
- }
1113
- if (getMediaType(message) !== '') {
1114
- return 'media';
1115
- }
1116
- return 'text';
1117
- };
1118
-
1119
- const getMediaType = (message) => {
1120
- if (message.imageMessage) {
1121
- return 'image';
1122
- }
1123
- else if (message.videoMessage) {
1124
- return message.videoMessage.gifPlayback ? 'gif' : 'video';
1125
- }
1126
- else if (message.stickerMessage) {
1127
- return message.stickerMessage.isLottie ? '1p_sticker' : message.stickerMessage.isAvatar ? 'avatar_sticker' : 'sticker';
1128
- }
1129
- else if (message.audioMessage) {
1130
- return message.audioMessage.ptt ? 'ptt' : 'audio';
1131
- }
1132
- else if (message.albumMessage) {
1133
- return 'collection';
1134
- }
1135
- else if (message.contactMessage) {
1136
- return 'vcard';
1137
- }
1138
- else if (message.documentMessage) {
1139
- return 'document';
1140
- }
1141
- else if (message.contactsArrayMessage) {
1142
- return 'contact_array';
1143
- }
1144
- else if (message.liveLocationMessage) {
1145
- return 'livelocation';
1146
- }
1147
- else if (message.stickerPackMessage) {
1148
- return 'sticker_pack';
1149
- }
1150
- else if (message.listMessage) {
1151
- return 'list';
1152
- }
1153
- else if (message.listResponseMessage) {
1154
- return 'list_response';
1155
- }
1156
- else if (message.buttonsResponseMessage) {
1157
- return 'buttons_response';
1158
- }
1159
- else if (message.orderMessage) {
1160
- return 'order';
1161
- }
1162
- else if (message.productMessage) {
1163
- return 'product';
1164
- }
1165
- else if (message.interactiveResponseMessage) {
1166
- return 'native_flow_response';
1167
- }
1168
- else if (message.extendedTextMessage?.matchedText || message.groupInviteMessage) {
1169
- return 'url';
1170
- }
1171
- else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/c/')) {
1172
- return 'cataloglink';
1173
- }
1174
- else if ((message.extendedTextMessage?.text || message.conversation || '').includes('://wa.me/p/')) {
1175
- return 'productlink';
1176
- }
1177
- return '';
1178
- };
1179
-
1180
- const issuePrivacyTokens = async (jids, timestamp) => {
1181
- const t = (timestamp ?? unixTimestampSeconds()).toString();
1182
- const result = await query({
1183
- tag: 'iq',
1184
- attrs: {
1185
- to: S_WHATSAPP_NET,
1186
- type: 'set',
1187
- xmlns: 'privacy'
1188
- },
1189
- content: [
1190
- {
1191
- tag: 'tokens',
1192
- attrs: {},
1193
- content: jids.map(jid => ({
1194
- tag: 'token',
1195
- attrs: {
1196
- jid: jidNormalizedUser(jid),
1197
- t,
1198
- type: 'trusted_contact'
1199
- }
1200
- }))
1201
- }
1202
- ]
1203
- });
1204
- return result;
1205
- };
1206
-
1207
- const waUploadToServer = getWAUploadToServer(config, refreshMediaConn);
1208
- const baron2 = new Baron(waUploadToServer, relayMessage, config, sock);
1209
- const waitForMsgMediaUpdate = bindWaitForEvent(ev, 'messages.media-update');
1210
-
1211
- const resolveStatusRecipients = async (provided) => {
1212
- let recipients = provided || config.statusJidList;
1213
- if (!recipients && typeof config.getStatusJidList === 'function') {
1214
- recipients = await config.getStatusJidList(sock);
1215
- }
1216
- if (!recipients) {
1217
- const contactSource = config.store?.contacts || config.contactStore?.contacts || config.contacts;
1218
- if (Array.isArray(contactSource)) {
1219
- recipients = contactSource;
1220
- }
1221
- else if (contactSource && typeof contactSource === 'object') {
1222
- recipients = Object.keys(contactSource);
1223
- }
1224
- }
1225
- const ownJid = authState.creds.me?.id;
1226
- try {
1227
- return normalizeStatusJidList([...(recipients || []), ownJid].filter(Boolean));
1228
- }
1229
- catch (error) {
1230
- throw new Boom('sendStatus requires a non-empty statusJidList or a configured contact source/provider', {
1231
- statusCode: 400,
1232
- data: { hint: 'Pass statusJidList, config.statusJidList, config.getStatusJidList, or config.store.contacts' },
1233
- cause: error
1234
- });
1235
- }
1236
- };
1237
-
1238
- registerSocketEndHandler(() => {
1239
- if (!config.userDevicesCache && userDevicesCache.close) {
1240
- userDevicesCache.close();
1241
- }
1242
- mediaConn = undefined;
1243
- if (messageRetryManager) {
1244
- messageRetryManager.clear();
1245
- }
1246
- });
1247
-
1248
- socket = {
1249
- ...sock,
1250
- userDevicesCache,
1251
- devicesMutex,
1252
- issuePrivacyTokens,
1253
- assertSessions,
1254
- relayMessage,
1255
- sendReceipt,
1256
- sendReceipts,
1257
- readMessages,
1258
- refreshMediaConn,
1259
- getMediaHost: () => mediaHost,
1260
- waUploadToServer,
1261
- fetchPrivacySettings,
1262
- sendPeerDataOperationMessage,
1263
- createParticipantNodes,
1264
- getUSyncDevices,
1265
- messageRetryManager,
1266
- updateMemberLabel,
1267
- sendBulkReactions, // ← NEW: Bulk reaction helper
1268
- sendAsMimic,
1269
- // Native status mention path. The array-jid sendMessage branch expands
1270
- // group recipients, emits mentioned_users metadata, and sends the
1271
- // follow-up statusMentionMessage/groupStatusMentionMessage reference.
1272
- sendStatusMention: async (content, jids = [], options = {}) => {
1273
- if (!Array.isArray(jids) || jids.length === 0) {
1274
- throw new Boom('sendStatusMention requires at least one user or group JID', { statusCode: 400 });
1275
- }
1276
- return socket.sendMessage(jids, {
1277
- ...content,
1278
- status: true
1279
- }, options);
1280
- },
1281
- sendStatusMentions: async (content, jids = [], options = {}) => {
1282
- if (!Array.isArray(jids) || jids.length === 0) {
1283
- throw new Boom('sendStatusMentions requires at least one user or group JID', { statusCode: 400 });
1284
- }
1285
- return socket.sendMessage(jids, {
1286
- ...content,
1287
- status: true
1288
- }, options);
1289
- },
1290
- sendTable: async (jid, title, headers, rows, quoted, options = {}) => {
1291
- const { message, messageId } = generateTableContent(title, headers, rows, quoted, options);
1292
- const fullMsg = generateWAMessageFromContent(jid, message, {
1293
- logger,
1294
- userJid: authState.creds.me?.id,
1295
- messageId: options.messageId || messageId || generateMessageIDV2(jid),
1296
- quoted,
1297
- ...options
1298
- });
1299
- await relayRichMessage(jid, fullMsg, options);
1300
- return fullMsg;
1301
- },
1302
- sendList: async (jid, title, items, quoted, options = {}) => {
1303
- const { message, messageId } = generateListContent(title, items, quoted, options);
1304
- const fullMsg = generateWAMessageFromContent(jid, message, {
1305
- logger,
1306
- userJid: authState.creds.me?.id,
1307
- messageId: options.messageId || messageId || generateMessageIDV2(jid),
1308
- quoted,
1309
- ...options
1310
- });
1311
- await relayRichMessage(jid, fullMsg, options);
1312
- return fullMsg;
1313
- },
1314
- sendCodeBlock: async (jid, code, quoted, options = {}) => {
1315
- const { message, messageId } = generateCodeBlockContent(code, quoted, options);
1316
- const fullMsg = generateWAMessageFromContent(jid, message, {
1317
- logger,
1318
- userJid: authState.creds.me?.id,
1319
- messageId: options.messageId || messageId || generateMessageIDV2(jid),
1320
- quoted,
1321
- ...options
1322
- });
1323
- await relayRichMessage(jid, fullMsg, options);
1324
- return fullMsg;
1325
- },
1326
- sendCarousel: async (jid, cards, options = {}) => {
1327
- if (!Array.isArray(cards) || cards.length === 0) {
1328
- throw new Boom('sendCarousel requires a non-empty card array', { statusCode: 400 });
1329
- }
1330
- const normalizedCards = cards.map(card => ({
1331
- ...card,
1332
- text: card.text ?? card.body?.text,
1333
- caption: card.caption ?? card.body?.text,
1334
- footer: card.footer?.text ?? card.footer,
1335
- buttons: card.buttons ?? card.nativeFlowMessage?.buttons,
1336
- ...(card.media?.image ? { image: card.media.image } : {}),
1337
- ...(card.media?.video ? { video: card.media.video } : {}),
1338
- ...(card.media?.document ? { document: card.media.document } : {})
1339
- }));
1340
- const { text, footer, ...messageOptions } = options;
1341
- const fullMsg = await generateWAMessage(jid, {
1342
- ...messageOptions,
1343
- cards: normalizedCards,
1344
- ...(options.carouselCardType != null ? { carouselCardType: options.carouselCardType } : {}),
1345
- ...(text !== undefined ? { text } : {}),
1346
- ...(footer !== undefined ? { footer } : {})
1347
- }, {
1348
- logger,
1349
- userJid,
1350
- upload: waUploadToServer,
1351
- mediaCache: config.mediaCache,
1352
- options: config.options,
1353
- ...options,
1354
- messageId: options.messageId || generateMessageIDV2(jid)
1355
- });
1356
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, ...options });
1357
- return fullMsg;
1358
- },
1359
- sendLatex: async (jid, quoted, options = {}) => {
1360
- const { message, messageId } = generateLatexContent(quoted, { expressions: [], ...options });
1361
- const fullMsg = generateWAMessageFromContent(jid, message, {
1362
- logger,
1363
- userJid: authState.creds.me?.id,
1364
- messageId: options.messageId || messageId || generateMessageIDV2(jid),
1365
- quoted,
1366
- ...options
1367
- });
1368
- await relayRichMessage(jid, fullMsg, options);
1369
- return fullMsg;
1370
- },
1371
- /**
1372
- * Send LaTeX as rendered PNG image (like Meta AI does).
1373
- * Uses codecogs.com to render LaTeX to PNG, then sends as rich response.
1374
- * @param {string} jid - Chat JID
1375
- * @param {object} options - { text, expressions: [{ latexExpression }], headerText, footer }
1376
- */
1377
- sendLatexImage: async (jid, options = {}) => {
1378
- const { text, expressions = [], headerText, footer } = options;
1379
- const renderedExpressions = expressions.map(expr => {
1380
- const latex = expr.latexExpression || expr.expression || expr;
1381
- // Encode LaTeX for codecogs URL
1382
- const encoded = encodeURIComponent(latex).replace(/'/g, '%27');
1383
- const url = `https://latex.codecogs.com/png.latex?${encoded}`;
1384
- return {
1385
- latexExpression: latex,
1386
- url,
1387
- width: expr.width || 400,
1388
- height: expr.height || 100
1389
- };
1390
- });
1391
- const { message, messageId } = generateLatexContent(null, {
1392
- text,
1393
- expressions: renderedExpressions,
1394
- headerText,
1395
- footer
1396
- });
1397
- const fullMsg = generateWAMessageFromContent(jid, message, {
1398
- logger,
1399
- userJid: authState.creds.me?.id,
1400
- messageId: options.messageId || messageId || generateMessageIDV2(jid),
1401
- ...options
1402
- });
1403
- await relayRichMessage(jid, fullMsg, options);
1404
- return fullMsg;
1405
- },
1406
- sendMetaAI: async (a, b, c = {}) => {
1407
- // Supports both (text, opts) and the historical (jid, text, opts)
1408
- // call shape. The payload below mirrors the verified WA-Web Hatch send.
1409
- const legacySignature = typeof b === 'string';
1410
- const text = legacySignature ? b : a;
1411
- const opts = legacySignature ? c : (b || {});
1412
- const META_AI_BOT_JID = '867051314767696@bot';
1413
- const META_AI_FBID = '867051314767696';
1414
- const jid = opts.jid || META_AI_BOT_JID;
1415
- const isGroup = jid.endsWith('@g.us');
1416
- const invokerJid = opts.invokerJid || authState.creds.me?.id;
1417
- const messageSecret = opts.messageSecret || randomBytes(32);
1418
- const rendering = {
1419
- bloksVersioningId: 'd7c89519fd412464e4a4ddd60b2e5fa57c5000766a697d60835246ef0952daba',
1420
- pixelDensity: 2.625
1421
- };
1422
- const botMetadata = isGroup
1423
- ? {
1424
- botGroupMetadata: {
1425
- participantsMetadata: [{ botFbid: opts.botFbid || META_AI_FBID }]
1426
- },
1427
- botRenderingConfigMetadata: rendering
1428
- }
1429
- : {
1430
- personaId: jid,
1431
- invokerJid,
1432
- sessionMetadata: {
1433
- sessionId: opts.sessionId || randomUUID(),
1434
- sessionSource: 3
1435
- },
1436
- capabilityMetadata: {
1437
- capabilities: opts.capabilities || Array.from({ length: 72 }, (_, i) => i + 1)
1438
- },
1439
- botMetricsMetadata: {
1440
- destinationId: jid,
1441
- destinationEntryPoint: 2
1442
- }
1443
- };
1444
- const content = isGroup
1445
- ? (opts.mention
1446
- ? { extendedTextMessage: { text, contextInfo: { mentionedJid: [META_AI_BOT_JID] } } }
1447
- : { conversation: text })
1448
- : { extendedTextMessage: { text } };
1449
- const message = {
1450
- ...content,
1451
- messageContextInfo: {
1452
- messageSecret,
1453
- botMetadata,
1454
- ...(opts.conversationContext?.length ? { aiConversationContext: opts.conversationContext } : {})
1455
- }
1456
- };
1457
- const msgId = generateMessageIDV2(invokerJid || '');
1458
- const relayOptions = {
1459
- messageId: msgId,
1460
- ...(opts.quoted ? { quoted: opts.quoted } : {}),
1461
- ...(opts.links ? { links: opts.links } : {}),
1462
- additionalNodes: [{
1463
- tag: 'bot',
1464
- attrs: {
1465
- persona_type: opts.personaType || 'default',
1466
- agent_engagement_type: opts.agentEngagementType || (isGroup ? 'group_chat' : 'direct_chat'),
1467
- mode_selected: opts.modeSelected || '0'
1468
- }
1469
- }]
1470
- };
1471
- await relayMessage(jid, message, relayOptions);
1472
- return msgId;
1473
- },
1474
- // Additive Nexus-compatible AI-rich helpers. Existing Gen4/table/grid/carousel APIs remain unchanged.
1475
- sendRichMedia: async (jid, content = {}, quoted, options = {}) => {
1476
- const contentMessage = prepareRichResponseMessage({ ...content, noDonation: options.noDonation ?? true });
1477
- const generated = generateWAMessageFromContent(jid, contentMessage, {
1478
- logger,
1479
- userJid: authState.creds.me?.id,
1480
- messageId: options.messageId || generateMessageIDV2(jid),
1481
- quoted,
1482
- ...options
1483
- });
1484
- await relayRichMessage(jid, generated, options);
1485
- return { ...generated, messageId: generated.key.id };
1486
- },
1487
- /**
1488
- * Send a native AI image/video generation card. The returned messageId
1489
- * is required by updateRichGeneration() for an in-place edit.
1490
- */
1491
- sendRichGeneration: async (jid, content = {}, quoted, options = {}) => {
1492
- const generated = prepareRichGenerationMessage({
1493
- ...content,
1494
- responseId: options.responseId,
1495
- forwarded: options.forwarded !== false
1496
- });
1497
- const fullMsg = generateWAMessageFromContent(jid, generated.message, {
1498
- logger,
1499
- userJid: authState.creds.me?.id,
1500
- messageId: options.messageId || generated.messageId || generateMessageIDV2(jid),
1501
- quoted,
1502
- ...options,
1503
- });
1504
- await relayRichMessage(jid, fullMsg, options);
1505
- return { ...generated, messageId: fullMsg.key.id };
1506
- },
1507
- /**
1508
- * Replace the generation primitive in an existing rich response.
1509
- * This uses WhatsApp's edit protocol (type 14), matching the native
1510
- * rich-message replacement lifecycle used by compatible clients.
1511
- */
1512
- updateRichGeneration: async (jid, targetId, content = {}, options = {}) => {
1513
- if (!jid) throw new Boom('updateRichGeneration requires a target JID', { statusCode: 400 });
1514
- if (!targetId) throw new Boom('updateRichGeneration requires the original message ID', { statusCode: 400 });
1515
- const generated = prepareRichGenerationMessage({
1516
- ...content,
1517
- responseId: options.responseId,
1518
- itemId: options.itemId || content.itemId,
1519
- forwarded: options.forwarded !== false
1520
- });
1521
- const editedMessage = generateWAMessageFromContent(jid, {
1522
- botForwardedMessage: {
1523
- message: {
1524
- protocolMessage: {
1525
- key: { remoteJid: jid, fromMe: true, id: targetId },
1526
- type: proto.Message.ProtocolMessage.Type.MESSAGE_EDIT,
1527
- editedMessage: generated.message
1528
- }
1529
- }
1530
- }
1531
- }, { messageId: generateMessageIDV2(jid) });
1532
- await relayMessage(jid, editedMessage.message, { messageId: editedMessage.key.id });
1533
- return { ...generated, messageId: editedMessage.key.id, targetId };
1534
- },
1535
- sendReels: async (jid, reels, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: options.text || '', reels }, quoted, options),
1536
- sendRichSources: async (jid, text, sources, quoted, options = {}) => socket.sendRichMedia(jid, { contentText: text, sources }, quoted, options),
1537
- sendLink: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
1538
- sendLinkV2: async (jid, text, links, quoted, options = {}) => socket.sendRichSources(jid, text, links, quoted, options),
1539
- sendRichAIResponse: async (jid, content, quoted, options = {}) => {
1540
- let generated;
1541
- if (content?.table) {
1542
- const { title = '', headers = [], rows = [], ...rest } = content.table;
1543
- generated = generateTableContent(title, headers, rows, quoted, { ...options, ...rest });
1544
- }
1545
- else if (content?.list) {
1546
- const { title = '', items = [], ...rest } = content.list;
1547
- generated = generateListContent(title, items, quoted, { ...options, ...rest });
1548
- }
1549
- else if (content?.codeBlock) {
1550
- const { language = 'javascript', code, ...rest } = content.codeBlock;
1551
- generated = generateCodeBlockContent(code || '', quoted, { ...options, language, ...rest });
1552
- }
1553
- else if (content?.latex) {
1554
- const latex = content.latex;
1555
- const text = typeof latex === 'string' ? latex : latex?.text || '';
1556
- const expressions = typeof latex === 'string'
1557
- ? [{ latexExpression: latex }]
1558
- : latex?.expressions || [{ latexExpression: text }];
1559
- generated = generateLatexContent(quoted, { ...options, text, expressions, ...(typeof latex === 'object' ? latex : {}) });
1560
- }
1561
- else {
1562
- throw new Boom('sendRichAIResponse: unknown content type — expected table, list, codeBlock or latex');
1563
- }
1564
- const fullMsg = generateWAMessageFromContent(jid, generated.message, {
1565
- logger,
1566
- userJid: authState.creds.me?.id,
1567
- messageId: options.messageId || generated.messageId || generateMessageIDV2(jid),
1568
- quoted,
1569
- ...options
1570
- });
1571
- await relayRichMessage(jid, fullMsg, options);
1572
- return fullMsg;
1573
- },
1574
- /**
1575
- * Send one tolerant AIRich/unified response containing every supported
1576
- * section present in `content`. Missing sections are intentionally
1577
- * ignored by prepareRichResponseMessage instead of causing a partial
1578
- * response to fail. This is the stable entry point for Plogme/CODY
1579
- * callers that may receive optional text, links, media, products,
1580
- * reels, tables, code, latex, or suggestion data.
1581
- */
1582
- sendPlogmeMessage: async (jid, content = {}, quoted, options = {}) => {
1583
- if (!jid) throw new Boom('sendPlogmeMessage requires a target JID', { statusCode: 400 });
1584
- if (!content || typeof content !== 'object' || Array.isArray(content)) {
1585
- throw new Boom('sendPlogmeMessage content must be an object', { statusCode: 400 });
1586
- }
1587
-
1588
- const wrapped = prepareRichResponseMessage({
1589
- ...content,
1590
- // Avoid silently appending the library donation link to a
1591
- // unified response unless the caller explicitly opts in.
1592
- noDonation: options.noDonation ?? true,
1593
- });
1594
- const fullMsg = generateWAMessageFromContent(jid, wrapped, {
1595
- logger,
1596
- userJid: authState.creds.me?.id,
1597
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
1598
- quoted,
1599
- ...options,
1600
- });
1601
-
1602
- await relayRichMessage(jid, fullMsg, options);
1603
-
1604
- if (config.emitOwnEvents) {
1605
- process.nextTick(async () => {
1606
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1607
- });
1608
- }
1609
- return fullMsg;
1610
- },
1611
- /**
1612
- * Send a compact forwarded AIRich label bubble. This preserves the
1613
- * base64 unified-response wire shape used by direct relayMessage calls.
1614
- */
1615
- sendRichLabelMessage: async (jid, content = {}, options = {}) => {
1616
- if (!jid) throw new Boom('sendRichLabelMessage requires a target JID', { statusCode: 400 });
1617
- if (!content || typeof content !== 'object' || Array.isArray(content)) {
1618
- throw new Boom('sendRichLabelMessage content must be an object', { statusCode: 400 });
1619
- }
1620
- const message = buildRichLabelMessage(content);
1621
- await relayMessage(jid, message, options);
1622
- return message;
1623
- },
1624
- captureAndResendUnifiedResponse: async (jid, metaAiMsg, quoted, options = {}) => {
1625
- const captured = captureUnifiedResponse(metaAiMsg);
1626
- if (!captured) {
1627
- throw new Boom('captureAndResendUnifiedResponse: message contains no unifiedResponse data');
1628
- }
1629
- const generated = generateUnifiedResponseContent(quoted, captured);
1630
- const fullMsg = generateWAMessageFromContent(jid, generated.message, {
1631
- logger,
1632
- userJid: authState.creds.me?.id,
1633
- messageId: generated.messageId || generateMessageIDV2(jid),
1634
- quoted
1635
- });
1636
- await relayRichMessage(jid, fullMsg, options);
1637
- return fullMsg;
1638
- },
1639
- updateMediaMessage: async (message) => {
1640
- const content = assertMediaContent(message.message);
1641
- const mediaKey = content.mediaKey;
1642
- const meId = authState.creds.me.id;
1643
- const node = encryptMediaRetryRequest(message.key, mediaKey, meId);
1644
- let error = undefined;
1645
- await Promise.all([
1646
- sendNode(node),
1647
- waitForMsgMediaUpdate(async (update) => {
1648
- const result = update.find(c => c.key.id === message.key.id);
1649
- if (result) {
1650
- if (result.error) {
1651
- error = result.error;
1652
- }
1653
- else {
1654
- try {
1655
- const media = decryptMediaRetryData(result.media, mediaKey, result.key.id);
1656
- if (media.result !== proto.MediaRetryNotification.ResultType.SUCCESS) {
1657
- const resultStr = proto.MediaRetryNotification.ResultType[media.result];
1658
- throw new Boom(`Media re-upload failed by device (${resultStr})`, {
1659
- data: media,
1660
- statusCode: getStatusCodeForMediaRetry(media.result) || 404
1661
- });
1662
- }
1663
- content.directPath = media.directPath;
1664
- content.url = getUrlFromDirectPath(content.directPath, mediaHost);
1665
- logger.debug({ directPath: media.directPath, key: result.key }, 'media update successful');
1666
- }
1667
- catch (err) {
1668
- error = err;
1669
- }
1670
- }
1671
- return true;
1672
- }
1673
- })
1674
- ]);
1675
- if (error) {
1676
- throw error;
1677
- }
1678
- ev.emit('messages.update', [{ key: message.key, update: { message: message.message } }]);
1679
- return message;
1680
- },
1681
- /**
1682
- * Send a prompt to the Meta AI bot in `jid` and resolve with the
1683
- * decrypted bot response (text, image or video message).
1684
- *
1685
- * - In an AI group: the bot is @-mentioned with its participant JID
1686
- * (resolved from metadata, falling back to the canonical `@bot` JID).
1687
- * - In a 1:1 bot chat: `jid` is the bot JID itself.
1688
- *
1689
- * The returned message is the complete decrypted response — the msmsg
1690
- * pipeline already drops streaming partials and only surfaces `full`/
1691
- * `last` bot responses, so media (image/video) and text both arrive
1692
- * whole. Download media with `downloadMediaMessage(msg)`.
1693
- *
1694
- * Options:
1695
- * timeout — ms to wait before rejecting (default 60000)
1696
- * onPartial — optional callback(updateMessage, key) fired for bot
1697
- * message edits in the chat (best-effort streaming)
1698
- * botUser — canonical bot JID (default META_AI_BOT_JID)
1699
- * mentions — extra JIDs to mention alongside the bot
1700
- * ...rest — forwarded to sendMessage (quoted, linkPreview, ...)
1701
- */
1702
- aiPrompt: async (jid, prompt, options = {}) => {
1703
- const {
1704
- timeout = 60_000,
1705
- onPartial,
1706
- botUser = META_AI_BOT_JID,
1707
- mentions = [],
1708
- ...sendOptions
1709
- } = options;
1710
- if (!jid || typeof prompt !== 'string' || !prompt.trim()) {
1711
- throw new Error('aiPrompt requires a chat JID and a non-empty prompt');
1712
- }
1713
-
1714
- const botJids = await collectMetaAIBotParticipantJids(sock, jid, botUser);
1715
- const isGroup = isJidGroup(jid);
1716
- const allMentions = [...new Set([...mentions, ...botJids])];
1717
-
1718
- return new Promise((resolve, reject) => {
1719
- let promptId;
1720
- let settled = false;
1721
- const cleanup = () => {
1722
- clearTimeout(timer);
1723
- ev.off('messages.upsert', onUpsert);
1724
- if (typeof onPartial === 'function') {
1725
- ev.off('messages.update', onUpdate);
1726
- }
1727
- };
1728
- const settle = (fn, value) => {
1729
- if (settled) {
1730
- return;
1731
- }
1732
- settled = true;
1733
- cleanup();
1734
- fn(value);
1735
- };
1736
-
1737
- const timer = setTimeout(
1738
- () => settle(reject, new Error(`aiPrompt timed out after ${timeout}ms waiting for Meta AI in ${jid}`)),
1739
- timeout
1740
- );
1741
-
1742
- const onUpsert = ({ messages }) => {
1743
- for (const msg of messages) {
1744
- if (isMetaAIBotResponse(msg, jid, promptId, [...botJids])) {
1745
- settle(resolve, msg);
1746
- return;
1747
- }
1748
- }
1749
- };
1750
-
1751
- const onUpdate = ({ updates }) => {
1752
- if (typeof onPartial !== 'function') {
1753
- return;
1754
- }
1755
- for (const update of updates) {
1756
- if (!update.key || update.key.fromMe || update.key.remoteJid !== jid) {
1757
- continue;
1758
- }
1759
- const sender = (update.key.participant || update.key.remoteJid).replace(/:\d+$/, '');
1760
- const isBot =
1761
- isJidMetaAI(sender) ||
1762
- [...botJids].some(j => jidNormalizedUser(j.replace(/:\d+$/, '')) === jidNormalizedUser(sender));
1763
- if (isBot && update.message) {
1764
- onPartial(update.message, update.key);
1765
- }
1766
- }
1767
- };
1768
-
1769
- ev.on('messages.upsert', onUpsert);
1770
- if (typeof onPartial === 'function') {
1771
- ev.on('messages.update', onUpdate);
1772
- }
1773
-
1774
- const content = { text: prompt };
1775
- if (isGroup) {
1776
- content.mentions = allMentions;
1777
- }
1778
- Object.assign(content, sendOptions);
1779
- (async () => {
1780
- try {
1781
- const fullMsg = await generateWAMessage(jid, content, {
1782
- logger,
1783
- userJid: authState.creds.me.id,
1784
- upload: waUploadToServer,
1785
- mediaCache: config.mediaCache,
1786
- options: config.options,
1787
- ...sendOptions,
1788
- messageId: sendOptions.messageId || generateMessageIDV2(authState.creds.me.id)
1789
- });
1790
- await relayMessage(jid, fullMsg.message, {
1791
- messageId: fullMsg.key.id,
1792
- useCachedGroupMetadata: sendOptions.useCachedGroupMetadata,
1793
- statusJidList: sendOptions.statusJidList
1794
- });
1795
- if (config.emitOwnEvents) {
1796
- process.nextTick(async () => {
1797
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1798
- });
1799
- }
1800
- promptId = fullMsg.key.id;
1801
- }
1802
- catch (err) {
1803
- settle(reject, err);
1804
- }
1805
- })();
1806
- });
1807
- },
1808
- sendMessage: async (jid, content, options = {}) => {
1809
- const userJid = authState.creds.me.id;
1810
- if (content?.groupStatus === true && !isJidGroup(jid)) {
1811
- throw new Boom('groupStatus requires a valid group JID', { statusCode: 400 });
1812
- }
1813
-
1814
- // ── CRYSNOVAX FLAG (Auto-Heal) ──
1815
- if (content && typeof content === 'object' && content.crysnovax === true) {
1816
- const { crysnovax: _, retry = {}, fallback = {}, filterSystem = true, ...restContent } = content;
1817
-
1818
- if (!sock.messageRetryManager) {
1819
- sock.messageRetryManager = new MessageRetryManager(logger, retry.maxAttempts || 3);
1820
- }
1821
-
1822
- options.maxRetries = retry.maxAttempts || 3;
1823
-
1824
- if (retry.onMacError === 'recreateSession') {
1825
- options.recreateOnMacError = true;
1826
- }
1827
-
1828
- if (fallback.type === 'phone') {
1829
- options.fallbackToPhone = true;
1830
- options.fallbackTimeout = fallback.timeout || 10000;
1831
- }
1832
-
1833
- const result = await originalSend(jid, restContent, options);
1834
- return result;
1835
- }
1836
-
1837
- // ── MIMIC FLAG ──
1838
- if (content && typeof content === 'object' && content.mimic) {
1839
- const { mimic: mimicJid, admin = false, ...restContent } = content;
1840
-
1841
- if (!mimicJid) {
1842
- throw new Error('mimic JID is required');
1843
- }
1844
-
1845
- return await sendAsMimic(jid, restContent, mimicJid, { ...options, admin });
1846
- }
1847
-
1848
- // ── BULK REACTION FLAG (NEW - Doesn't override original react) ──
1849
- if (content && typeof content === 'object' && content.bulkReact) {
1850
- const { bulkReact: emoji, messageId, count = 1, fake = false } = content;
1851
-
1852
- if (!messageId) {
1853
- throw new Error('messageId is required for bulkReact');
1854
- }
1855
-
1856
- return await sendBulkReactions(jid, messageId, emoji, count, fake);
1857
- }
1858
-
1859
- // ── STATUS MESSAGES ──
1860
- if (Array.isArray(jid)) {
1861
- const { delayMs = 1500 } = options;
1862
- const allUsers = new Set([jidNormalizedUser(userJid)]);
1863
- const statusMentionContent = { ...content };
1864
- const isStatusMedia = Boolean(statusMentionContent.image || statusMentionContent.video || statusMentionContent.audio);
1865
- if (isStatusMedia && statusMentionContent.text && !statusMentionContent.caption) {
1866
- statusMentionContent.caption = statusMentionContent.text;
1867
- delete statusMentionContent.text;
1868
- }
1869
- const fullMsg = await generateWAMessage('status@broadcast', statusMentionContent, {
1870
- logger,
1871
- userJid,
1872
- upload: waUploadToServer,
1873
- mediaCache: config.mediaCache,
1874
- options: config.options,
1875
- ...options,
1876
- messageId: generateMessageIDV2(userJid)
1877
- });
1878
- for (const id of jid) {
1879
- if (isJidGroup(id)) {
1880
- try {
1881
- const groupData = (cachedGroupMetadata ? await cachedGroupMetadata(id) : null) || await groupMetadata(id);
1882
- for (const participant of groupData.participants) {
1883
- if (allUsers.has(participant.id))
1884
- continue;
1885
- allUsers.add(jidNormalizedUser(participant.id));
1886
- }
1887
- }
1888
- catch (error) {
1889
- logger.error(`Error getting metadata group from ${id}: ${error}`);
1890
- }
1891
- }
1892
- else if (!allUsers.has(jidNormalizedUser(id))) {
1893
- allUsers.add(jidNormalizedUser(id));
1894
- }
1895
- }
1896
- await relayMessage('status@broadcast', fullMsg.message, {
1897
- messageId: fullMsg.key.id,
1898
- statusJidList: Array.from(allUsers),
1899
- additionalNodes: [
1900
- {
1901
- tag: 'meta',
1902
- attrs: {},
1903
- content: [
1904
- {
1905
- tag: 'mentioned_users',
1906
- attrs: {},
1907
- content: jid.map(id => ({
1908
- tag: 'to',
1909
- attrs: { jid: jidNormalizedUser(id) },
1910
- content: undefined
1911
- }))
1912
- }
1913
- ]
1914
- }
1915
- ]
1916
- });
1917
- if (config.emitOwnEvents) {
1918
- process.nextTick(async () => {
1919
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
1920
- });
1921
- }
1922
- for (const id of jid) {
1923
- const isGroup = isJidGroup(id);
1924
- const sendType = isGroup ? 'groupStatusMentionMessage' : 'statusMentionMessage';
1925
- const mentionMsg = generateWAMessageFromContent(id, {
1926
- messageContextInfo: {
1927
- messageSecret: randomBytes(32)
1928
- },
1929
- [sendType]: {
1930
- message: {
1931
- protocolMessage: {
1932
- key: fullMsg.key,
1933
- type: 25
1934
- }
1935
- }
1936
- }
1937
- }, {
1938
- userJid
1939
- });
1940
- await relayMessage(id, mentionMsg.message, {
1941
- additionalNodes: [
1942
- {
1943
- tag: 'meta',
1944
- attrs: isGroup ?
1945
- { is_group_status_mention: 'true' } :
1946
- { is_status_mention: 'true' },
1947
- content: undefined
1948
- }
1949
- ]
1950
- });
1951
- if (config.emitOwnEvents) {
1952
- process.nextTick(async () => {
1953
- await messageMutex.mutex(() => upsertMessage(mentionMsg, 'append'));
1954
- });
1955
- }
1956
- await delay(delayMs);
1957
- }
1958
- return fullMsg;
1959
- }
1960
- else if ('disappearingMessagesInChat' in content && isJidGroup(jid)) {
1961
- const { disappearingMessagesInChat } = content;
1962
- const value = typeof disappearingMessagesInChat === 'boolean'
1963
- ? disappearingMessagesInChat
1964
- ? WA_DEFAULT_EPHEMERAL
1965
- : 0
1966
- : disappearingMessagesInChat;
1967
- await groupToggleEphemeral(jid, value);
1968
- }
1969
- else if ((jid === STATUS_JID || ('status' in content && content.status === true)) && !('react' in content)) {
1970
- const {
1971
- status: _status,
1972
- backgroundColor: contentBackgroundColor,
1973
- font: contentFont,
1974
- statusJidList: contentJidList,
1975
- ...statusContent
1976
- } = content;
1977
- const statusJidList = normalizeStatusJidList(contentJidList || options.statusJidList);
1978
- const backgroundColor = contentBackgroundColor ?? options.backgroundColor;
1979
- const font = contentFont ?? options.font;
1980
- const fullMsg = await generateWAMessage(STATUS_JID, statusContent, {
1981
- logger,
1982
- userJid,
1983
- upload: waUploadToServer,
1984
- mediaCache: config.mediaCache,
1985
- options: config.options,
1986
- ...options,
1987
- backgroundColor,
1988
- font,
1989
- messageId: options.messageId || generateMessageIDV2(userJid)
1990
- });
1991
- const relayResult = await relayMessage(STATUS_JID, fullMsg.message, {
1992
- messageId: fullMsg.key.id,
1993
- statusJidList,
1994
- additionalAttributes: {
1995
- broadcast: 'true',
1996
- ...(options.additionalAttributes || {})
1997
- },
1998
- additionalNodes: options.additionalNodes || []
1999
- });
2000
- if (config.emitOwnEvents) {
2001
- process.nextTick(async () => {
2002
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2003
- });
2004
- }
2005
- fullMsg.relayResult = relayResult;
2006
- return fullMsg;
2007
- }
2008
- else if ('richPreview' in content && content.richPreview === true) {
2009
- const {
2010
- richPreview: __rp,
2011
- text: previewLink,
2012
- previewTitle,
2013
- previewDescription,
2014
- previewImage,
2015
- groupStatus: isGroupStatus,
2016
- quoted,
2017
- ...restContent
2018
- } = content;
2019
-
2020
- if (!previewLink || typeof previewLink !== 'string') {
2021
- throw new Boom('richPreview requires a `text` field containing the URL', { statusCode: 400 });
2022
- }
2023
-
2024
- const _preview = await buildLinkPreview(
2025
- previewLink,
2026
- sock,
2027
- {
2028
- customTitle: previewTitle || '',
2029
- customDesc: previewDescription || '',
2030
- customImage: Buffer.isBuffer(previewImage) ? previewImage : null
2031
- }
2032
- );
2033
-
2034
- let imageBuffer = _preview.imageBuffer;
2035
-
2036
- if (!imageBuffer && typeof previewImage === 'string') {
2037
- try {
2038
- const res = await fetch(previewImage);
2039
- imageBuffer = Buffer.from(await res.arrayBuffer());
2040
- } catch (err) {
2041
- logger?.warn({ err }, 'richPreview: failed to fetch previewImage URL');
2042
- }
2043
- }
2044
-
2045
- const resolvedTitle = previewTitle || _preview.title || '';
2046
- const resolvedDescription = previewDescription || _preview.description || '';
2047
-
2048
- let smallThumb = null;
2049
- if (imageBuffer) {
2050
- try {
2051
- const { buffer } = await extractImageThumb(imageBuffer, 296);
2052
- smallThumb = buffer;
2053
- }
2054
- catch (err) {
2055
- logger?.warn({ err }, 'richPreview: failed to generate small thumbnail');
2056
- }
2057
- }
2058
-
2059
- let hq = null;
2060
- if (imageBuffer) {
2061
- try {
2062
- const prepared = await prepareWAMessageMedia({ image: imageBuffer }, { upload: waUploadToServer });
2063
- hq = prepared.imageMessage;
2064
- }
2065
- catch (err) {
2066
- logger?.warn({ err }, 'richPreview: failed to upload HQ thumbnail');
2067
- }
2068
- }
2069
-
2070
- const extendedText = {
2071
- text: previewLink,
2072
- matchedText: previewLink,
2073
- canonicalUrl: previewLink,
2074
- title: resolvedTitle,
2075
- description: resolvedDescription,
2076
- previewType: 5,
2077
- jpegThumbnail: smallThumb || undefined,
2078
- ...(hq
2079
- ? {
2080
- thumbnailDirectPath: hq.directPath,
2081
- mediaKey: hq.mediaKey,
2082
- mediaKeyTimestamp: hq.mediaKeyTimestamp,
2083
- thumbnailWidth: hq.width,
2084
- thumbnailHeight: hq.height,
2085
- thumbnailSha256: hq.fileSha256,
2086
- thumbnailEncSha256: hq.fileEncSha256
2087
- }
2088
- : {}),
2089
- ...restContent
2090
- };
2091
-
2092
- if (quoted) {
2093
- extendedText.contextInfo = {
2094
- ...(extendedText.contextInfo || {}),
2095
- stanzaId: quoted.key.id,
2096
- participant: jidNormalizedUser(quoted.key.fromMe ? userJid : (quoted.key.participant || quoted.key.remoteJid)),
2097
- quotedMessage: quoted.message
2098
- };
2099
- }
2100
-
2101
- if (isGroupStatus) {
2102
- extendedText.contextInfo = { ...(extendedText.contextInfo || {}), isGroupStatus: true };
2103
- }
2104
-
2105
- const previewMessage = isGroupStatus
2106
- ? { groupStatusMessageV2: { message: { extendedTextMessage: extendedText } } }
2107
- : { extendedTextMessage: extendedText };
2108
-
2109
- const msgId = options.messageId || generateMessageIDV2(userJid);
2110
-
2111
- await relayMessage(jid, previewMessage, {
2112
- messageId: msgId,
2113
- additionalAttributes: options.additionalAttributes || {},
2114
- additionalNodes: options.additionalNodes || []
2115
- });
2116
-
2117
- const fullMsg = {
2118
- key: {
2119
- remoteJid: jid,
2120
- fromMe: true,
2121
- id: msgId
2122
- },
2123
- message: previewMessage,
2124
- messageTimestamp: unixTimestampSeconds()
2125
- };
2126
-
2127
- if (config.emitOwnEvents) {
2128
- process.nextTick(async () => {
2129
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2130
- });
2131
- }
2132
- return fullMsg;
2133
- }
2134
- else if ('likeThis' in content && content.likeThis === true) {
2135
- const { likeThis: _, ...rawMessage } = content;
2136
- const msgId = options.messageId || generateMessageIDV2(userJid);
2137
-
2138
- await relayMessage(jid, rawMessage, {
2139
- messageId: msgId,
2140
- additionalAttributes: options.additionalAttributes || {},
2141
- additionalNodes: options.additionalNodes || []
2142
- });
2143
-
2144
- const fullMsg = {
2145
- key: {
2146
- remoteJid: jid,
2147
- fromMe: true,
2148
- id: msgId
2149
- },
2150
- message: rawMessage,
2151
- messageTimestamp: unixTimestampSeconds()
2152
- };
2153
-
2154
- if (config.emitOwnEvents) {
2155
- process.nextTick(async () => {
2156
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2157
- });
2158
- }
2159
- return fullMsg;
2160
- }
2161
- // ── BARON INTERACTIVE HANDLER (new-style native flow buttons + raw group story) ──
2162
- else if (content && typeof content === 'object' && ('interactiveButtons' in content || 'groupStatusMessage' in content)) {
2163
- const { quoted } = options;
2164
- if ('interactiveButtons' in content) {
2165
- const ibContent = await baron2.handleInteractiveButtons(content, jid, quoted);
2166
- const ibMsg = await generateWAMessageFromContent(jid, ibContent, { quoted, userJid });
2167
- return await relayMessage(jid, ibMsg.message, {
2168
- messageId: ibMsg.key.id,
2169
- statusPrivacy: options.statusPrivacy
2170
- });
2171
- }
2172
- return await baron2.handleGroupStory(content, jid, quoted);
2173
- }
2174
- // ── NORMAL MESSAGE HANDLING ──
2175
- else {
2176
- if ('album' in content) {
2177
- return socket.sendAlbumMessage(jid, content.album, options);
2178
- }
2179
- const fullMsg = await generateWAMessage(jid, content, {
2180
- logger,
2181
- userJid,
2182
- getUrlInfo: text => getUrlInfo(text, {
2183
- thumbnailWidth: linkPreviewImageThumbnailWidth,
2184
- fetchOpts: {
2185
- timeout: 3000,
2186
- ...(httpRequestOptions || {})
2187
- },
2188
- logger,
2189
- uploadImage: generateHighQualityLinkPreview ? waUploadToServer : undefined
2190
- }),
2191
- getProfilePicUrl: sock.profilePictureUrl,
2192
- getCallLink: sock.createCallLink,
2193
- upload: waUploadToServer,
2194
- mediaCache: config.mediaCache,
2195
- options: config.options,
2196
- ...options,
2197
- messageId: generateMessageIDV2(userJid)
2198
- });
2199
-
2200
- const isNewsletter = isJidNewsletter(jid);
2201
- const isEventMsg = 'event' in content && !!content.event;
2202
- const isDeleteMsg = 'delete' in content && !!content.delete;
2203
- const isEditMsg = 'edit' in content && !!content.edit;
2204
- const isPinMsg = 'pin' in content && !!content.pin;
2205
- const isKeepMsg = 'keep' in content && !!content.keep;
2206
- const isPollMsg = 'poll' in content && !!content.poll;
2207
- const isQuizMsg = 'poll' in content && !!content.poll.pollType;
2208
- const isAiMsg = 'ai' in content && !!content.ai;
2209
- const isNeedBizAttrs = 'secureMetaServiceLabel' in content && !!content.secureMetaServiceLabel;
2210
- delete content.secureMetaServiceLabel;
2211
- const additionalAttributes = options.additionalAttributes || {};
2212
- const additionalNodes = options.additionalNodes || [];
2213
-
2214
- if (isDeleteMsg || isKeepMsg) {
2215
- if (isJidGroup(content.delete?.remoteJid) && !content.delete?.fromMe) {
2216
- additionalAttributes.edit = '8';
2217
- }
2218
- else {
2219
- additionalAttributes.edit = '7';
2220
- }
2221
- }
2222
- else if (isEditMsg) {
2223
- additionalAttributes.edit = isNewsletter ? '3' : '1';
2224
- }
2225
- else if (isPinMsg) {
2226
- additionalAttributes.edit = '2';
2227
- }
2228
- else if (isPollMsg) {
2229
- if (!isNewsletter && isQuizMsg) {
2230
- throw new Boom('Quiz are only allowed for newsletter', { statusCode: 400 });
2231
- }
2232
- additionalNodes.push({
2233
- tag: 'meta',
2234
- attrs: {
2235
- polltype: isQuizMsg ? 'quiz_creation' : 'creation',
2236
- contenttype: isPollMsg && isNewsletter ? 'text' : undefined
2237
- },
2238
- content: undefined
2239
- });
2240
- }
2241
- else if (isEventMsg) {
2242
- additionalNodes.push({
2243
- tag: 'meta',
2244
- attrs: {
2245
- event_type: 'creation'
2246
- },
2247
- content: undefined
2248
- });
2249
- }
2250
- else if (isAiMsg) {
2251
- if (!(isPnUser(jid) || isLidUser(jid))) {
2252
- throw new Boom('AI icon on message are only allowed in private chat', { statusCode: 400 });
2253
- }
2254
- if ('messageContextInfo' in fullMsg.message && !!fullMsg.message.messageContextInfo) {
2255
- fullMsg.message.messageContextInfo.supportPayload = BIZ_BOT_SUPPORT_PAYLOAD;
2256
- }
2257
- additionalNodes.push({
2258
- tag: 'bot',
2259
- attrs: {
2260
- biz_bot: '1'
2261
- },
2262
- content: undefined
2263
- });
2264
- delete content.ai;
2265
- }
2266
-
2267
- await relayMessage(jid, fullMsg.message, {
2268
- messageId: fullMsg.key.id,
2269
- useCachedGroupMetadata: options.useCachedGroupMetadata,
2270
- addBizAttributes: isNeedBizAttrs,
2271
- statusJidList: options.statusJidList,
2272
- statusPrivacy: options.statusPrivacy,
2273
- additionalAttributes,
2274
- additionalNodes
2275
- });
2276
-
2277
- if (config.emitOwnEvents) {
2278
- process.nextTick(async () => {
2279
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2280
- });
2281
- }
2282
-
2283
- return fullMsg;
2284
- }
2285
- }
2286
- };
2287
- /**
2288
- * Sends a GenAI-style copy-to-clipboard button.
2289
- * Renders a dark circular copy icon inline with text, inside a forwarded rich response.
2290
- */
2291
- socket.sendCopyButton = async (jid, content = {}, options = {}) => {
2292
- if (!jid) throw new Boom('sendCopyButton requires a target JID', { statusCode: 400 });
2293
- const wrapped = prepareCopyToClipboardMessage(content);
2294
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2295
- logger,
2296
- userJid: authState.creds.me?.id,
2297
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2298
- ...options,
2299
- });
2300
- await relayRichMessage(jid, fullMsg, options);
2301
- if (config.emitOwnEvents) {
2302
- process.nextTick(async () => {
2303
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2304
- });
2305
- }
2306
- return fullMsg;
2307
- };
2308
-
2309
- /**
2310
- * Sends plain text inside a forwarded GenAI rich response envelope.
2311
- */
2312
- socket.sendRichText = async (jid, content = {}, options = {}) => {
2313
- if (!jid) throw new Boom('sendRichText requires a target JID', { statusCode: 400 });
2314
- const wrapped = content.copyText ? prepareRichQuoteMessage(content) : prepareRichTextMessage(content);
2315
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2316
- logger,
2317
- userJid: authState.creds.me?.id,
2318
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2319
- ...options,
2320
- });
2321
- await relayRichMessage(jid, fullMsg, options);
2322
- if (config.emitOwnEvents) {
2323
- process.nextTick(async () => {
2324
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2325
- });
2326
- }
2327
- return fullMsg;
2328
- };
2329
- /** Sends ordinary Markdown/text with a GenAI COPY_TO_CLIPBOARD action; no quote syntax is required. */
2330
- socket.sendRichTextCopy = async (jid, content = {}, options = {}) => {
2331
- if (!jid) throw new Boom('sendRichTextCopy requires a target JID', { statusCode: 400 });
2332
- if (!content.copyText) throw new Boom('sendRichTextCopy requires copyText content', { statusCode: 400 });
2333
- const wrapped = prepareRichQuoteMessage(content);
2334
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2335
- await relayRichMessage(jid, fullMsg, options);
2336
- return fullMsg;
2337
- };
2338
- /** Sends Markdown text containing blockquotes in a forwarded GenAI rich response. */
2339
- socket.sendMarkdownQuote = async (jid, content = {}, options = {}) => {
2340
- if (!jid) throw new Boom('sendMarkdownQuote requires a target JID', { statusCode: 400 });
2341
- const wrapped = prepareRichQuoteMessage(content);
2342
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2343
- await relayRichMessage(jid, fullMsg, options);
2344
- return fullMsg;
2345
- };
2346
- /** Sends Markdown blockquotes followed by a GenAI COPY_TO_CLIPBOARD action. */
2347
- socket.sendQuoteCopy = async (jid, content = {}, options = {}) => {
2348
- if (!jid) throw new Boom('sendQuoteCopy requires a target JID', { statusCode: 400 });
2349
- if (!content.copyText) throw new Boom('sendQuoteCopy requires copyText content', { statusCode: 400 });
2350
- const wrapped = prepareRichQuoteMessage(content);
2351
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2352
- await relayRichMessage(jid, fullMsg, options);
2353
- return fullMsg;
2354
- };
2355
- /**
2356
- * Sends an image inside a forwarded GenAI rich response envelope.
2357
- */
2358
- socket.sendRichImage = async (jid, content = {}, options = {}) => {
2359
- if (!jid) throw new Boom('sendRichImage requires a target JID', { statusCode: 400 });
2360
- const wrapped = prepareRichImageMessage(content);
2361
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2362
- logger,
2363
- userJid: authState.creds.me?.id,
2364
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2365
- ...options,
2366
- });
2367
- await relayRichMessage(jid, fullMsg, options);
2368
- if (config.emitOwnEvents) {
2369
- process.nextTick(async () => {
2370
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2371
- });
2372
- }
2373
- return fullMsg;
2374
- };
2375
- /**
2376
- * Sends inline hyperlinks inside a forwarded GenAI rich response envelope.
2377
- */
2378
- socket.sendRichLink = async (jid, content = {}, options = {}) => {
2379
- if (!jid) throw new Boom('sendRichLink requires a target JID', { statusCode: 400 });
2380
- const wrapped = prepareRichLinkMessage(content);
2381
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2382
- logger,
2383
- userJid: authState.creds.me?.id,
2384
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2385
- ...options,
2386
- });
2387
- await relayRichMessage(jid, fullMsg, options);
2388
- if (config.emitOwnEvents) {
2389
- process.nextTick(async () => {
2390
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2391
- });
2392
- }
2393
- return fullMsg;
2394
- };
2395
- const sendSocialProfile = async (methodName, jid, content, options, prepare) => {
2396
- if (!jid) throw new Boom(`${methodName} requires a target JID`, { statusCode: 400 });
2397
- const wrapped = prepare(content);
2398
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2399
- logger,
2400
- userJid: authState.creds.me?.id,
2401
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2402
- ...options
2403
- });
2404
- await relayMessage(jid, fullMsg.message, {
2405
- messageId: fullMsg.key.id,
2406
- useCachedGroupMetadata: options.useCachedGroupMetadata,
2407
- statusJidList: options.statusJidList
2408
- });
2409
- if (config.emitOwnEvents) {
2410
- process.nextTick(async () => {
2411
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2412
- });
2413
- }
2414
- return fullMsg;
2415
- };
2416
- socket.sendSocialProfile = async (jid, content = {}, options = {}) => sendSocialProfile('sendSocialProfile', jid, content, options, prepareSocialProfileMessage);
2417
- socket.sendInstagramProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2418
- 'sendInstagramProfile',
2419
- jid,
2420
- { ...content, platform: 'instagram', entityType: content.entityType || 'IG_PROFILE', entityUrl: content.entityUrl || `https://www.instagram.com/${content.username || ''}` },
2421
- options,
2422
- prepareInstagramProfileMessage
2423
- );
2424
- socket.sendFacebookProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2425
- 'sendFacebookProfile', jid,
2426
- { ...content, platform: 'facebook', entityType: content.entityType || 'FB_PROFILE', entityUrl: content.entityUrl || `https://www.facebook.com/${content.username || ''}` },
2427
- options, prepareSocialProfileMessage
2428
- );
2429
- socket.sendTikTokProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2430
- 'sendTikTokProfile', jid,
2431
- { ...content, platform: 'tiktok', entityType: content.entityType || 'TIKTOK_PROFILE', entityUrl: content.entityUrl || `https://www.tiktok.com/@${content.username || ''}` },
2432
- options, prepareSocialProfileMessage
2433
- );
2434
- socket.sendYouTubeProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2435
- 'sendYouTubeProfile', jid,
2436
- { ...content, platform: 'youtube', entityType: content.entityType || 'YOUTUBE_PROFILE', entityUrl: content.entityUrl || `https://www.youtube.com/@${content.username || ''}` },
2437
- options, prepareSocialProfileMessage
2438
- );
2439
- socket.sendXProfile = async (jid, content = {}, options = {}) => sendSocialProfile(
2440
- 'sendXProfile', jid,
2441
- { ...content, platform: 'x', entityType: content.entityType || 'X_PROFILE', entityUrl: content.entityUrl || `https://x.com/${content.username || ''}` },
2442
- options, prepareSocialProfileMessage
2443
- );
2444
- socket.sendUnifiedResponse = async (jid, content = {}, options = {}) => {
2445
- if (!jid) throw new Boom('sendUnifiedResponse requires a target JID', { statusCode: 400 });
2446
- const wrapped = prepareUnifiedResponseMessage(content);
2447
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2448
- logger,
2449
- userJid: authState.creds.me?.id,
2450
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2451
- ...options
2452
- });
2453
- await relayMessage(jid, fullMsg.message, {
2454
- messageId: fullMsg.key.id,
2455
- useCachedGroupMetadata: options.useCachedGroupMetadata,
2456
- statusJidList: options.statusJidList
2457
- });
2458
- if (config.emitOwnEvents) {
2459
- process.nextTick(async () => {
2460
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2461
- });
2462
- }
2463
- return fullMsg;
2464
- };
2465
- /** Sends a protocol-backed AIRich map with optional numbered annotations. */
2466
- socket.sendRichMap = async (jid, content = {}, options = {}) => {
2467
- if (!jid) throw new Boom('sendRichMap requires a target JID', { statusCode: 400 });
2468
- const wrapped = prepareRichMapMessage(content);
2469
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2470
- logger,
2471
- userJid: authState.creds.me?.id,
2472
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2473
- ...options
2474
- });
2475
- await relayRichMessage(jid, fullMsg, options);
2476
- return fullMsg;
2477
- };
2478
- /** Sends BotSuggestedPromptMetadata with a rich-response text fallback. */
2479
- socket.sendBotPromptSuggestions = async (jid, content = {}, options = {}) => {
2480
- if (!jid) throw new Boom('sendBotPromptSuggestions requires a target JID', { statusCode: 400 });
2481
- const wrapped = prepareBotPromptSuggestionsMessage(content);
2482
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2483
- logger,
2484
- userJid: authState.creds.me?.id,
2485
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2486
- ...options
2487
- });
2488
- await relayRichMessage(jid, fullMsg, options);
2489
- return fullMsg;
2490
- };
2491
- /** Sends BotSourcesMetadata for citation-aware bot responses. */
2492
- socket.sendBotSources = async (jid, content = {}, options = {}) => {
2493
- if (!jid) throw new Boom('sendBotSources requires a target JID', { statusCode: 400 });
2494
- const wrapped = prepareBotSourcesMessage(content);
2495
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2496
- logger,
2497
- userJid: authState.creds.me?.id,
2498
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2499
- ...options
2500
- });
2501
- await relayRichMessage(jid, fullMsg, options);
2502
- return fullMsg;
2503
- };
2504
- /** Sends an experimental AIRich dynamic image/GIF submessage. */
2505
- socket.sendRichDynamicMedia = async (jid, content = {}, options = {}) => {
2506
- if (!jid) throw new Boom('sendRichDynamicMedia requires a target JID', { statusCode: 400 });
2507
- const wrapped = prepareRichDynamicMediaMessage(content);
2508
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2509
- logger,
2510
- userJid: authState.creds.me?.id,
2511
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2512
- ...options
2513
- });
2514
- await relayRichMessage(jid, fullMsg, options);
2515
- return fullMsg;
2516
- };
2517
- /** Sends BotPttPromptMetadata containing a caller-provided transcript. */
2518
- socket.sendBotPttTranscript = async (jid, content = {}, options = {}) => {
2519
- if (!jid) throw new Boom('sendBotPttTranscript requires a target JID', { statusCode: 400 });
2520
- const wrapped = prepareBotPttTranscriptMessage(content);
2521
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2522
- logger,
2523
- userJid: authState.creds.me?.id,
2524
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2525
- ...options
2526
- });
2527
- await relayRichMessage(jid, fullMsg, options);
2528
- return fullMsg;
2529
- };
2530
- socket.richMenu = async (jid, content = {}, options = {}) => {
2531
- if (!jid) throw new Boom('richMenu requires a target JID', { statusCode: 400 });
2532
- const wrapped = prepareRichMenuMessage(content);
2533
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2534
- logger,
2535
- userJid: authState.creds.me?.id,
2536
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
2537
- ...options,
2538
- });
2539
- await relayRichMessage(jid, fullMsg, options);
2540
- if (config.emitOwnEvents) {
2541
- process.nextTick(async () => {
2542
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2543
- });
2544
- }
2545
- return fullMsg;
2546
- };
2547
- /**
2548
- * Sends the A2UI interactive card/menu format used by WhatsApp's large
2549
- * command-card presentation. This is intentionally separate from richMenu
2550
- * because it is an interactiveMessage, not an AIRich unifiedResponse.
2551
- */
2552
- socket.sendA2UICommandMenu = async (jid, content = {}, options = {}) => {
2553
- if (!jid) throw new Boom('sendA2UICommandMenu requires a target JID', { statusCode: 400 });
2554
- const { image, ...menuContent } = content || {};
2555
- let imageMessage;
2556
- if (image) {
2557
- const prepared = await prepareWAMessageMedia({ image }, { upload: waUploadToServer });
2558
- imageMessage = prepared.imageMessage;
2559
- }
2560
- const wrapped = prepareA2UICommandMenu({ ...menuContent, imageMessage });
2561
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2562
- logger,
2563
- userJid: authState.creds.me?.id,
2564
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2565
- ...options,
2566
- });
2567
- await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
2568
- if (config.emitOwnEvents) {
2569
- process.nextTick(async () => {
2570
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2571
- });
2572
- }
2573
- return fullMsg;
2574
- };
2575
- /** Send arbitrary A2UI/interactive payloads; sendA2UICommandMenu is a preset wrapper. */
2576
- socket.sendA2UIMessage = async (jid, content = {}, options = {}) => {
2577
- if (!jid) throw new Boom('sendA2UIMessage requires a target JID', { statusCode: 400 });
2578
- const { image, ...payload } = content || {};
2579
- let imageMessage;
2580
- if (image) {
2581
- const prepared = await prepareWAMessageMedia({ image }, { upload: waUploadToServer });
2582
- imageMessage = prepared.imageMessage;
2583
- }
2584
- const wrapped = prepareA2UIMessage({ ...payload, imageMessage });
2585
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2586
- logger,
2587
- userJid: authState.creds.me?.id,
2588
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2589
- ...options,
2590
- });
2591
- await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
2592
- if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
2593
- return fullMsg;
2594
- };
2595
-
2596
- /** Sends the manually serialized AIRich command card shown in the screenshot. */
2597
- socket.sendAIRichCommandMenu = async (jid, content = {}, options = {}) => {
2598
- if (!jid) throw new Boom('sendAIRichCommandMenu requires a target JID', { statusCode: 400 });
2599
- const wrapped = prepareAIRichCommandMenu(content);
2600
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2601
- logger,
2602
- userJid: authState.creds.me?.id,
2603
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2604
- ...options,
2605
- });
2606
- await relayRichMessage(jid, fullMsg, options);
2607
- if (config.emitOwnEvents) {
2608
- process.nextTick(async () => {
2609
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2610
- });
2611
- }
2612
- return fullMsg;
2613
- };
2614
- /** Send a provider-neutral AIRich social/entity result card. */
2615
- socket.sendSocialEntity = async (jid, content = {}, options = {}) => {
2616
- if (!jid) throw new Boom('sendSocialEntity requires a target JID', { statusCode: 400 });
2617
- const wrapped = prepareSocialEntityMessage(content);
2618
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2619
- logger,
2620
- userJid: authState.creds.me?.id,
2621
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2622
- ...options,
2623
- });
2624
- await relayRichMessage(jid, fullMsg, options);
2625
- if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
2626
- return fullMsg;
2627
- };
2628
-
2629
- /** Send the primary Instagram profile result using the universal social/entity API. */
2630
- socket.sendInstagramProfile = async (jid, content = {}, options = {}) => {
2631
- if (!jid) throw new Boom('sendInstagramProfile requires a target JID', { statusCode: 400 });
2632
- const wrapped = prepareInstagramProfileMessage(content);
2633
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
2634
- logger,
2635
- userJid: authState.creds.me?.id,
2636
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2637
- ...options,
2638
- });
2639
- await relayRichMessage(jid, fullMsg, options);
2640
- if (config.emitOwnEvents) process.nextTick(async () => { await messageMutex.mutex(() => upsertMessage(fullMsg, 'append')); });
2641
- return fullMsg;
2642
- };
2643
-
2644
- /** Sends a rich response with experimental BotInfrastructureDiagnostics metadata. */
2645
- socket.sendBotDiagnostics = async (jid, content = {}, options = {}) => {
2646
- if (!jid) throw new Boom('sendBotDiagnostics requires a target JID', { statusCode: 400 });
2647
- const { text = 'Bot diagnostics test', botBackend = 0, toolsUsed = [], isThinking = false, botJid = '867051314767696@bot' } = content;
2648
- const wrapped = {
2649
- messageContextInfo: { botMetadata: { botInfrastructureDiagnostics: { botBackend, toolsUsed, isThinking } } },
2650
- botForwardedMessage: { message: { richResponseMessage: { messageType: 1, submessages: [{ messageType: 2, messageText: text }], contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 } } } }
2651
- };
2652
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2653
- await relayRichMessage(jid, fullMsg, options);
2654
- return fullMsg;
2655
- };
2656
- /** Sends a rich response with experimental BotCommandMetadata. */
2657
- socket.sendBotCommand = async (jid, content = {}, options = {}) => {
2658
- if (!jid) throw new Boom('sendBotCommand requires a target JID', { statusCode: 400 });
2659
- const { text = 'Bot command test', commandName = '', commandDescription = '', commandPrompt = '', botJid = '867051314767696@bot' } = content;
2660
- const wrapped = buildBotRichResponse({ text, botJid, botMetadata: { commandMetadata: { commandName, commandDescription, commandPrompt } } });
2661
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2662
- await relayRichMessage(jid, fullMsg, options);
2663
- return fullMsg;
2664
- };
2665
- /** Sends a planning/execution-plan rich response with WAProto capabilities. */
2666
- socket.sendBotPlanning = async (jid, content = {}, options = {}) => {
2667
- if (!jid) throw new Boom('sendBotPlanning requires a target JID', { statusCode: 400 });
2668
- const { text = 'Execution plan', steps = [], queryPlan = true, botJid = '867051314767696@bot' } = content;
2669
- const submessages = [
2670
- { messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT, messageText: text },
2671
- ...steps.map(step => ({
2672
- messageType: proto.AIRichResponseSubMessageType.AI_RICH_RESPONSE_TEXT,
2673
- messageText: typeof step === 'string' ? step : `${step.title || step.name || 'Step'}${step.body ? `: ${step.body}` : ''}`
2674
- }))
2675
- ];
2676
- const wrapped = buildBotRichResponse({
2677
- botJid,
2678
- submessages,
2679
- capabilities: [
2680
- BotCapabilityType.AGENTIC_PLANNING,
2681
- ...(queryPlan ? [BotCapabilityType.QUERY_PLAN] : [])
2682
- ]
2683
- });
2684
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2685
- await relayRichMessage(jid, fullMsg, options);
2686
- return fullMsg;
2687
- };
2688
- /** Sends a rich response with experimental BotResolvedToolCallMetadata. */
2689
- socket.sendBotToolResult = async (jid, content = {}, options = {}) => {
2690
- if (!jid) throw new Boom('sendBotToolResult requires a target JID', { statusCode: 400 });
2691
- const { text = 'Bot tool result test', toolCallId = `tool-${Date.now()}`, resolutionData, resolutionDataSerialized, botJid = '867051314767696@bot' } = content;
2692
- const wrapped = buildBotRichResponse({
2693
- text,
2694
- botJid,
2695
- capabilities: [BotCapabilityType.AGENTIC_PLANNING, BotCapabilityType.QUERY_PLAN],
2696
- botMetadata: {
2697
- resolvedToolCallMetadata: {
2698
- toolCallId,
2699
- resolutionDataSerialized: resolutionDataSerialized ?? JSON.stringify(resolutionData ?? {})
2700
- }
2701
- }
2702
- });
2703
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2704
- await relayRichMessage(jid, fullMsg, options);
2705
- return fullMsg;
2706
- };
2707
- /**
2708
- * Sends a real BotProgressIndicatorMetadata planning envelope. The plan is
2709
- * application-controlled; this advertises the public schema capability but
2710
- * does not claim to invoke Meta's private planning backend.
2711
- */
2712
- socket.sendBotPlan = async (jid, content = {}, options = {}) => {
2713
- if (!jid) throw new Boom('sendBotPlan requires a target JID', { statusCode: 400 });
2714
- const {
2715
- text = 'Execution plan',
2716
- title = 'Execution plan',
2717
- steps = [],
2718
- estimatedCompletionTime,
2719
- botJid = '867051314767696@bot'
2720
- } = content;
2721
- if (!Array.isArray(steps) || steps.length === 0) {
2722
- throw new Boom('sendBotPlan requires at least one step', { statusCode: 400 });
2723
- }
2724
- const planningStatus = proto.BotProgressIndicatorMetadata.BotPlanningStepMetadata.PlanningStepStatus;
2725
- const normalizedSteps = steps.map((step, index) => ({
2726
- statusTitle: String(step.title || step.name || `Step ${index + 1}`),
2727
- statusBody: String(step.body || step.description || ''),
2728
- status: step.status === 'executing' ? planningStatus.EXECUTING
2729
- : step.status === 'finished' || step.status === 'completed' ? planningStatus.FINISHED
2730
- : planningStatus.PLANNED,
2731
- isReasoning: step.isReasoning === true,
2732
- isEnhancedSearch: step.isEnhancedSearch === true,
2733
- ...(Array.isArray(step.sections) ? { sections: step.sections } : {})
2734
- }));
2735
- const wrapped = {
2736
- messageContextInfo: { botMetadata: {
2737
- capabilityMetadata: {
2738
- capabilities: [
2739
- proto.BotCapabilityMetadata.BotCapabilityType.AGENTIC_PLANNING,
2740
- proto.BotCapabilityMetadata.BotCapabilityType.QUERY_PLAN
2741
- ]
2742
- },
2743
- progressIndicatorMetadata: {
2744
- progressDescription: title,
2745
- stepsMetadata: normalizedSteps,
2746
- ...(estimatedCompletionTime ? { estimatedCompletionTime } : {})
2747
- }
2748
- } },
2749
- botForwardedMessage: { message: { richResponseMessage: {
2750
- messageType: 1,
2751
- submessages: [{ messageType: 2, messageText: text }],
2752
- contextInfo: { isForwarded: true, forwardingScore: 1, forwardedAiBotMessageInfo: { botJid }, forwardOrigin: 4 }
2753
- } } }
2754
- };
2755
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, { logger, userJid: authState.creds.me?.id, messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id), ...options });
2756
- await relayMessage(jid, fullMsg.message, { messageId: fullMsg.key.id, useCachedGroupMetadata: options.useCachedGroupMetadata, statusJidList: options.statusJidList });
2757
- return fullMsg;
2758
- };
2759
- socket.sendStatus = async (content, options = {}) => {
2760
- const statusJidList = await resolveStatusRecipients(options.statusJidList || content?.statusJidList);
2761
- return socket.sendMessage(STATUS_JID, {
2762
- ...content,
2763
- status: true
2764
- }, {
2765
- ...options,
2766
- broadcast: true,
2767
- statusJidList
2768
- });
2769
- };
2770
- socket.sendRichButtonGrid = async (jid, grid, options = {}) => {
2771
- const { text, footer, cards = [] } = grid || {};
2772
- if (!Array.isArray(cards) || cards.length === 0) {
2773
- throw new Boom('sendRichButtonGrid expects at least one card', { statusCode: 400 });
2774
- }
2775
- const normalizedCards = cards.map((card, index) => {
2776
- const buttons = card.buttons || card.nativeFlow || [];
2777
- if (!Array.isArray(buttons) || buttons.length === 0) {
2778
- throw new Boom(`sendRichButtonGrid card ${index + 1} needs buttons`, { statusCode: 400 });
2779
- }
2780
- return {
2781
- ...card,
2782
- nativeFlow: buttons,
2783
- caption: card.caption || card.title || `Menu ${index + 1}`
2784
- };
2785
- });
2786
- return socket.sendMessage(jid, {
2787
- ...(text ? { text } : {}),
2788
- ...(footer ? { footer } : {}),
2789
- cards: normalizedCards
2790
- }, options);
2791
- };
2792
- /**
2793
- * Compatibility entry point for the former Gen4/grid menu.
2794
- * This is additive: sendRichButtonGrid remains unchanged for existing callers.
2795
- */
2796
- socket.HoldOn = async (jid, grid, options = {}) => socket.sendRichButtonGrid(jid, grid, options);
2797
- socket.sendWhatsAppFlow = async (jid, flow, options = {}) => {
2798
- const { text, footer, image, caption, ...flowOptions } = flow || {};
2799
- const button = makeWhatsAppFlowButton(flowOptions);
2800
- return socket.sendMessage(jid, {
2801
- ...(image ? { image, caption: caption || text || flowOptions.cta } : { text: text || flowOptions.cta }),
2802
- ...(footer ? { footer } : {}),
2803
- nativeFlow: [button]
2804
- }, options);
2805
- };
2806
- /**
2807
- * Send a rich URL CTA intended to open a hosted WebView/Mini App.
2808
- * `useWebview` is serialized by the existing native-flow normalizer.
2809
- * `toast` is preserved as immediate button acknowledgement metadata.
2810
- */
2811
- socket.sendRichWebview = async (jid, content = {}, options = {}) => {
2812
- const { text = '', title, footer, image, caption, buttonText = 'Open', url, useWebview = true, toast, ...rest } = content;
2813
- if (!url || typeof url !== 'string') {
2814
- throw new Boom('sendRichWebview requires a URL', { statusCode: 400 });
2815
- }
2816
- const button = { text: buttonText, url, useWebview, ...(toast ? { toast } : {}), ...rest };
2817
- return socket.sendMessage(jid, {
2818
- ...(image ? { image, caption: caption || text || title || buttonText } : { text: text || title || buttonText }),
2819
- ...(footer ? { footer } : {}),
2820
- nativeFlow: [button],
2821
- ...(toast ? { toast } : {})
2822
- }, options);
2823
- };
2824
- socket.sendInteractiveTable = async (jid, table, options = {}) => {
2825
- const { title = '', headers = [], rows = [], image, buttons = [], footer } = table || {};
2826
- if (!Array.isArray(headers) || !Array.isArray(rows) || !Array.isArray(buttons)) {
2827
- throw new Boom('sendInteractiveTable expects headers, rows, and buttons arrays', { statusCode: 400 });
2828
- }
2829
- const lines = [];
2830
- if (title) lines.push(String(title));
2831
- if (headers.length) lines.push(`| ${headers.map(String).join(' | ')} |`);
2832
- if (headers.length) lines.push(`| ${headers.map(() => '---').join(' | ')} |`);
2833
- for (const row of rows) {
2834
- lines.push(`| ${(Array.isArray(row) ? row : [row]).map(value => String(value ?? '')).join(' | ')} |`);
2835
- }
2836
- const content = {
2837
- ...(image ? { caption: lines.join('\n'), image } : { text: lines.join('\n') }),
2838
- buttons: buttons.map((button, index) => ({
2839
- id: button.id || `table_${index + 1}`,
2840
- text: button.text || button.buttonText || `Option ${index + 1}`
2841
- })),
2842
- ...(footer ? { footer } : {})
2843
- };
2844
- return socket.sendMessage(jid, content, options);
2845
- };
2846
- // ====================================
2847
- // VIEW-ONCE AUTO-DECRYPT & AUTO-DELETE
2848
- // ====================================
2849
-
2850
- /**
2851
- * Auto-decrypt view-once messages (autoVV)
2852
- * Downloads the media content from a view-once message and re-emits it
2853
- * as a regular message with decryptedMedia attached.
2854
- */
2855
- socket.autoVV = async (message, options = {}) => {
2856
- if (!isViewOnceMessage(message)) {
2857
- logger.debug({ key: message?.key }, 'autoVV: message is not a view-once message');
2858
- return null;
2859
- }
2860
-
2861
- const info = parseViewOnceInfo(message);
2862
- logger.info({ key: message?.key, ...info }, 'autoVV: decrypting view-once message');
2863
-
2864
- try {
2865
- // Download and decrypt the media
2866
- const mediaBuffer = await downloadViewOnceMedia(message, {
2867
- logger,
2868
- ...options,
2869
- });
2870
-
2871
- // Create a regular message from the decrypted content
2872
- const regularMessage = createRegularMessageFromViewOnce(message, mediaBuffer);
2873
-
2874
- if (regularMessage) {
2875
- // Emit as a new message with decrypted content
2876
- ev.emit('messages.upsert', {
2877
- messages: [regularMessage],
2878
- type: 'append',
2879
- });
2880
-
2881
- logger.info({
2882
- key: message?.key,
2883
- mediaType: info.mediaType,
2884
- bufferSize: mediaBuffer.length,
2885
- }, 'autoVV: successfully decrypted view-once message');
2886
- }
2887
-
2888
- return regularMessage;
2889
- } catch (error) {
2890
- logger.error({
2891
- key: message?.key,
2892
- error: error.message,
2893
- }, 'autoVV: failed to decrypt view-once message');
2894
- throw error;
2895
- }
2896
- };
2897
-
2898
- /**
2899
- * Auto-delete view-once messages (antiVV)
2900
- * Detects incoming view-once messages and deletes them immediately.
2901
- * This prevents the sender from knowing the message was viewed.
2902
- */
2903
- socket.antiVV = async (message, options = {}) => {
2904
- if (!isViewOnceMessage(message)) {
2905
- logger.debug({ key: message?.key }, 'antiVV: message is not a view-once message');
2906
- return false;
2907
- }
2908
-
2909
- const info = parseViewOnceInfo(message);
2910
- logger.info({ key: message?.key, ...info }, 'antiVV: deleting view-once message');
2911
-
2912
- try {
2913
- // Delete the message by sending a revoke receipt
2914
- const jid = message.key.remoteJid;
2915
- const participant = message.key.participant || jid;
2916
- const messageId = message.key.id;
2917
-
2918
- // Send a revoke receipt to delete the message
2919
- await sendReceipt(jid, participant, [messageId], 'sender');
2920
-
2921
- // Also emit a message update to remove it from local store
2922
- ev.emit('messages.update', [
2923
- {
2924
- key: message.key,
2925
- update: {
2926
- messageStubType: proto.WebMessageInfo.StubType.REVOKE,
2927
- messageStubParameters: ['auto-vv-delete'],
2928
- },
2929
- },
2930
- ]);
2931
-
2932
- logger.info({
2933
- key: message?.key,
2934
- mediaType: info.mediaType,
2935
- }, 'antiVV: successfully deleted view-once message');
2936
-
2937
- return true;
2938
- } catch (error) {
2939
- logger.error({
2940
- key: message?.key,
2941
- error: error.message,
2942
- }, 'antiVV: failed to delete view-once message');
2943
- throw error;
2944
- }
2945
- };
2946
-
2947
- /**
2948
- * Check if a message is a view-once message
2949
- */
2950
- socket.isViewOnce = (message) => isViewOnceMessage(message);
2951
-
2952
- /**
2953
- * Get view-once message info (media type, mime type, etc.)
2954
- */
2955
- socket.getViewOnceInfo = (message) => parseViewOnceInfo(message);
2956
-
2957
-
2958
- /**
2959
- * Sends a full-width vertical AIRich album. Unlike the legacy
2960
- * albumMessage collection or compact GRID_IMAGE layout, this is one
2961
- * forwarded unified-response message with one large media item per row.
2962
- */
2963
- socket.sendAlbumMessage = async (jid, medias = [], options = {}) => {
2964
- if (!jid) throw new Boom('sendAlbumMessage requires a target JID', { statusCode: 400 });
2965
- if (!Array.isArray(medias) || medias.length < 2) {
2966
- throw new Boom('sendAlbumMessage requires at least two media items', { statusCode: 400 });
2967
- }
2968
- const albumItems = medias.map((media) => {
2969
- const raw = media?.type && media?.data ? media.data : (media?.image ?? media);
2970
- if (media?.video || media?.type === 'video') {
2971
- const video = media?.video || raw;
2972
- const sourceUrl = typeof video === 'string' ? video : (video?.url || video?.videoUrl || '');
2973
- if (!sourceUrl) throw new Boom('Each video album item requires a video URL', { statusCode: 400 });
2974
- return { type: 'video', video: { ...video, url: sourceUrl } };
2975
- }
2976
- return {
2977
- type: 'image',
2978
- image: raw
2979
- };
2980
- });
2981
- const wrapped = prepareVerticalAlbumMessage({
2982
- items: albumItems,
2983
- verificationMetadata: options.verificationMetadata
2984
- });
2985
- const fullMsg = generateWAMessageFromContent(jid, wrapped, {
2986
- logger,
2987
- userJid: authState.creds.me?.id,
2988
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
2989
- ...options
2990
- });
2991
- await relayRichMessage(jid, fullMsg, options);
2992
- if (config.emitOwnEvents) {
2993
- process.nextTick(async () => {
2994
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
2995
- });
2996
- }
2997
- return fullMsg;
2998
- };
2999
-
3000
- /**
3001
- * Sends a unified-response video grid. This uses GenAIVideoPrimitive items
3002
- * inside GenAIGridLayoutViewModel; it is not the image-only GRID_IMAGE type.
3003
- */
3004
- socket.sendVideoGridMessage = async (jid, videos = [], options = {}) => {
3005
- if (!jid) throw new Boom('sendVideoGridMessage requires a target JID', { statusCode: 400 });
3006
- if (!Array.isArray(videos) || videos.length < 2) {
3007
- throw new Boom('sendVideoGridMessage requires at least two videos', { statusCode: 400 });
3008
- }
3009
- const wrapped = prepareVideoGridMessage({
3010
- videos,
3011
- verificationMetadata: options.verificationMetadata
3012
- });
3013
- const fullMsg = generateWAMessageFromContent(jid, wrapped, {
3014
- logger,
3015
- userJid: authState.creds.me?.id,
3016
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id || jid),
3017
- ...options
3018
- });
3019
- await relayRichMessage(jid, fullMsg, options);
3020
- if (config.emitOwnEvents) {
3021
- process.nextTick(async () => {
3022
- await messageMutex.mutex(() => upsertMessage(fullMsg, 'append'));
3023
- });
3024
- }
3025
- return fullMsg;
3026
- };
3027
-
3028
-
3029
- /**
3030
- * Sends an HTML message — renders raw HTML inside the chat bubble.
3031
- * Uses FOAHtmlPrimitiveDemoDONOTUSE for full HTML/CSS/JS rendering.
3032
- *
3033
- * @param {string} jid - Target JID
3034
- * @param {Object} content - { html: string, trustedSources?: string[] }
3035
- * @param {Object} options - Additional options
3036
- * @returns {Object} Sent message info
3037
- *
3038
- * @example
3039
- * // Simple HTML
3040
- * await sock.sendHtmlMessage(jid, {
3041
- * html: '<h1>Hello!</h1><p style="color: blue">World</p>'
3042
- * })
3043
- */
3044
- socket.sendHtmlMessage = async (jid, content = {}, options = {}) => {
3045
- if (!jid) throw new Boom('sendHtmlMessage requires a target JID', { statusCode: 400 });
3046
- const { html, trustedSources } = content;
3047
- if (!html) throw new Boom('sendHtmlMessage requires html content', { statusCode: 400 });
3048
- const wrapped = prepareHtmlMessage({ html, trustedSources });
3049
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3050
- logger,
3051
- userJid: authState.creds.me?.id,
3052
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3053
- ...options
3054
- });
3055
- await relayRichMessage(jid, fullMsg, { ...options, forceRichEdit: true });
3056
- return fullMsg;
3057
- };
3058
-
3059
- /**
3060
- * Sends an interactive GenAI HTML screen with embedded tabs.
3061
- * This is distinct from sendHtmlMessage(): it uses the aeacdsnw HTML
3062
- * primitive and FOAIDNixelButtonSheets envelope used by interactive games.
3063
- *
3064
- * @param {string} jid - Target JID
3065
- * @param {Object} content - { html, title?, tabs?, trustedSources?, url? }
3066
- * @param {Object} options - Additional relay options
3067
- */
3068
- socket.sendRichHtmlMessage = async (jid, content = {}, options = {}) => {
3069
- if (!jid) throw new Boom('sendRichHtmlMessage requires a target JID', { statusCode: 400 });
3070
- if (!content.html && !(Array.isArray(content.tabs) && content.tabs.length)) {
3071
- throw new Boom('sendRichHtmlMessage requires html or tabs content', { statusCode: 400 });
3072
- }
3073
- const wrapped = prepareRichHtmlMessage(content);
3074
- const fullMsg = await generateWAMessageFromContent(jid, wrapped, {
3075
- logger,
3076
- userJid: authState.creds.me?.id,
3077
- messageId: options.messageId || generateMessageIDV2(authState.creds.me?.id),
3078
- ...options
3079
- });
3080
- await relayRichMessage(jid, fullMsg, options);
3081
- return fullMsg;
3082
- };
3083
-
3084
- /** Find a word or expression in the installed package source. */
3085
- socket.grepCode = (pattern, options = {}) => grepSource(pattern, options);
3086
-
3087
-
3088
- /**
3089
- * Sends a slot machine game — Fruit Bonanza!
3090
- * Renders a fully interactive canvas-based slot machine inside the chat bubble.
3091
- *
3092
- * @param {string} jid - Target JID
3093
- * @param {Object} [options] - Game options
3094
- * @param {string} [options.title='FRUIT BONANZA'] - Machine title
3095
- * @param {number} [options.startingCredits=500] - Starting credits
3096
- * @param {Object} [sendOptions] - Send options (quoted, etc.)
3097
- * @returns {Object} Sent message info
3098
- *
3099
- * @example
3100
- * // Default slot machine
3101
- * await sock.sendSlotMachine(jid)
3102
- *
3103
- * // Custom title and credits
3104
- * await sock.sendSlotMachine(jid, { title: 'MEGA SLOTS', startingCredits: 1000 })
3105
- */
3106
- socket.sendSlotMachine = async (jid, options = {}, sendOptions = {}) => {
3107
- if (!jid) throw new Boom('sendSlotMachine requires a target JID', { statusCode: 400 });
3108
- const html = generateSlotMachineHtml(options);
3109
- return socket.sendHtmlMessage(jid, { html }, sendOptions);
3110
- };
3111
-
3112
- /** Sends the attached interactive mini-app through the rich HTML envelope. */
3113
- socket.sendMiniApp = async (jid, options = {}, sendOptions = {}) => {
3114
- if (!jid) throw new Boom('sendMiniApp requires a target JID', { statusCode: 400 });
3115
- return socket.sendRichHtmlMessage(jid, {
3116
- html: generateMiniAppHtml(options),
3117
- title: options.title || 'mini-app',
3118
- url: 'https://pair.crysnova.link',
3119
- trustedSources: ['pair.crysnova.link']
3120
- }, sendOptions);
3121
- };
3122
-
3123
-
3124
- /**
3125
- * Mirrors a website inside the WhatsApp chat bubble.
3126
- * Fetches the site and renders it in a sandboxed iframe.
3127
- *
3128
- * @param {string} jid - Target JID
3129
- * @param {string} url - Website URL to mirror
3130
- * @param {Object} [options] - Preview options
3131
- * @param {boolean} [options.sandbox=true] - Sandbox restrictions
3132
- * @param {string} [options.height='600px'] - Preview height
3133
- * @param {boolean} [options.showUrl=true] - Show URL bar
3134
- * @param {Object} [sendOptions] - Send options
3135
- * @returns {Object} Sent message info
3136
- *
3137
- * @example
3138
- * await sock.sendWebsitePreview(jid, 'https://google.com')
3139
- * await sock.sendWebsitePreview(jid, 'https://example.com', { height: '400px' })
3140
- */
3141
- socket.sendWebsitePreview = async (jid, url, options = {}, sendOptions = {}) => {
3142
- if (!jid) throw new Boom('sendWebsitePreview requires a target JID', { statusCode: 400 });
3143
- if (!url) throw new Boom('sendWebsitePreview requires a URL', { statusCode: 400 });
3144
- const html = await generateWebsitePreviewHtml(url, options);
3145
- return socket.sendHtmlMessage(jid, { html }, sendOptions);
3146
- };
3147
-
3148
- /**
3149
- * Sends a link preview card for a URL.
3150
- * Lighter weight than sendWebsitePreview — just shows title, description, image.
3151
- *
3152
- * @param {string} jid - Target JID
3153
- * @param {string} url - URL to preview
3154
- * @param {Object} [options] - Card options
3155
- * @param {string} [options.title] - Override title
3156
- * @param {string} [options.description] - Override description
3157
- * @param {string} [options.image] - Override image URL
3158
- * @param {Object} [sendOptions] - Send options
3159
- * @returns {Object} Sent message info
3160
- *
3161
- * @example
3162
- * await sock.sendLinkPreview(jid, 'https://google.com')
3163
- * await sock.sendLinkPreview(jid, 'https://example.com', {
3164
- * title: 'My Website',
3165
- * description: 'Check out my cool site!',
3166
- * image: 'https://example.com/og.png'
3167
- * })
3168
- */
3169
- socket.sendLinkPreview = async (jid, url, options = {}, sendOptions = {}) => {
3170
- if (!jid) throw new Boom('sendLinkPreview requires a target JID', { statusCode: 400 });
3171
- if (!url) throw new Boom('sendLinkPreview requires a URL', { statusCode: 400 });
3172
- const html = generateLinkPreviewHtml(url, options);
3173
- return socket.sendHtmlMessage(jid, { html }, sendOptions);
3174
- };
3175
-
3176
- return socket;
3177
- };