@yui-bails/yui-bails 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (457) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1685 -2
  3. package/WAProto/GenerateStatics.sh +3 -0
  4. package/WAProto/WAProto.proto +5479 -0
  5. package/WAProto/fix-imports.js +85 -0
  6. package/WAProto/index.d.ts +14017 -0
  7. package/WAProto/index.js +97691 -0
  8. package/engine-requirements.js +10 -0
  9. package/lib/Defaults/index.d.ts +75 -0
  10. package/lib/Defaults/index.d.ts.map +1 -0
  11. package/lib/Defaults/index.js +139 -0
  12. package/lib/Defaults/index.js.map +1 -0
  13. package/lib/Signal/Group/ciphertext-message.d.ts +10 -0
  14. package/lib/Signal/Group/ciphertext-message.d.ts.map +1 -0
  15. package/lib/Signal/Group/ciphertext-message.js +12 -0
  16. package/lib/Signal/Group/ciphertext-message.js.map +1 -0
  17. package/lib/Signal/Group/group-session-builder.d.ts +15 -0
  18. package/lib/Signal/Group/group-session-builder.d.ts.map +1 -0
  19. package/lib/Signal/Group/group-session-builder.js +30 -0
  20. package/lib/Signal/Group/group-session-builder.js.map +1 -0
  21. package/lib/Signal/Group/group_cipher.d.ts +17 -0
  22. package/lib/Signal/Group/group_cipher.d.ts.map +1 -0
  23. package/lib/Signal/Group/group_cipher.js +82 -0
  24. package/lib/Signal/Group/group_cipher.js.map +1 -0
  25. package/lib/Signal/Group/index.d.ts +12 -0
  26. package/lib/Signal/Group/index.d.ts.map +1 -0
  27. package/lib/Signal/Group/index.js +12 -0
  28. package/lib/Signal/Group/index.js.map +1 -0
  29. package/lib/Signal/Group/keyhelper.d.ts +11 -0
  30. package/lib/Signal/Group/keyhelper.d.ts.map +1 -0
  31. package/lib/Signal/Group/keyhelper.js +18 -0
  32. package/lib/Signal/Group/keyhelper.js.map +1 -0
  33. package/lib/Signal/Group/sender-chain-key.d.ts +14 -0
  34. package/lib/Signal/Group/sender-chain-key.d.ts.map +1 -0
  35. package/lib/Signal/Group/sender-chain-key.js +26 -0
  36. package/lib/Signal/Group/sender-chain-key.js.map +1 -0
  37. package/lib/Signal/Group/sender-key-distribution-message.d.ts +17 -0
  38. package/lib/Signal/Group/sender-key-distribution-message.d.ts.map +1 -0
  39. package/lib/Signal/Group/sender-key-distribution-message.js +63 -0
  40. package/lib/Signal/Group/sender-key-distribution-message.js.map +1 -0
  41. package/lib/Signal/Group/sender-key-message.d.ts +19 -0
  42. package/lib/Signal/Group/sender-key-message.d.ts.map +1 -0
  43. package/lib/Signal/Group/sender-key-message.js +66 -0
  44. package/lib/Signal/Group/sender-key-message.js.map +1 -0
  45. package/lib/Signal/Group/sender-key-name.d.ts +18 -0
  46. package/lib/Signal/Group/sender-key-name.d.ts.map +1 -0
  47. package/lib/Signal/Group/sender-key-name.js +48 -0
  48. package/lib/Signal/Group/sender-key-name.js.map +1 -0
  49. package/lib/Signal/Group/sender-key-record.d.ts +31 -0
  50. package/lib/Signal/Group/sender-key-record.d.ts.map +1 -0
  51. package/lib/Signal/Group/sender-key-record.js +41 -0
  52. package/lib/Signal/Group/sender-key-record.js.map +1 -0
  53. package/lib/Signal/Group/sender-key-state.d.ts +39 -0
  54. package/lib/Signal/Group/sender-key-state.d.ts.map +1 -0
  55. package/lib/Signal/Group/sender-key-state.js +84 -0
  56. package/lib/Signal/Group/sender-key-state.js.map +1 -0
  57. package/lib/Signal/Group/sender-message-key.d.ts +12 -0
  58. package/lib/Signal/Group/sender-message-key.d.ts.map +1 -0
  59. package/lib/Signal/Group/sender-message-key.js +26 -0
  60. package/lib/Signal/Group/sender-message-key.js.map +1 -0
  61. package/lib/Signal/libsignal.d.ts +5 -0
  62. package/lib/Signal/libsignal.d.ts.map +1 -0
  63. package/lib/Signal/libsignal.js +431 -0
  64. package/lib/Signal/libsignal.js.map +1 -0
  65. package/lib/Signal/lid-mapping.d.ts +23 -0
  66. package/lib/Signal/lid-mapping.d.ts.map +1 -0
  67. package/lib/Signal/lid-mapping.js +277 -0
  68. package/lib/Signal/lid-mapping.js.map +1 -0
  69. package/lib/Socket/Client/index.d.ts +3 -0
  70. package/lib/Socket/Client/index.d.ts.map +1 -0
  71. package/lib/Socket/Client/index.js +3 -0
  72. package/lib/Socket/Client/index.js.map +1 -0
  73. package/lib/Socket/Client/types.d.ts +16 -0
  74. package/lib/Socket/Client/types.d.ts.map +1 -0
  75. package/lib/Socket/Client/types.js +11 -0
  76. package/lib/Socket/Client/types.js.map +1 -0
  77. package/lib/Socket/Client/websocket.d.ts +13 -0
  78. package/lib/Socket/Client/websocket.d.ts.map +1 -0
  79. package/lib/Socket/Client/websocket.js +54 -0
  80. package/lib/Socket/Client/websocket.js.map +1 -0
  81. package/lib/Socket/business.d.ts +217 -0
  82. package/lib/Socket/business.d.ts.map +1 -0
  83. package/lib/Socket/business.js +379 -0
  84. package/lib/Socket/business.js.map +1 -0
  85. package/lib/Socket/chats.d.ts +125 -0
  86. package/lib/Socket/chats.d.ts.map +1 -0
  87. package/lib/Socket/chats.js +1198 -0
  88. package/lib/Socket/chats.js.map +1 -0
  89. package/lib/Socket/communities.d.ts +273 -0
  90. package/lib/Socket/communities.d.ts.map +1 -0
  91. package/lib/Socket/communities.js +431 -0
  92. package/lib/Socket/communities.js.map +1 -0
  93. package/lib/Socket/groups.d.ts +161 -0
  94. package/lib/Socket/groups.d.ts.map +1 -0
  95. package/lib/Socket/groups.js +347 -0
  96. package/lib/Socket/groups.js.map +1 -0
  97. package/lib/Socket/index.d.ts +322 -0
  98. package/lib/Socket/index.d.ts.map +1 -0
  99. package/lib/Socket/index.js +105 -0
  100. package/lib/Socket/index.js.map +1 -0
  101. package/lib/Socket/messages-recv.d.ts +203 -0
  102. package/lib/Socket/messages-recv.d.ts.map +1 -0
  103. package/lib/Socket/messages-recv.js +1772 -0
  104. package/lib/Socket/messages-recv.js.map +1 -0
  105. package/lib/Socket/messages-send.d.ts +199 -0
  106. package/lib/Socket/messages-send.d.ts.map +1 -0
  107. package/lib/Socket/messages-send.js +1159 -0
  108. package/lib/Socket/messages-send.js.map +1 -0
  109. package/lib/Socket/mex.d.ts +3 -0
  110. package/lib/Socket/mex.d.ts.map +1 -0
  111. package/lib/Socket/mex.js +42 -0
  112. package/lib/Socket/mex.js.map +1 -0
  113. package/lib/Socket/newsletter.d.ts +170 -0
  114. package/lib/Socket/newsletter.d.ts.map +1 -0
  115. package/lib/Socket/newsletter.js +181 -0
  116. package/lib/Socket/newsletter.js.map +1 -0
  117. package/lib/Socket/session-manager.d.ts +408 -0
  118. package/lib/Socket/session-manager.d.ts.map +1 -0
  119. package/lib/Socket/session-manager.js +177 -0
  120. package/lib/Socket/session-manager.js.map +1 -0
  121. package/lib/Socket/socket.d.ts +59 -0
  122. package/lib/Socket/socket.d.ts.map +1 -0
  123. package/lib/Socket/socket.js +1039 -0
  124. package/lib/Socket/socket.js.map +1 -0
  125. package/lib/Types/Auth.d.ts +117 -0
  126. package/lib/Types/Auth.d.ts.map +1 -0
  127. package/lib/Types/Auth.js +2 -0
  128. package/lib/Types/Auth.js.map +1 -0
  129. package/lib/Types/Bussines.d.ts +25 -0
  130. package/lib/Types/Bussines.d.ts.map +1 -0
  131. package/lib/Types/Bussines.js +2 -0
  132. package/lib/Types/Bussines.js.map +1 -0
  133. package/lib/Types/Call.d.ts +15 -0
  134. package/lib/Types/Call.d.ts.map +1 -0
  135. package/lib/Types/Call.js +2 -0
  136. package/lib/Types/Call.js.map +1 -0
  137. package/lib/Types/Chat.d.ts +124 -0
  138. package/lib/Types/Chat.d.ts.map +1 -0
  139. package/lib/Types/Chat.js +8 -0
  140. package/lib/Types/Chat.js.map +1 -0
  141. package/lib/Types/Contact.d.ts +26 -0
  142. package/lib/Types/Contact.d.ts.map +1 -0
  143. package/lib/Types/Contact.js +2 -0
  144. package/lib/Types/Contact.js.map +1 -0
  145. package/lib/Types/Events.d.ts +274 -0
  146. package/lib/Types/Events.d.ts.map +1 -0
  147. package/lib/Types/Events.js +2 -0
  148. package/lib/Types/Events.js.map +1 -0
  149. package/lib/Types/GroupMetadata.d.ts +71 -0
  150. package/lib/Types/GroupMetadata.d.ts.map +1 -0
  151. package/lib/Types/GroupMetadata.js +2 -0
  152. package/lib/Types/GroupMetadata.js.map +1 -0
  153. package/lib/Types/Label.d.ts +47 -0
  154. package/lib/Types/Label.d.ts.map +1 -0
  155. package/lib/Types/Label.js +25 -0
  156. package/lib/Types/Label.js.map +1 -0
  157. package/lib/Types/LabelAssociation.d.ts +30 -0
  158. package/lib/Types/LabelAssociation.d.ts.map +1 -0
  159. package/lib/Types/LabelAssociation.js +7 -0
  160. package/lib/Types/LabelAssociation.js.map +1 -0
  161. package/lib/Types/Message.d.ts +402 -0
  162. package/lib/Types/Message.d.ts.map +1 -0
  163. package/lib/Types/Message.js +11 -0
  164. package/lib/Types/Message.js.map +1 -0
  165. package/lib/Types/Mex.d.ts +141 -0
  166. package/lib/Types/Mex.d.ts.map +1 -0
  167. package/lib/Types/Mex.js +37 -0
  168. package/lib/Types/Mex.js.map +1 -0
  169. package/lib/Types/Product.d.ts +79 -0
  170. package/lib/Types/Product.d.ts.map +1 -0
  171. package/lib/Types/Product.js +2 -0
  172. package/lib/Types/Product.js.map +1 -0
  173. package/lib/Types/Signal.d.ts +87 -0
  174. package/lib/Types/Signal.d.ts.map +1 -0
  175. package/lib/Types/Signal.js +2 -0
  176. package/lib/Types/Signal.js.map +1 -0
  177. package/lib/Types/Socket.d.ts +172 -0
  178. package/lib/Types/Socket.d.ts.map +1 -0
  179. package/lib/Types/Socket.js +3 -0
  180. package/lib/Types/Socket.js.map +1 -0
  181. package/lib/Types/State.d.ts +97 -0
  182. package/lib/Types/State.d.ts.map +1 -0
  183. package/lib/Types/State.js +56 -0
  184. package/lib/Types/State.js.map +1 -0
  185. package/lib/Types/USync.d.ts +26 -0
  186. package/lib/Types/USync.d.ts.map +1 -0
  187. package/lib/Types/USync.js +2 -0
  188. package/lib/Types/USync.js.map +1 -0
  189. package/lib/Types/index.d.ts +66 -0
  190. package/lib/Types/index.d.ts.map +1 -0
  191. package/lib/Types/index.js +26 -0
  192. package/lib/Types/index.js.map +1 -0
  193. package/lib/Utils/auth-utils.d.ts +24 -0
  194. package/lib/Utils/auth-utils.d.ts.map +1 -0
  195. package/lib/Utils/auth-utils.js +302 -0
  196. package/lib/Utils/auth-utils.js.map +1 -0
  197. package/lib/Utils/banner.d.ts +28 -0
  198. package/lib/Utils/banner.d.ts.map +1 -0
  199. package/lib/Utils/banner.js +99 -0
  200. package/lib/Utils/banner.js.map +1 -0
  201. package/lib/Utils/browser-utils.d.ts +4 -0
  202. package/lib/Utils/browser-utils.d.ts.map +1 -0
  203. package/lib/Utils/browser-utils.js +29 -0
  204. package/lib/Utils/browser-utils.js.map +1 -0
  205. package/lib/Utils/business.d.ts +23 -0
  206. package/lib/Utils/business.d.ts.map +1 -0
  207. package/lib/Utils/business.js +231 -0
  208. package/lib/Utils/business.js.map +1 -0
  209. package/lib/Utils/button-builder.d.ts +10 -0
  210. package/lib/Utils/button-builder.d.ts.map +1 -0
  211. package/lib/Utils/button-builder.js +48 -0
  212. package/lib/Utils/button-builder.js.map +1 -0
  213. package/lib/Utils/chat-utils.d.ts +100 -0
  214. package/lib/Utils/chat-utils.d.ts.map +1 -0
  215. package/lib/Utils/chat-utils.js +872 -0
  216. package/lib/Utils/chat-utils.js.map +1 -0
  217. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  218. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  219. package/lib/Utils/companion-reg-client-utils.js +35 -0
  220. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  221. package/lib/Utils/console-filter.d.ts +10 -0
  222. package/lib/Utils/console-filter.d.ts.map +1 -0
  223. package/lib/Utils/console-filter.js +44 -0
  224. package/lib/Utils/console-filter.js.map +1 -0
  225. package/lib/Utils/crypto.d.ts +37 -0
  226. package/lib/Utils/crypto.d.ts.map +1 -0
  227. package/lib/Utils/crypto.js +118 -0
  228. package/lib/Utils/crypto.js.map +1 -0
  229. package/lib/Utils/decode-wa-message.d.ts +66 -0
  230. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  231. package/lib/Utils/decode-wa-message.js +317 -0
  232. package/lib/Utils/decode-wa-message.js.map +1 -0
  233. package/lib/Utils/event-buffer.d.ts +36 -0
  234. package/lib/Utils/event-buffer.d.ts.map +1 -0
  235. package/lib/Utils/event-buffer.js +622 -0
  236. package/lib/Utils/event-buffer.js.map +1 -0
  237. package/lib/Utils/generics.d.ts +92 -0
  238. package/lib/Utils/generics.d.ts.map +1 -0
  239. package/lib/Utils/generics.js +395 -0
  240. package/lib/Utils/generics.js.map +1 -0
  241. package/lib/Utils/group-cache.d.ts +22 -0
  242. package/lib/Utils/group-cache.d.ts.map +1 -0
  243. package/lib/Utils/group-cache.js +31 -0
  244. package/lib/Utils/group-cache.js.map +1 -0
  245. package/lib/Utils/group-fetch.d.ts +19 -0
  246. package/lib/Utils/group-fetch.d.ts.map +1 -0
  247. package/lib/Utils/group-fetch.js +43 -0
  248. package/lib/Utils/group-fetch.js.map +1 -0
  249. package/lib/Utils/group-tools.d.ts +38 -0
  250. package/lib/Utils/group-tools.d.ts.map +1 -0
  251. package/lib/Utils/group-tools.js +75 -0
  252. package/lib/Utils/group-tools.js.map +1 -0
  253. package/lib/Utils/helpers.d.ts +180 -0
  254. package/lib/Utils/helpers.d.ts.map +1 -0
  255. package/lib/Utils/helpers.js +279 -0
  256. package/lib/Utils/helpers.js.map +1 -0
  257. package/lib/Utils/history.d.ts +24 -0
  258. package/lib/Utils/history.d.ts.map +1 -0
  259. package/lib/Utils/history.js +134 -0
  260. package/lib/Utils/history.js.map +1 -0
  261. package/lib/Utils/identity-change-handler.d.ts +44 -0
  262. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  263. package/lib/Utils/identity-change-handler.js +50 -0
  264. package/lib/Utils/identity-change-handler.js.map +1 -0
  265. package/lib/Utils/index.d.ts +33 -0
  266. package/lib/Utils/index.d.ts.map +1 -0
  267. package/lib/Utils/index.js +33 -0
  268. package/lib/Utils/index.js.map +1 -0
  269. package/lib/Utils/insights.d.ts +80 -0
  270. package/lib/Utils/insights.d.ts.map +1 -0
  271. package/lib/Utils/insights.js +188 -0
  272. package/lib/Utils/insights.js.map +1 -0
  273. package/lib/Utils/link-preview.d.ts +21 -0
  274. package/lib/Utils/link-preview.d.ts.map +1 -0
  275. package/lib/Utils/link-preview.js +85 -0
  276. package/lib/Utils/link-preview.js.map +1 -0
  277. package/lib/Utils/logger.d.ts +13 -0
  278. package/lib/Utils/logger.d.ts.map +1 -0
  279. package/lib/Utils/logger.js +9 -0
  280. package/lib/Utils/logger.js.map +1 -0
  281. package/lib/Utils/lt-hash.d.ts +8 -0
  282. package/lib/Utils/lt-hash.d.ts.map +1 -0
  283. package/lib/Utils/lt-hash.js +8 -0
  284. package/lib/Utils/lt-hash.js.map +1 -0
  285. package/lib/Utils/make-mutex.d.ts +9 -0
  286. package/lib/Utils/make-mutex.d.ts.map +1 -0
  287. package/lib/Utils/make-mutex.js +33 -0
  288. package/lib/Utils/make-mutex.js.map +1 -0
  289. package/lib/Utils/mentions.d.ts +11 -0
  290. package/lib/Utils/mentions.d.ts.map +1 -0
  291. package/lib/Utils/mentions.js +29 -0
  292. package/lib/Utils/mentions.js.map +1 -0
  293. package/lib/Utils/message-retry-manager.d.ts +115 -0
  294. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  295. package/lib/Utils/message-retry-manager.js +265 -0
  296. package/lib/Utils/message-retry-manager.js.map +1 -0
  297. package/lib/Utils/message-store.d.ts +19 -0
  298. package/lib/Utils/message-store.d.ts.map +1 -0
  299. package/lib/Utils/message-store.js +26 -0
  300. package/lib/Utils/message-store.js.map +1 -0
  301. package/lib/Utils/messages-media.d.ts +133 -0
  302. package/lib/Utils/messages-media.d.ts.map +1 -0
  303. package/lib/Utils/messages-media.js +788 -0
  304. package/lib/Utils/messages-media.js.map +1 -0
  305. package/lib/Utils/messages.d.ts +95 -0
  306. package/lib/Utils/messages.d.ts.map +1 -0
  307. package/lib/Utils/messages.js +1094 -0
  308. package/lib/Utils/messages.js.map +1 -0
  309. package/lib/Utils/noise-handler.d.ts +20 -0
  310. package/lib/Utils/noise-handler.d.ts.map +1 -0
  311. package/lib/Utils/noise-handler.js +201 -0
  312. package/lib/Utils/noise-handler.js.map +1 -0
  313. package/lib/Utils/offline-node-processor.d.ts +17 -0
  314. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  315. package/lib/Utils/offline-node-processor.js +40 -0
  316. package/lib/Utils/offline-node-processor.js.map +1 -0
  317. package/lib/Utils/pre-key-manager.d.ts +28 -0
  318. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  319. package/lib/Utils/pre-key-manager.js +106 -0
  320. package/lib/Utils/pre-key-manager.js.map +1 -0
  321. package/lib/Utils/process-message.d.ts +60 -0
  322. package/lib/Utils/process-message.d.ts.map +1 -0
  323. package/lib/Utils/process-message.js +630 -0
  324. package/lib/Utils/process-message.js.map +1 -0
  325. package/lib/Utils/replies.d.ts +60 -0
  326. package/lib/Utils/replies.d.ts.map +1 -0
  327. package/lib/Utils/replies.js +154 -0
  328. package/lib/Utils/replies.js.map +1 -0
  329. package/lib/Utils/reporting-utils.d.ts +11 -0
  330. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  331. package/lib/Utils/reporting-utils.js +258 -0
  332. package/lib/Utils/reporting-utils.js.map +1 -0
  333. package/lib/Utils/send-queue.d.ts +50 -0
  334. package/lib/Utils/send-queue.d.ts.map +1 -0
  335. package/lib/Utils/send-queue.js +124 -0
  336. package/lib/Utils/send-queue.js.map +1 -0
  337. package/lib/Utils/signal.d.ts +47 -0
  338. package/lib/Utils/signal.d.ts.map +1 -0
  339. package/lib/Utils/signal.js +201 -0
  340. package/lib/Utils/signal.js.map +1 -0
  341. package/lib/Utils/stanza-ack.d.ts +11 -0
  342. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  343. package/lib/Utils/stanza-ack.js +38 -0
  344. package/lib/Utils/stanza-ack.js.map +1 -0
  345. package/lib/Utils/sync-action-utils.d.ts +19 -0
  346. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  347. package/lib/Utils/sync-action-utils.js +49 -0
  348. package/lib/Utils/sync-action-utils.js.map +1 -0
  349. package/lib/Utils/tc-token-utils.d.ts +37 -0
  350. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  351. package/lib/Utils/tc-token-utils.js +164 -0
  352. package/lib/Utils/tc-token-utils.js.map +1 -0
  353. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  354. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  355. package/lib/Utils/use-multi-file-auth-state.js +154 -0
  356. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  357. package/lib/Utils/validate-connection.d.ts +11 -0
  358. package/lib/Utils/validate-connection.d.ts.map +1 -0
  359. package/lib/Utils/validate-connection.js +210 -0
  360. package/lib/Utils/validate-connection.js.map +1 -0
  361. package/lib/Utils/wa-version.d.ts +33 -0
  362. package/lib/Utils/wa-version.d.ts.map +1 -0
  363. package/lib/Utils/wa-version.js +92 -0
  364. package/lib/Utils/wa-version.js.map +1 -0
  365. package/lib/WABinary/constants.d.ts +28 -0
  366. package/lib/WABinary/constants.d.ts.map +1 -0
  367. package/lib/WABinary/constants.js +1301 -0
  368. package/lib/WABinary/constants.js.map +1 -0
  369. package/lib/WABinary/decode.d.ts +7 -0
  370. package/lib/WABinary/decode.d.ts.map +1 -0
  371. package/lib/WABinary/decode.js +262 -0
  372. package/lib/WABinary/decode.js.map +1 -0
  373. package/lib/WABinary/encode.d.ts +3 -0
  374. package/lib/WABinary/encode.d.ts.map +1 -0
  375. package/lib/WABinary/encode.js +220 -0
  376. package/lib/WABinary/encode.js.map +1 -0
  377. package/lib/WABinary/generic-utils.d.ts +17 -0
  378. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  379. package/lib/WABinary/generic-utils.js +213 -0
  380. package/lib/WABinary/generic-utils.js.map +1 -0
  381. package/lib/WABinary/index.d.ts +6 -0
  382. package/lib/WABinary/index.d.ts.map +1 -0
  383. package/lib/WABinary/index.js +6 -0
  384. package/lib/WABinary/index.js.map +1 -0
  385. package/lib/WABinary/jid-utils.d.ts +48 -0
  386. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  387. package/lib/WABinary/jid-utils.js +96 -0
  388. package/lib/WABinary/jid-utils.js.map +1 -0
  389. package/lib/WABinary/types.d.ts +19 -0
  390. package/lib/WABinary/types.d.ts.map +1 -0
  391. package/lib/WABinary/types.js +2 -0
  392. package/lib/WABinary/types.js.map +1 -0
  393. package/lib/WAM/BinaryInfo.d.ts +9 -0
  394. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  395. package/lib/WAM/BinaryInfo.js +10 -0
  396. package/lib/WAM/BinaryInfo.js.map +1 -0
  397. package/lib/WAM/constants.d.ts +40 -0
  398. package/lib/WAM/constants.d.ts.map +1 -0
  399. package/lib/WAM/constants.js +22853 -0
  400. package/lib/WAM/constants.js.map +1 -0
  401. package/lib/WAM/encode.d.ts +3 -0
  402. package/lib/WAM/encode.d.ts.map +1 -0
  403. package/lib/WAM/encode.js +150 -0
  404. package/lib/WAM/encode.js.map +1 -0
  405. package/lib/WAM/index.d.ts +4 -0
  406. package/lib/WAM/index.d.ts.map +1 -0
  407. package/lib/WAM/index.js +4 -0
  408. package/lib/WAM/index.js.map +1 -0
  409. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  410. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  411. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  412. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  413. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  414. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  415. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  416. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  417. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  418. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  419. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  420. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  421. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  422. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  423. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  424. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  425. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  426. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  427. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  428. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  429. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  430. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  431. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  432. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  433. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  434. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  435. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  436. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  437. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  438. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  439. package/lib/WAUSync/Protocols/index.js +6 -0
  440. package/lib/WAUSync/Protocols/index.js.map +1 -0
  441. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  442. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  443. package/lib/WAUSync/USyncQuery.js +98 -0
  444. package/lib/WAUSync/USyncQuery.js.map +1 -0
  445. package/lib/WAUSync/USyncUser.d.ts +17 -0
  446. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  447. package/lib/WAUSync/USyncUser.js +31 -0
  448. package/lib/WAUSync/USyncUser.js.map +1 -0
  449. package/lib/WAUSync/index.d.ts +4 -0
  450. package/lib/WAUSync/index.d.ts.map +1 -0
  451. package/lib/WAUSync/index.js +4 -0
  452. package/lib/WAUSync/index.js.map +1 -0
  453. package/lib/index.d.ts +13 -0
  454. package/lib/index.d.ts.map +1 -0
  455. package/lib/index.js +12 -0
  456. package/lib/index.js.map +1 -0
  457. package/package.json +150 -3
package/README.md CHANGED
@@ -1,3 +1,1686 @@
1
- # Temporary Holding Version
1
+ # Yui-Bails
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Una bails profesional para tu bot de WhatsApp 👑
4
+
5
+ **Creador:** [AmilcarGit](https://github.com/AmilcarGit)
6
+
7
+ <p align="center"><img alt="Yui-Bails" src="Media/logo.svg" height="90"/></p>
8
+
9
+ <p align="center">
10
+ <img src="https://readme-typing-svg.demolab.com?font=Fira+Code&weight=800&size=28&duration=2600&pause=700&color=F72585&center=true&vCenter=true&width=700&height=55&lines=%E2%9A%A1+YUI+%C2%B7+BAILS+%E2%9A%A1" alt="yui bails" />
11
+ </p>
12
+
13
+ <p align="center">
14
+ <img src="https://readme-typing-svg.demolab.com?font=Fira+Code&weight=600&size=18&duration=2400&pause=500&color=00E5FF&center=true&vCenter=true&width=700&height=40&lines=%F0%9F%9A%80+Optimizado+a+fondo+%C2%B7+respuestas+en+ms+bajos;%F0%9F%94%98+Botones+nativos+%C2%B7+listas+%C2%B7+flows+incluidos;%F0%9F%A7%B9+Consola+limpia+%C2%B7+cero+ruido+de+prekeys;%E2%9C%82%EF%B8%8F+Sin+cosas+innecesarias+%C2%B7+puro+rendimiento" alt="features" />
15
+ </p>
16
+
17
+ <p align="center">
18
+ <img src="https://user-images.githubusercontent.com/74038190/212284100-561aa473-3905-4a80-b561-0d28506553ee.gif" width="100%" alt="divider" />
19
+ </p>
20
+
21
+ <p align="center">
22
+ <a href="#-botones-nativos-incluidos"><img src="https://img.shields.io/badge/%F0%9F%94%98_BOTONES-NATIVOS-00e5ff?style=for-the-badge&labelColor=0d1117" alt="botones" /></a>
23
+ <a href="#-qué-trae-yui-bails"><img src="https://img.shields.io/badge/%E2%9A%A1_MODO-TURBO-f72585?style=for-the-badge&labelColor=0d1117" alt="turbo" /></a>
24
+ <a href="#-qué-trae-yui-bails"><img src="https://img.shields.io/badge/%F0%9F%A7%B9_CONSOLA-LIMPIA-9d4edd?style=for-the-badge&labelColor=0d1117" alt="consola" /></a>
25
+ </p>
26
+
27
+ <div align='center'>
28
+
29
+ **Yui-Bails**, creada por **AmilcarGit**, es una librería WebSockets en TypeScript para la API de WhatsApp Web **optimizada para volar**: menos latencia, botones que sí se pintan, y una consola sin basura.
30
+
31
+ </div>
32
+
33
+ ## ⚡ ¿Qué trae Yui-Bails?
34
+
35
+ | | Mejora | Detalle |
36
+ |---|---|---|
37
+ | 🔘 | **Botones nativos** | `buttons` con respuesta rápida, URL, llamar, copiar código y menú desplegable — con el nodo `<biz>` que hace que **sí se rendericen** |
38
+ | 📋 | **Listas** | `sections` para menús de lista en chats privados |
39
+ | 🚀 | **Menos ms por mensaje** | Cache de dispositivos ×6 más duradero (se salta consultas al servidor antes de cada envío) |
40
+ | 🧠 | **Cache de claves Signal ×3** | Menos lecturas de disco en cada cifrado/descifrado |
41
+ | 🪶 | **Logger silencioso** | pino ya no serializa JSON en cada evento — CPU libre y panel limpio |
42
+ | 🧹 | **Cero ruido de prekeys** | Adiós al spam de `Closing session: SessionEntry {...}` de libsignal |
43
+ | 📡 | **Keep-alive 10s** | Detecta caídas de conexión 3× más rápido |
44
+ | ⏱️ | **Sin bloqueos largos** | Reintentos de transacción 30s→2.5s peor caso · link preview con tope de 1.5s |
45
+ | 🪄 | **Arranque ligero** | Sin sincronización de historial completo |
46
+ | 🔄 | **Versión de WA Web al día** | Cada conexión pregunta a WhatsApp qué versión está sirviendo — se acabaron los `405`/`428` al vincular ([detalles](#whatsapp-web-version-fix-for-405--428-on-pairing)) |
47
+ | ✨ | **Banner con flow** | Verás el banner de Yui-Bails apenas arranque |
48
+ | 🧰 | **Helpers integrados** | `getSender`, `reply`, `react`, `sendButtons`, `sendList`, `sendPoll`, `downloadMedia` y conteo de votos de encuestas ([detalles](#-helpers-integrados)) |
49
+ | 🛡️ | **Cola anti-ban** | Pausas aleatorias, límite por chat y "escribiendo…" automático ([detalles](#️-cola-anti-ban-sendqueue)) |
50
+ | 📱 | **Multi-sesión** | Varios números de WhatsApp en un solo proceso con `makeSessionManager` ([detalles](#-multi-sesión-makesessionmanager)) |
51
+
52
+ ## 🔘 Botones nativos incluidos
53
+
54
+ ```js
55
+ await sock.sendMessage(jid, {
56
+ text: 'Texto del mensaje', // con imagen/video usa "caption" en vez de "text"
57
+ footer: 'Pie de página',
58
+ title: 'Título',
59
+ buttons: [
60
+ { text: 'Respuesta rápida', id: '#menu' },
61
+ { text: 'Abrir web', url: 'https://ejemplo.com' },
62
+ { text: 'Llamar', call: '573001234567' },
63
+ { text: 'Copiar código', copy: 'CODIGO123' },
64
+ {
65
+ text: 'Desplegable',
66
+ sections: [{
67
+ title: 'Sección 1',
68
+ rows: [
69
+ { title: 'Opción A', description: 'desc', id: '#a' },
70
+ { title: 'Opción B', description: 'desc', id: '#b' }
71
+ ]
72
+ }]
73
+ }
74
+ ]
75
+ }, { quoted: m })
76
+ ```
77
+
78
+ Con imagen de cabecera:
79
+
80
+ ```js
81
+ await sock.sendMessage(jid, {
82
+ image: { url: './imagen.jpg' }, // también video o document
83
+ caption: 'Texto del mensaje',
84
+ footer: 'Pie de página',
85
+ buttons: [{ text: 'Respuesta rápida', id: '#menu' }]
86
+ })
87
+ ```
88
+
89
+ Listas en chat privado:
90
+
91
+ ```js
92
+ await sock.sendMessage(jid, {
93
+ text: 'Elige una opción',
94
+ title: 'Menú',
95
+ buttonText: 'Ver opciones',
96
+ sections: [{
97
+ title: 'Sección 1',
98
+ rows: [{ title: 'Opción A', description: 'desc', id: '#a' }]
99
+ }]
100
+ })
101
+ ```
102
+
103
+ La respuesta del usuario llega así (desenvuelve antes `msg.ephemeralMessage?.message || msg.viewOnceMessage?.message || msg`):
104
+
105
+ ```js
106
+ // botón de respuesta rápida
107
+ msg.buttonsResponseMessage?.selectedButtonId
108
+
109
+ // desplegable / lista
110
+ msg.listResponseMessage?.singleSelectReply?.selectedRowId
111
+
112
+ // botones native flow (url/copiar/llamar no responden, son acciones directas)
113
+ msg.interactiveResponseMessage?.nativeFlowResponseMessage?.paramsJson // -> JSON.parse(...).id
114
+ ```
115
+
116
+ ### ⚙️ Formato de botones (`buttonsFormat`)
117
+
118
+ Cuando alguien toca un botón, **su teléfono** genera el mensaje de respuesta — no el bot. Según el formato con el que se enviaron los botones, esa respuesta se ve distinta para el resto del chat:
119
+
120
+ | Formato | Los botones se pintan | La respuesta al tocar |
121
+ |---|---|---|
122
+ | `interactive` *(por defecto)* | En clientes modernos | `interactiveResponseMessage` — los clientes sin soporte muestran *"Recibiste un mensaje que no es compatible con tu versión de WhatsApp"* |
123
+ | `buttons` | `ButtonsMessage` clásico | `buttonsResponseMessage` — **todos los clientes la ven como texto normal** |
124
+
125
+ Si te molesta el aviso de "actualiza WhatsApp" que le sale a los demás, usa el formato clásico:
126
+
127
+ ```js
128
+ // por mensaje
129
+ await sock.sendMessage(jid, {
130
+ text: 'Elige una opción',
131
+ footer: 'Pie',
132
+ buttonsFormat: 'buttons', // 👈
133
+ buttons: [{ text: 'Opción A', id: '#a' }]
134
+ })
135
+ ```
136
+
137
+ ```bash
138
+ # o globalmente, sin tocar los plugins
139
+ YUI_BAILS_BUTTONS_FORMAT=buttons
140
+ ```
141
+
142
+ Los botones de `url`, `call`, `copy` y `sections` no tienen equivalente clásico, así que siguen enviándose como native flow incluso en modo `buttons` (aunque esos no generan mensaje de respuesta, así que no producen el aviso).
143
+
144
+ ## 🧰 Helpers integrados
145
+
146
+ Todo socket creado con `makeWASocket` ya los trae, no hay que importar nada.
147
+
148
+ ```js
149
+ sock.ev.on('messages.upsert', async ({ messages }) => {
150
+ const msg = messages[0]
151
+
152
+ // Quién escribió: número real + id interno de WhatsApp (LID), aunque llegue solo uno
153
+ const sender = await sock.getSender(msg)
154
+ sender.number // '51910227479' (undefined si WhatsApp solo mandó el LID)
155
+ sender.id // '269715926691844' (id interno, parte de @lid)
156
+ sender.jid // mejor jid para hablarle
157
+ sender.isGroup // true / false
158
+ sender.is(['51910227479', '269715926691844']) // ¿está en la lista? (ideal para owners)
159
+
160
+ await sock.reply(msg, 'Hola 👋') // responde citando
161
+ await sock.react(msg, '🔥') // reacciona
162
+
163
+ await sock.sendButtons(msg.key.remoteJid, {
164
+ text: 'Elige una opción',
165
+ buttons: [{ id: 'a', text: 'Opción A' }, { text: 'Web', url: 'https://example.com' }]
166
+ })
167
+
168
+ await sock.sendList(msg.key.remoteJid, {
169
+ text: 'Menú',
170
+ buttonText: 'Ver opciones',
171
+ sections: [{ title: 'Comandos', rows: [{ id: 'menu', title: 'Menú', description: 'Lista de comandos' }] }]
172
+ })
173
+
174
+ // Descarga en una sola llamada (también la del mensaje al que respondes)
175
+ const buffer = await sock.downloadMedia(msg)
176
+ const citada = await sock.downloadMedia(msg, { quoted: true })
177
+ })
178
+ ```
179
+
180
+ ### Encuestas con conteo de votos
181
+
182
+ ```js
183
+ const encuesta = await sock.sendPoll(jid, '¿Color favorito?', ['Rojo', 'Azul'])
184
+
185
+ sock.ev.on('poll.votes', ({ pollName, votes, voter }) => {
186
+ // votes = [{ name: 'Rojo', voters: [...] }, { name: 'Azul', voters: [...] }]
187
+ console.log(pollName, votes.map(v => `${v.name}: ${v.voters.length}`))
188
+ })
189
+
190
+ sock.getPollVotes(encuesta.key) // resultado actual
191
+ ```
192
+
193
+ > Para recibir los votos de encuestas que no envió este proceso, implementa `getMessage` en la config.
194
+
195
+ ## 🎛️ Botones avanzados
196
+
197
+ ### Carrusel de tarjetas
198
+
199
+ Hasta 10 tarjetas que se deslizan, cada una con su imagen o video, textos y botones.
200
+
201
+ ```js
202
+ await sock.sendCarousel(jid, {
203
+ text: 'Nuestro catálogo',
204
+ footer: 'Yui-Bails',
205
+ cards: [
206
+ {
207
+ image: { url: 'https://example.com/a.jpg' },
208
+ title: 'Plan básico',
209
+ body: 'Ideal para empezar',
210
+ buttons: [{ id: 'comprar_basico', text: 'Comprar' }, { text: 'Ver web', url: 'https://example.com' }]
211
+ },
212
+ { image: bufferDeImagen, title: 'Plan pro', body: 'Todo incluido', buttons: [{ id: 'comprar_pro', text: 'Comprar' }] }
213
+ ]
214
+ })
215
+ ```
216
+
217
+ ### Responder a botones y menús sin complicarte
218
+
219
+ ```js
220
+ // se ejecuta cuando alguien toca el botón o la fila con ese id (string, RegExp o función)
221
+ sock.onButton('comprar_basico', async (msg, reply) => {
222
+ await sock.reply(msg, `Elegiste: ${reply.text}`)
223
+ }, { once: true, onUsed: msg => sock.reply(msg, 'Este menú ya fue usado ✋') }) // solo el primer toque por menú
224
+
225
+ sock.onList(/^fila_/, async (msg, reply) => sock.reply(msg, `Fila ${reply.id}`))
226
+ sock.onReply(r => r.id.startsWith('x_'), handler) // botones y listas a la vez
227
+
228
+ // esperar la siguiente respuesta de la misma persona en el mismo chat
229
+ await sock.reply(msg, '¿Cómo te llamas?')
230
+ const respuesta = await sock.awaitReply(msg, { timeoutMs: 30_000 })
231
+ if (!respuesta) return sock.reply(msg, '⏱️ Se acabó el tiempo')
232
+ ```
233
+
234
+ `onButton`, `onList` y `onReply` devuelven una función para quitar el manejador. `getReply(msg)` también está exportada si quieres leer el toque tú mismo.
235
+
236
+ ### Quitar los botones de un mensaje
237
+
238
+ ```js
239
+ const enviado = await sock.sendButtons(jid, { text: 'Elige', buttons })
240
+ // ...cuando ya lo usaron:
241
+ await sock.disableButtons(enviado, '✅ Opción elegida')
242
+ ```
243
+
244
+ `disableButtons` edita el mensaje para dejarlo como texto. WhatsApp puede negarse a editar algunos mensajes interactivos y entonces devuelve `false`; para garantizar un solo uso usa `{ once: true }` en `onButton`.
245
+
246
+ ### Icono de IA
247
+
248
+ ```js
249
+ await sock.sendMessage(jid, { text: 'Hola, soy un bot', ai: true })
250
+ ```
251
+
252
+ Marca el mensaje como enviado por un bot de negocio para que WhatsApp muestre el icono de IA. Que se muestre depende de la versión de WhatsApp de quien lo recibe.
253
+
254
+ ## 📊 Datos reales del bot
255
+
256
+ Nada estimado: son contadores y mediciones de lo que hace tu bot.
257
+
258
+ ```js
259
+ // Estado de la conexión, con un ping real a los servidores de WhatsApp
260
+ const salud = await sock.health()
261
+ // { state: 'open', uptimeMs, connectedMs, reconnects, queueSize,
262
+ // memory: { rssMB, heapUsedMB }, latencyMs: 142 } ← latencyMs se mide en ese momento
263
+ await sock.health({ ping: false }) // sin tocar la red
264
+
265
+ // Contadores desde que arrancó (o desde resetStats)
266
+ const stats = sock.getStats()
267
+ // { since, sent, received, failed, sentByType: { text: 12, image: 2 }, receivedByType: {...} }
268
+
269
+ // Hasta dónde llegó cada mensaje que enviaste
270
+ sock.ev.on('message.status', ({ key, status, userJid }) => {
271
+ // status: 'sent' | 'delivered' | 'read' | 'played' | 'failed'
272
+ // en grupos llega uno por miembro (userJid)
273
+ })
274
+ sock.getMessageStatus(mensaje.key) // último estado conocido
275
+ ```
276
+
277
+ `health()` no inventa nada: si no hay conexión devuelve `latencyMs: undefined` y el motivo en `pingError`. El estado de entrega solo llega para mensajes enviados por esta cuenta, y WhatsApp no informa "leído" si la otra persona desactivó las confirmaciones de lectura.
278
+
279
+ ## 👮 Permisos de grupo (con LID)
280
+
281
+ Entienden los dos tipos de identidad de WhatsApp, así que funcionan aunque el grupo muestre LIDs en lugar de números.
282
+
283
+ ```js
284
+ await sock.isAdmin(grupo, msg) // msg, número, jid o el resultado de getSender
285
+ await sock.isAdmin(grupo, '51910227479')
286
+ await sock.isBotAdmin(grupo)
287
+ const admins = await sock.getAdmins(grupo)
288
+
289
+ await sock.kick(grupo, '51911111111') // números o jids, uno o varios
290
+ await sock.addMembers(grupo, ['51911111111', '51922222222'])
291
+ await sock.promote(grupo, '51911111111')
292
+ await sock.demote(grupo, '51911111111')
293
+ ```
294
+
295
+ Usan la caché de grupos (se actualiza sola al cambiar miembros). Para expulsar, añadir o dar admin, el bot debe ser admin del grupo.
296
+
297
+ ## 🏷️ Menciones automáticas
298
+
299
+ Escribe `@número` en un texto o pie de foto y se convierte en mención real; no hace falta armar `mentions`.
300
+
301
+ ```js
302
+ await sock.sendMessage(grupo, { text: 'Hola @51910227479, bienvenido' })
303
+ ```
304
+
305
+ Si el mensaje ya trae su propio `mentions`, se respeta. Solo cuentan números de 7 a 15 dígitos (`@nombre` no). Se desactiva con `autoMentions: false`.
306
+
307
+ ## 🧱 Estabilidad integrada
308
+
309
+ Cosas que casi todos los bots acaban programando a mano, ya resueltas y activas por defecto:
310
+
311
+ - **Sesión a prueba de cortes:** `useMultiFileAuthState` escribe `creds.json` en un archivo temporal y lo renombra, así un corte de luz o un cierre a mitad de guardado no lo deja a medias. Guarda además `creds.json.bak` (solo de archivos sanos) y, si el principal se daña, lo restaura solo.
312
+ - **Reintentos sin configurar nada:** la librería guarda en memoria los últimos mensajes (`messageStore`, 1000 por defecto) para responder a los reintentos de WhatsApp y a los votos de encuestas. Tu `getMessage`, si lo pasas, tiene prioridad. `sock.messageStore` te da acceso.
313
+ - **Caché de grupos:** la lista de miembros de cada grupo se guarda 5 minutos (se renueva sola si el grupo cambia), para no pedirla en cada envío y evitar límites. Si pasas tu propio `cachedGroupMetadata`, se respeta el tuyo.
314
+ - **Resultado claro de cada envío:** `sock.sendSafe()` nunca lanza error y dice `sent`, `failed` o `unknown` (se agotó el tiempo o se cayó la conexión: puede que sí llegue; su `settled` da el resultado final).
315
+
316
+ ```js
317
+ const sock = makeWASocket({
318
+ auth: state,
319
+ messageStore: { max: 2000 }, // o false para desactivarlo
320
+ groupMetadataCache: { ttlMs: 10 * 60_000 } // o false para desactivarla
321
+ })
322
+
323
+ const r = await sock.sendSafe(jid, 'hola', undefined, { timeoutMs: 15_000 })
324
+ if (r.status === 'sent') console.log('enviado', r.message.key.id)
325
+ if (r.status === 'unknown') console.log('quizá llegó:', (await r.settled).status)
326
+ ```
327
+
328
+ ## 🛡️ Cola anti-ban (`sendQueue`)
329
+
330
+ Desactivada por defecto. Al activarla, todo lo que pase por `sock.sendMessage` (incluidos `reply`, `sendButtons`…) sale **uno a uno**, con pausas aleatorias, un límite por chat y el indicador "escribiendo…" proporcional al texto.
331
+
332
+ ```js
333
+ const sock = makeWASocket({
334
+ auth: state,
335
+ sendQueue: true // o personaliza:
336
+ // sendQueue: { minDelayMs: 1000, maxDelayMs: 3000, perChatIntervalMs: 2000,
337
+ // perChatLimit: { max: 15, windowMs: 60_000 }, typing: true }
338
+ })
339
+
340
+ sock.queue.size // mensajes esperando
341
+ sock.queue.clear() // descarta los que faltan
342
+ sock.sendMessageNow(jid, { text: 'urgente' }) // salta la cola
343
+ ```
344
+
345
+ | Opción | Por defecto | Qué hace |
346
+ |---|---|---|
347
+ | `minDelayMs` / `maxDelayMs` | 800 / 2500 | Pausa aleatoria entre dos envíos |
348
+ | `perChatIntervalMs` | 1500 | Mínimo entre dos mensajes al mismo chat |
349
+ | `perChatLimit` | 20 por 60 s | Pasado el límite, los mensajes esperan |
350
+ | `typing` | `true` | "escribiendo…" antes de los textos |
351
+ | `typingMsPerChar` / `typingMinMs` / `typingMaxMs` | 30 / 500 / 3000 | Duración del "escribiendo…" |
352
+ | `maxQueueSize` | 500 | Con la cola llena, `sendMessage` falla con 429 |
353
+
354
+ Reduce el riesgo de bloqueo, pero no lo elimina: no escribas a números que no te conocen ni hagas spam.
355
+
356
+ ## 📱 Multi-sesión (`makeSessionManager`)
357
+
358
+ Varios números de WhatsApp en un mismo proceso. Cada sesión guarda su login en `<authDir>/<id>/`, tiene su socket y se reconecta sola.
359
+
360
+ ```js
361
+ import { makeSessionManager } from 'yui-bails'
362
+
363
+ const sessions = makeSessionManager({
364
+ authDir: './sesiones',
365
+ config: { printQRInTerminal: false },
366
+ // se llama con cada socket nuevo (también tras reconectar)
367
+ setup: (sock, id) => {
368
+ sock.ev.on('messages.upsert', async ({ messages }) => {
369
+ await sock.reply(messages[0], `Hola desde la sesión ${id}`)
370
+ })
371
+ }
372
+ })
373
+
374
+ sessions.on('session.qr', ({ id, qr }) => console.log(id, 'escanea:', qr))
375
+ sessions.on('session.pairing-code', ({ id, code }) => console.log(id, 'código:', code))
376
+ sessions.on('session.open', ({ id, user }) => console.log(id, 'conectado como', user?.id))
377
+ sessions.on('session.logged-out', ({ id }) => console.log(id, 'cerró sesión'))
378
+
379
+ await sessions.start('ventas') // QR
380
+ await sessions.start('soporte', { pairingNumber: '51910227479' }) // código de vinculación
381
+ await sessions.startAll() // restaura todas las sesiones guardadas al arrancar
382
+
383
+ sessions.get('ventas') // el socket
384
+ sessions.list() // estado de cada sesión
385
+ await sessions.stop('ventas') // cierra pero conserva el login
386
+ await sessions.logout('ventas') // cierra sesión en WhatsApp y borra el login
387
+ await sessions.stopAll()
388
+ ```
389
+
390
+ Los ids solo admiten letras, números, `_`, `-` y `.` (son nombres de carpeta).
391
+
392
+ ## 🎛️ Variables de entorno
393
+
394
+ | Variable | Efecto |
395
+ |---|---|
396
+ | `YUI_BAILS_BUTTONS_FORMAT=buttons` | Cambia el formato de botones a `ButtonsMessage` clásico (ver abajo) |
397
+ | `YUI_BAILS_LOG_LEVEL=info` | Reactiva los logs internos (por defecto: silencio total) |
398
+ | `YUI_BAILS_VERBOSE=1` | Muestra también el ruido de libsignal (desactiva el filtro) |
399
+ | `YUI_BAILS_NO_BANNER=1` | Oculta el banner de arranque |
400
+
401
+ <p align="center">
402
+ <img src="https://user-images.githubusercontent.com/74038190/212284100-561aa473-3905-4a80-b561-0d28506553ee.gif" width="100%" alt="divider" />
403
+ </p>
404
+
405
+ <h2 align="center">📚 Guía de uso</h2>
406
+
407
+ # Disclaimer
408
+ This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or its affiliates.
409
+ The official WhatsApp website can be found at whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.
410
+
411
+ The maintainer of Yui-Bails does not in any way condone the use of this application in practices that violate the Terms of Service of WhatsApp. The maintainers of this application call upon the personal responsibility of its users to use this application in a fair way, as it is intended to be used.
412
+ Use at your own discretion. Do not spam people with this. We discourage any stalkerware, bulk or automated messaging usage.
413
+
414
+ ##
415
+
416
+ - Yui-Bails does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a **WebSocket**.
417
+ - Not running Selenium or Chromium saves you like **half a gig** of ram :/
418
+ - Yui-Bails supports interacting with the multi-device & web versions of WhatsApp.
419
+
420
+ ## Example
421
+
422
+ Do check out & run [example.ts](Example/example.ts) to see an example usage of the library.
423
+ The script covers most common use cases.
424
+ To run the example script, download or clone the repo and then type the following in a terminal:
425
+ 1. ``` cd path/to/Yui-Bails ```
426
+ 2. ``` yarn ```
427
+ 3. ``` yarn example ```
428
+
429
+ ## Install
430
+
431
+ Use the stable version (npm):
432
+ ```
433
+ npm install yui-bails@npm:@yui-bails/yui-bails
434
+ ```
435
+ The `yui-bails@npm:` part keeps the short name, so `import ... from 'yui-bails'` works.
436
+
437
+ Use the edge version (no guarantee of stability, but latest fixes + features)
438
+ ```
439
+ yarn add github:AmilcarGit/Yui-Bails
440
+ ```
441
+
442
+ Then import your code using:
443
+ ```ts
444
+ import makeWASocket from 'yui-bails'
445
+ ```
446
+
447
+ # Index
448
+
449
+ - [Connecting Account](#connecting-account)
450
+ - [Connect with QR-CODE](#starting-socket-with-qr-code)
451
+ - [Connect with Pairing Code](#starting-socket-with-pairing-code)
452
+ - [Receive Full History](#receive-full-history)
453
+ - [Important Notes About Socket Config](#important-notes-about-socket-config)
454
+ - [Caching Group Metadata (Recommended)](#caching-group-metadata-recommended)
455
+ - [Improve Retry System & Decrypt Poll Votes](#improve-retry-system--decrypt-poll-votes)
456
+ - [Receive Notifications in Whatsapp App](#receive-notifications-in-whatsapp-app)
457
+
458
+ - [Save Auth Info](#saving--restoring-sessions)
459
+ - [Handling Events](#handling-events)
460
+ - [Example to Start](#example-to-start)
461
+ - [Decrypt Poll Votes](#decrypt-poll-votes)
462
+ - [Summary of Events on First Connection](#summary-of-events-on-first-connection)
463
+ - [Implementing a Data Store](#implementing-a-data-store)
464
+ - [Whatsapp IDs Explain](#whatsapp-ids-explain)
465
+ - [Utility Functions](#utility-functions)
466
+ - [Sending Messages](#sending-messages)
467
+ - [Non-Media Messages](#non-media-messages)
468
+ - [Text Message](#text-message)
469
+ - [Quote Message](#quote-message-works-with-all-types)
470
+ - [Mention User](#mention-user-works-with-most-types)
471
+ - [Forward Messages](#forward-messages)
472
+ - [Location Message](#location-message)
473
+ - [Contact Message](#contact-message)
474
+ - [Reaction Message](#reaction-message)
475
+ - [Pin Message](#pin-message)
476
+ - [Poll Message](#poll-message)
477
+ - [Sending with Link Preview](#sending-messages-with-link-previews)
478
+ - [Media Messages](#media-messages)
479
+ - [Gif Message](#gif-message)
480
+ - [Video Message](#video-message)
481
+ - [Audio Message](#audio-message)
482
+ - [Image Message](#image-message)
483
+ - [ViewOnce Message](#view-once-message)
484
+ - [Modify Messages](#modify-messages)
485
+ - [Delete Messages (for everyone)](#deleting-messages-for-everyone)
486
+ - [Edit Messages](#editing-messages)
487
+ - [Manipulating Media Messages](#manipulating-media-messages)
488
+ - [Thumbnail in Media Messages](#thumbnail-in-media-messages)
489
+ - [Downloading Media Messages](#downloading-media-messages)
490
+ - [Re-upload Media Message to Whatsapp](#re-upload-media-message-to-whatsapp)
491
+ - [Reject Call](#reject-call)
492
+ - [Send States in Chat](#send-states-in-chat)
493
+ - [Reading Messages](#reading-messages)
494
+ - [Update Presence](#update-presence)
495
+ - [Modifying Chats](#modifying-chats)
496
+ - [Archive a Chat](#archive-a-chat)
497
+ - [Mute/Unmute a Chat](#muteunmute-a-chat)
498
+ - [Mark a Chat Read/Unread](#mark-a-chat-readunread)
499
+ - [Delete a Message for Me](#delete-a-message-for-me)
500
+ - [Delete a Chat](#delete-a-chat)
501
+ - [Star/Unstar a Message](#starunstar-a-message)
502
+ - [Disappearing Messages](#disappearing-messages)
503
+ - [User Querys](#user-querys)
504
+ - [Check If ID Exists in Whatsapp](#check-if-id-exists-in-whatsapp)
505
+ - [Query Chat History (groups too)](#query-chat-history-groups-too)
506
+ - [Fetch Status](#fetch-status)
507
+ - [Fetch Profile Picture (groups too)](#fetch-profile-picture-groups-too)
508
+ - [Fetch Bussines Profile (such as description or category)](#fetch-bussines-profile-such-as-description-or-category)
509
+ - [Fetch Someone's Presence (if they're typing or online)](#fetch-someones-presence-if-theyre-typing-or-online)
510
+ - [Change Profile](#change-profile)
511
+ - [Change Profile Status](#change-profile-status)
512
+ - [Change Profile Name](#change-profile-name)
513
+ - [Change Display Picture (groups too)](#change-display-picture-groups-too)
514
+ - [Remove display picture (groups too)](#remove-display-picture-groups-too)
515
+ - [Groups](#groups)
516
+ - [Create a Group](#create-a-group)
517
+ - [Add/Remove or Demote/Promote](#addremove-or-demotepromote)
518
+ - [Change Subject (name)](#change-subject-name)
519
+ - [Change Description](#change-description)
520
+ - [Change Settings](#change-settings)
521
+ - [Leave a Group](#leave-a-group)
522
+ - [Get Invite Code](#get-invite-code)
523
+ - [Revoke Invite Code](#revoke-invite-code)
524
+ - [Join Using Invitation Code](#join-using-invitation-code)
525
+ - [Get Group Info by Invite Code](#get-group-info-by-invite-code)
526
+ - [Query Metadata (participants, name, description...)](#query-metadata-participants-name-description)
527
+ - [Join using groupInviteMessage](#join-using-groupinvitemessage)
528
+ - [Get Request Join List](#get-request-join-list)
529
+ - [Approve/Reject Request Join](#approvereject-request-join)
530
+ - [Get All Participating Groups Metadata](#get-all-participating-groups-metadata)
531
+ - [Toggle Ephemeral](#toggle-ephemeral)
532
+ - [Change Add Mode](#change-add-mode)
533
+ - [Privacy](#privacy)
534
+ - [Block/Unblock User](#blockunblock-user)
535
+ - [Get Privacy Settings](#get-privacy-settings)
536
+ - [Get BlockList](#get-blocklist)
537
+ - [Update LastSeen Privacy](#update-lastseen-privacy)
538
+ - [Update Online Privacy](#update-online-privacy)
539
+ - [Update Profile Picture Privacy](#update-profile-picture-privacy)
540
+ - [Update Status Privacy](#update-status-privacy)
541
+ - [Update Read Receipts Privacy](#update-read-receipts-privacy)
542
+ - [Update Groups Add Privacy](#update-groups-add-privacy)
543
+ - [Update Default Disappearing Mode](#update-default-disappearing-mode)
544
+ - [Broadcast Lists & Stories](#broadcast-lists--stories)
545
+ - [Send Broadcast & Stories](#send-broadcast--stories)
546
+ - [Query a Broadcast List's Recipients & Name](#query-a-broadcast-lists-recipients--name)
547
+ - [Writing Custom Functionality](#writing-custom-functionality)
548
+ - [Enabling Debug Level in Yui-Bails Logs](#enabling-debug-level-in-yui-bails-logs)
549
+ - [How Whatsapp Communicate With Us](#how-whatsapp-communicate-with-us)
550
+ - [Register a Callback for Websocket Events](#register-a-callback-for-websocket-events)
551
+
552
+ ## Connecting Account
553
+
554
+ WhatsApp provides a multi-device API that allows Yui-Bails to be authenticated as a second WhatsApp client by scanning a **QR code** or **Pairing Code** with WhatsApp on your phone.
555
+
556
+ > [!NOTE]
557
+ > **[Here](#example-to-start) is a simple example of event handling**
558
+
559
+ > [!TIP]
560
+ > **You can see all supported socket configs in the [SocketConfig type alias](src/Types) (Recommended)**
561
+
562
+ ### Starting socket with **QR-CODE**
563
+
564
+ > [!TIP]
565
+ > You can customize browser name if you connect with **QR-CODE**, with `Browser` constant, we have some browsers config, **see the [BrowsersMap type alias](src/Types)**
566
+
567
+ ```ts
568
+ import makeWASocket from 'yui-bails'
569
+
570
+ const sock = makeWASocket({
571
+ // can provide additional config here
572
+ browser: Browsers.ubuntu('My App'),
573
+ printQRInTerminal: true
574
+ })
575
+ ```
576
+
577
+ If the connection is successful, you will see a QR code printed on your terminal screen, scan it with WhatsApp on your phone and you'll be logged in!
578
+
579
+ ### Starting socket with **Pairing Code**
580
+
581
+
582
+ > [!IMPORTANT]
583
+ > Pairing Code isn't Mobile API, it's a method to connect Whatsapp Web without QR-CODE, you can connect only with one device, see [here](https://faq.whatsapp.com/1324084875126592/?cms_platform=web)
584
+
585
+ The phone number can't have `+` or `()` or `-`, only numbers, you must provide country code
586
+
587
+ ```ts
588
+ import makeWASocket from 'yui-bails'
589
+
590
+ const sock = makeWASocket({
591
+ // can provide additional config here
592
+ printQRInTerminal: false //need to be false
593
+ })
594
+
595
+ if (!sock.authState.creds.registered) {
596
+ const number = 'XXXXXXXXXXX'
597
+ const code = await sock.requestPairingCode(number)
598
+ console.log(code)
599
+ }
600
+ ```
601
+
602
+ ### Receive Full History
603
+
604
+ 1. Set `syncFullHistory` as `true`
605
+ 2. Yui-Bails, by default, use chrome browser config
606
+ - If you'd like to emulate a desktop connection (and receive more message history), this browser setting to your Socket config:
607
+
608
+ ```ts
609
+ const sock = makeWASocket({
610
+ ...otherOpts,
611
+ // can use Windows, Ubuntu here too
612
+ browser: Browsers.macOS('Desktop'),
613
+ syncFullHistory: true
614
+ })
615
+ ```
616
+
617
+ ## Important Notes About Socket Config
618
+
619
+ ### WhatsApp Web Version (fix for `405` / `428` on pairing)
620
+ WhatsApp turns down the handshake of clients that announce an outdated web version, which shows up as a `405 Method Not Allowed` / `428` right when you try to get a QR or a pairing code.
621
+
622
+ Yui-Bails solves it on its own: **every connection asks WhatsApp which web version it is serving right now** (`web.whatsapp.com/sw.js`, falling back to `check-update`) and connects with that one. No protobuf/platform spoofing involved — only the version.
623
+
624
+ ```ts
625
+ // nothing to do: no `version` means "always the live one"
626
+ const sock = makeWASocket({ auth: state })
627
+ ```
628
+
629
+ - The fetched version is cached in memory for an hour and shared between sockets, so reconnecting costs no extra request. It is dropped automatically if WA answers `405`.
630
+ - If WA can't be reached, the connection goes ahead with the version bundled in the library.
631
+ - Passing `version` pins it and turns the sync off. To pin a fallback but still prefer the live version, set `syncWaWebVersion: true` as well:
632
+ ```ts
633
+ const sock = makeWASocket({
634
+ auth: state,
635
+ version: [2, 3000, 1035194821], // used only if WA can't be reached
636
+ syncWaWebVersion: true
637
+ })
638
+ ```
639
+ - To opt out entirely, set `syncWaWebVersion: false`.
640
+
641
+ ### Caching Group Metadata (Recommended)
642
+ - If you use yui-bails for groups, we recommend you to set `cachedGroupMetadata` in socket config, you need to implement a cache like this:
643
+
644
+ ```ts
645
+ const groupCache = new NodeCache({stdTTL: 5 * 60, useClones: false})
646
+
647
+ const sock = makeWASocket({
648
+ cachedGroupMetadata: async (jid) => groupCache.get(jid)
649
+ })
650
+
651
+ sock.ev.on('groups.update', async ([event]) => {
652
+ const metadata = await sock.groupMetadata(event.id)
653
+ groupCache.set(event.id, metadata)
654
+ })
655
+
656
+ sock.ev.on('group-participants.update', async (event) => {
657
+ const metadata = await sock.groupMetadata(event.id)
658
+ groupCache.set(event.id, metadata)
659
+ })
660
+ ```
661
+
662
+ ### Improve Retry System & Decrypt Poll Votes
663
+ - If you want to improve sending message, retrying when error occurs and decrypt poll votes, you need to have a store and set `getMessage` config in socket like this:
664
+ ```ts
665
+ const sock = makeWASocket({
666
+ getMessage: async (key) => await getMessageFromStore(key)
667
+ })
668
+ ```
669
+
670
+ ### Receive Notifications in Whatsapp App
671
+ - If you want to receive notifications in whatsapp app, set `markOnlineOnConnect` to `false`
672
+ ```ts
673
+ const sock = makeWASocket({
674
+ markOnlineOnConnect: false
675
+ })
676
+ ```
677
+ ## Saving & Restoring Sessions
678
+
679
+ You obviously don't want to keep scanning the QR code every time you want to connect.
680
+
681
+ So, you can load the credentials to log back in:
682
+ ```ts
683
+ import makeWASocket, { useMultiFileAuthState } from 'yui-bails'
684
+
685
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_yui')
686
+
687
+ // will use the given state to connect
688
+ // so if valid credentials are available -- it'll connect without QR
689
+ const sock = makeWASocket({ auth: state })
690
+
691
+ // this will be called as soon as the credentials are updated
692
+ sock.ev.on('creds.update', saveCreds)
693
+ ```
694
+
695
+ > [!IMPORTANT]
696
+ > `useMultiFileAuthState` is a utility function to help save the auth state in a single folder, this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system.
697
+
698
+ > [!NOTE]
699
+ > When a message is received/sent, due to signal sessions needing updating, the auth keys (`authState.keys`) will update. Whenever that happens, you must save the updated keys (`authState.keys.set()` is called). Not doing so will prevent your messages from reaching the recipient & cause other unexpected consequences. The `useMultiFileAuthState` function automatically takes care of that, but for any other serious implementation -- you will need to be very careful with the key state management.
700
+
701
+ ## Handling Events
702
+
703
+ - Yui-Bails uses the EventEmitter syntax for events.
704
+ They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
705
+
706
+ > [!IMPORTANT]
707
+ > **The events are in the [YuiEventMap type alias](src/Types)**, it's important you see all events
708
+
709
+ You can listen to these events like this:
710
+ ```ts
711
+ const sock = makeWASocket()
712
+ sock.ev.on('messages.upsert', ({ messages }) => {
713
+ console.log('got messages', messages)
714
+ })
715
+ ```
716
+
717
+ ### Example to Start
718
+
719
+ > [!NOTE]
720
+ > This example includes basic auth storage too
721
+
722
+ > [!NOTE]
723
+ > For reliable serialization of the authentication state, especially when storing as JSON, always use the BufferJSON utility.
724
+
725
+ ```ts
726
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState } from 'yui-bails'
727
+ import { Boom } from '@hapi/boom'
728
+
729
+ async function connectToWhatsApp () {
730
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_yui')
731
+ const sock = makeWASocket({
732
+ // can provide additional config here
733
+ auth: state,
734
+ printQRInTerminal: true
735
+ })
736
+ sock.ev.on('connection.update', (update) => {
737
+ const { connection, lastDisconnect } = update
738
+ if(connection === 'close') {
739
+ const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
740
+ console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
741
+ // reconnect if not logged out
742
+ if(shouldReconnect) {
743
+ connectToWhatsApp()
744
+ }
745
+ } else if(connection === 'open') {
746
+ console.log('opened connection')
747
+ }
748
+ })
749
+ sock.ev.on('messages.upsert', event => {
750
+ for (const m of event.messages) {
751
+ console.log(JSON.stringify(m, undefined, 2))
752
+
753
+ console.log('replying to', m.key.remoteJid)
754
+ await sock.sendMessage(m.key.remoteJid!, { text: 'Hello Word' })
755
+ }
756
+ })
757
+
758
+ // to storage creds (session info) when it updates
759
+ sock.ev.on('creds.update', saveCreds)
760
+ }
761
+ // run in main file
762
+ connectToWhatsApp()
763
+ ```
764
+
765
+ > [!IMPORTANT]
766
+ > In `messages.upsert` it's recommended to use a loop like `for (const message of event.messages)` to handle all messages in array
767
+
768
+ ### Decrypt Poll Votes
769
+
770
+ - By default poll votes are encrypted and handled in `messages.update`
771
+ - That's a simple example
772
+ ```ts
773
+ sock.ev.on('messages.update', event => {
774
+ for(const { key, update } of event) {
775
+ if(update.pollUpdates) {
776
+ const pollCreation = await getMessage(key)
777
+ if(pollCreation) {
778
+ console.log(
779
+ 'got poll update, aggregation: ',
780
+ getAggregateVotesInPollMessage({
781
+ message: pollCreation,
782
+ pollUpdates: update.pollUpdates,
783
+ })
784
+ )
785
+ }
786
+ }
787
+ }
788
+ })
789
+ ```
790
+
791
+ - `getMessage` is a [store](#implementing-a-data-store) implementation (in your end)
792
+
793
+ ### Summary of Events on First Connection
794
+
795
+ 1. When you connect first time, `connection.update` will be fired requesting you to restart sock
796
+ 2. Then, history messages will be received in `messaging.history-set`
797
+
798
+ ## Implementing a Data Store
799
+
800
+ - Yui-Bails does not come with a defacto storage for chats, contacts, or messages. However, a simple in-memory implementation has been provided. The store listens for chat updates, new messages, message updates, etc., to always have an up-to-date version of the data.
801
+
802
+ > [!IMPORTANT]
803
+ > I highly recommend building your own data store, as storing someone's entire chat history in memory is a terrible waste of RAM.
804
+
805
+ It can be used as follows:
806
+
807
+ ```ts
808
+ import makeWASocket, { makeInMemoryStore } from 'yui-bails'
809
+ // the store maintains the data of the WA connection in memory
810
+ // can be written out to a file & read from it
811
+ const store = makeInMemoryStore({ })
812
+ // can be read from a file
813
+ store.readFromFile('./yui_store.json')
814
+ // saves the state to a file every 10s
815
+ setInterval(() => {
816
+ store.writeToFile('./yui_store.json')
817
+ }, 10_000)
818
+
819
+ const sock = makeWASocket({ })
820
+ // will listen from this socket
821
+ // the store can listen from a new socket once the current socket outlives its lifetime
822
+ store.bind(sock.ev)
823
+
824
+ sock.ev.on('chats.upsert', () => {
825
+ // can use 'store.chats' however you want, even after the socket dies out
826
+ // 'chats' => a KeyedDB instance
827
+ console.log('got chats', store.chats.all())
828
+ })
829
+
830
+ sock.ev.on('contacts.upsert', () => {
831
+ console.log('got contacts', Object.values(store.contacts))
832
+ })
833
+
834
+ ```
835
+
836
+ The store also provides some simple functions such as `loadMessages` that utilize the store to speed up data retrieval.
837
+
838
+ ## Whatsapp IDs Explain
839
+
840
+ - `id` is the WhatsApp ID, called `jid` too, of the person or group you're sending the message to.
841
+ - It must be in the format ```[country code][phone number]@s.whatsapp.net```
842
+ - Example for people: ```+19999999999@s.whatsapp.net```.
843
+ - For groups, it must be in the format ``` 123456789-123345@g.us ```.
844
+ - For broadcast lists, it's `[timestamp of creation]@broadcast`.
845
+ - For stories, the ID is `status@broadcast`.
846
+
847
+ ## Utility Functions
848
+
849
+ - `getContentType`, returns the content type for any message
850
+ - `getDevice`, returns the device from message
851
+ - `makeCacheableSignalKeyStore`, make auth store more fast
852
+ - `downloadContentFromMessage`, download content from any message
853
+
854
+ ## Sending Messages
855
+
856
+ - Send all types of messages with a single function
857
+ - **In the [AnyMessageContent type alias](src/Types) you can see all message contents supported, like text message**
858
+ - **In the [MiscMessageGenerationOptions type alias](src/Types) you can see all options supported, like quote message**
859
+
860
+ ```ts
861
+ const jid: string
862
+ const content: AnyMessageContent
863
+ const options: MiscMessageGenerationOptions
864
+
865
+ sock.sendMessage(jid, content, options)
866
+ ```
867
+
868
+ ### Non-Media Messages
869
+
870
+ #### Text Message
871
+ ```ts
872
+ await sock.sendMessage(jid, { text: 'hello word' })
873
+ ```
874
+
875
+ #### Quote Message (works with all types)
876
+ ```ts
877
+ await sock.sendMessage(jid, { text: 'hello word' }, { quoted: message })
878
+ ```
879
+
880
+ #### Mention User (works with most types)
881
+ - @number is to mention in text, it's optional
882
+ ```ts
883
+ await sock.sendMessage(
884
+ jid,
885
+ {
886
+ text: '@12345678901',
887
+ mentions: ['12345678901@s.whatsapp.net']
888
+ }
889
+ )
890
+ ```
891
+
892
+ #### Forward Messages
893
+ - You need to have message object, can be retrieved from [store](#implementing-a-data-store) or use a [message](src/Types) object
894
+ ```ts
895
+ const msg = getMessageFromStore() // implement this on your end
896
+ await sock.sendMessage(jid, { forward: msg }) // WA forward the message!
897
+ ```
898
+
899
+ #### Location Message
900
+ ```ts
901
+ await sock.sendMessage(
902
+ jid,
903
+ {
904
+ location: {
905
+ degreesLatitude: 24.121231,
906
+ degreesLongitude: 55.1121221
907
+ }
908
+ }
909
+ )
910
+ ```
911
+ #### Contact Message
912
+ ```ts
913
+ const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
914
+ + 'VERSION:3.0\n'
915
+ + 'FN:Jeff Singh\n' // full name
916
+ + 'ORG:Ashoka Uni;\n' // the organization of the contact
917
+ + 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
918
+ + 'END:VCARD'
919
+
920
+ await sock.sendMessage(
921
+ id,
922
+ {
923
+ contacts: {
924
+ displayName: 'Jeff',
925
+ contacts: [{ vcard }]
926
+ }
927
+ }
928
+ )
929
+ ```
930
+
931
+ #### Reaction Message
932
+ - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](src/Types) object
933
+ ```ts
934
+ await sock.sendMessage(
935
+ jid,
936
+ {
937
+ react: {
938
+ text: '💖', // use an empty string to remove the reaction
939
+ key: message.key
940
+ }
941
+ }
942
+ )
943
+ ```
944
+
945
+ #### Pin Message
946
+ - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](src/Types) object
947
+
948
+ - Time can be:
949
+
950
+ | Time | Seconds |
951
+ |-------|----------------|
952
+ | 24h | 86.400 |
953
+ | 7d | 604.800 |
954
+ | 30d | 2.592.000 |
955
+
956
+ ```ts
957
+ await sock.sendMessage(
958
+ jid,
959
+ {
960
+ pin: {
961
+ type: 1, // 0 to remove
962
+ time: 86400
963
+ key: message.key
964
+ }
965
+ }
966
+ )
967
+ ```
968
+
969
+ #### Poll Message
970
+ ```ts
971
+ await sock.sendMessage(
972
+ jid,
973
+ {
974
+ poll: {
975
+ name: 'My Poll',
976
+ values: ['Option 1', 'Option 2', ...],
977
+ selectableCount: 1,
978
+ toAnnouncementGroup: false // or true
979
+ }
980
+ }
981
+ )
982
+ ```
983
+
984
+ ### Sending Messages with Link Previews
985
+
986
+ 1. By default, wa does not have link generation when sent from the web
987
+ 2. Yui-Bails has a function to generate the content for these link previews
988
+ 3. To enable this function's usage, add `link-preview-js` as a dependency to your project with `yarn add link-preview-js`
989
+ 4. Send a link:
990
+ ```ts
991
+ await sock.sendMessage(
992
+ jid,
993
+ {
994
+ text: 'Hi, this was sent using https://github.com/AmilcarGit/Yui-Bails'
995
+ }
996
+ )
997
+ ```
998
+
999
+ ### Media Messages
1000
+
1001
+ Sending media (video, stickers, images) is easier & more efficient than ever.
1002
+
1003
+ > [!NOTE]
1004
+ > In media messages, you can pass `{ stream: Stream }` or `{ url: Url }` or `Buffer` directly, you can see more in the [WAMediaUpload type alias](src/Types)
1005
+
1006
+ - When specifying a media url, Yui-Bails never loads the entire buffer into memory; it even encrypts the media as a readable stream.
1007
+
1008
+ > [!TIP]
1009
+ > It's recommended to use Stream or Url to save memory
1010
+
1011
+ #### Gif Message
1012
+ - Whatsapp doesn't support `.gif` files, that's why we send gifs as common `.mp4` video with `gifPlayback` flag
1013
+ ```ts
1014
+ await sock.sendMessage(
1015
+ jid,
1016
+ {
1017
+ video: fs.readFileSync('Media/ma_gif.mp4'),
1018
+ caption: 'hello word',
1019
+ gifPlayback: true
1020
+ }
1021
+ )
1022
+ ```
1023
+
1024
+ #### Video Message
1025
+ ```ts
1026
+ await sock.sendMessage(
1027
+ id,
1028
+ {
1029
+ video: {
1030
+ url: './Media/ma_gif.mp4'
1031
+ },
1032
+ caption: 'hello word',
1033
+ ptv: false // if set to true, will send as a `video note`
1034
+ }
1035
+ )
1036
+ ```
1037
+
1038
+ #### Audio Message
1039
+ - To audio message work in all devices you need to convert with some tool like `ffmpeg` with this flags:
1040
+ ```bash
1041
+ codec: libopus //ogg file
1042
+ ac: 1 //one channel
1043
+ avoid_negative_ts
1044
+ make_zero
1045
+ ```
1046
+ - Example:
1047
+ ```bash
1048
+ ffmpeg -i input.mp4 -avoid_negative_ts make_zero -ac 1 output.ogg
1049
+ ```
1050
+ ```ts
1051
+ await sock.sendMessage(
1052
+ jid,
1053
+ {
1054
+ audio: {
1055
+ url: './Media/audio.mp3'
1056
+ },
1057
+ mimetype: 'audio/mp4'
1058
+ }
1059
+ )
1060
+ ```
1061
+
1062
+ #### Image Message
1063
+ ```ts
1064
+ await sock.sendMessage(
1065
+ id,
1066
+ {
1067
+ image: {
1068
+ url: './Media/ma_img.png'
1069
+ },
1070
+ caption: 'hello word'
1071
+ }
1072
+ )
1073
+ ```
1074
+
1075
+ #### View Once Message
1076
+
1077
+ - You can send all messages above as `viewOnce`, you only need to pass `viewOnce: true` in content object
1078
+
1079
+ ```ts
1080
+ await sock.sendMessage(
1081
+ id,
1082
+ {
1083
+ image: {
1084
+ url: './Media/ma_img.png'
1085
+ },
1086
+ viewOnce: true, //works with video, audio too
1087
+ caption: 'hello word'
1088
+ }
1089
+ )
1090
+ ```
1091
+
1092
+ ## Modify Messages
1093
+
1094
+ ### Deleting Messages (for everyone)
1095
+
1096
+ ```ts
1097
+ const msg = await sock.sendMessage(jid, { text: 'hello word' })
1098
+ await sock.sendMessage(jid, { delete: msg.key })
1099
+ ```
1100
+
1101
+ **Note:** deleting for oneself is supported via `chatModify`, see in [this section](#modifying-chats)
1102
+
1103
+ ### Editing Messages
1104
+
1105
+ - You can pass all editable contents here
1106
+ ```ts
1107
+ await sock.sendMessage(jid, {
1108
+ text: 'updated text goes here',
1109
+ edit: response.key,
1110
+ });
1111
+ ```
1112
+
1113
+ ## Manipulating Media Messages
1114
+
1115
+ ### Thumbnail in Media Messages
1116
+ - For media messages, the thumbnail can be generated automatically for images & stickers provided you add `jimp` or `sharp` as a dependency in your project using `yarn add jimp` or `yarn add sharp`.
1117
+ - Thumbnails for videos can also be generated automatically, though, you need to have `ffmpeg` installed on your system.
1118
+
1119
+ ### Downloading Media Messages
1120
+
1121
+ If you want to save the media you received
1122
+ ```ts
1123
+ import { createWriteStream } from 'fs'
1124
+ import { downloadMediaMessage, getContentType } from 'yui-bails'
1125
+
1126
+ sock.ev.on('messages.upsert', async ({ [m] }) => {
1127
+ if (!m.message) return // if there is no text or media message
1128
+ const messageType = getContentType(m) // get what type of message it is (text, image, video...)
1129
+
1130
+ // if the message is an image
1131
+ if (messageType === 'imageMessage') {
1132
+ // download the message
1133
+ const stream = await downloadMediaMessage(
1134
+ m,
1135
+ 'stream', // can be 'buffer' too
1136
+ { },
1137
+ {
1138
+ logger,
1139
+ // pass this so that yui-bails can request a reupload of media
1140
+ // that has been deleted
1141
+ reuploadRequest: sock.updateMediaMessage
1142
+ }
1143
+ )
1144
+ // save to file
1145
+ const writeStream = createWriteStream('./my-download.jpeg')
1146
+ stream.pipe(writeStream)
1147
+ }
1148
+ }
1149
+ ```
1150
+
1151
+ ### Re-upload Media Message to Whatsapp
1152
+
1153
+ - WhatsApp automatically removes old media from their servers. For the device to access said media -- a re-upload is required by another device that has it. This can be accomplished using:
1154
+ ```ts
1155
+ await sock.updateMediaMessage(msg)
1156
+ ```
1157
+
1158
+ ## Reject Call
1159
+
1160
+ - You can obtain `callId` and `callFrom` from `call` event
1161
+
1162
+ ```ts
1163
+ await sock.rejectCall(callId, callFrom)
1164
+ ```
1165
+
1166
+ ## Send States in Chat
1167
+
1168
+ ### Reading Messages
1169
+ - A set of message [keys](src/Types) must be explicitly marked read now.
1170
+ - You cannot mark an entire 'chat' read as it were with Yui-Bails Web.
1171
+ This means you have to keep track of unread messages.
1172
+
1173
+ ```ts
1174
+ const key: WAMessageKey
1175
+ // can pass multiple keys to read multiple messages as well
1176
+ await sock.readMessages([key])
1177
+ ```
1178
+
1179
+ The message ID is the unique identifier of the message that you are marking as read.
1180
+ On a `WAMessage`, the `messageID` can be accessed using ```messageID = message.key.id```.
1181
+
1182
+ ### Update Presence
1183
+
1184
+ - ``` presence ``` can be one of the values in the [WAPresence type alias](src/Types)
1185
+ - The presence expires after about 10 seconds.
1186
+ - This lets the person/group with `jid` know whether you're online, offline, typing etc.
1187
+
1188
+ ```ts
1189
+ await sock.sendPresenceUpdate('available', jid)
1190
+ ```
1191
+
1192
+ > [!NOTE]
1193
+ > If a desktop client is active, WA doesn't send push notifications to the device. If you would like to receive said notifications -- mark your Yui-Bails client offline using `sock.sendPresenceUpdate('unavailable')`
1194
+
1195
+ ## Modifying Chats
1196
+
1197
+ WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
1198
+
1199
+ > [!IMPORTANT]
1200
+ > If you mess up one of your updates, WA can log you out of all your devices and you'll have to log in again.
1201
+
1202
+ ### Archive a Chat
1203
+ ```ts
1204
+ const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
1205
+ await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, jid)
1206
+ ```
1207
+ ### Mute/Unmute a Chat
1208
+
1209
+ - Supported times:
1210
+
1211
+ | Time | Miliseconds |
1212
+ |-------|-----------------|
1213
+ | Remove | null |
1214
+ | 8h | 86.400.000 |
1215
+ | 7d | 604.800.000 |
1216
+
1217
+ ```ts
1218
+ // mute for 8 hours
1219
+ await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid)
1220
+ // unmute
1221
+ await sock.chatModify({ mute: null }, jid)
1222
+ ```
1223
+ ### Mark a Chat Read/Unread
1224
+ ```ts
1225
+ const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
1226
+ // mark it unread
1227
+ await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, jid)
1228
+ ```
1229
+
1230
+ ### Delete a Message for Me
1231
+ ```ts
1232
+ await sock.chatModify(
1233
+ {
1234
+ clear: {
1235
+ messages: [
1236
+ {
1237
+ id: 'ATWYHDNNWU81732J',
1238
+ fromMe: true,
1239
+ timestamp: '1654823909'
1240
+ }
1241
+ ]
1242
+ }
1243
+ },
1244
+ jid
1245
+ )
1246
+
1247
+ ```
1248
+ ### Delete a Chat
1249
+ ```ts
1250
+ const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
1251
+ await sock.chatModify({
1252
+ delete: true,
1253
+ lastMessages: [
1254
+ {
1255
+ key: lastMsgInChat.key,
1256
+ messageTimestamp: lastMsgInChat.messageTimestamp
1257
+ }
1258
+ ]
1259
+ },
1260
+ jid
1261
+ )
1262
+ ```
1263
+ ### Pin/Unpin a Chat
1264
+ ```ts
1265
+ await sock.chatModify({
1266
+ pin: true // or `false` to unpin
1267
+ },
1268
+ jid
1269
+ )
1270
+ ```
1271
+ ### Star/Unstar a Message
1272
+ ```ts
1273
+ await sock.chatModify({
1274
+ star: {
1275
+ messages: [
1276
+ {
1277
+ id: 'messageID',
1278
+ fromMe: true // or `false`
1279
+ }
1280
+ ],
1281
+ star: true // - true: Star Message; false: Unstar Message
1282
+ }
1283
+ },
1284
+ jid
1285
+ )
1286
+ ```
1287
+
1288
+ ### Disappearing Messages
1289
+
1290
+ - Ephemeral can be:
1291
+
1292
+ | Time | Seconds |
1293
+ |-------|----------------|
1294
+ | Remove | 0 |
1295
+ | 24h | 86.400 |
1296
+ | 7d | 604.800 |
1297
+ | 90d | 7.776.000 |
1298
+
1299
+ - You need to pass in **Seconds**, default is 7 days
1300
+
1301
+ ```ts
1302
+ // turn on disappearing messages
1303
+ await sock.sendMessage(
1304
+ jid,
1305
+ // this is 1 week in seconds -- how long you want messages to appear for
1306
+ { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL }
1307
+ )
1308
+
1309
+ // will send as a disappearing message
1310
+ await sock.sendMessage(jid, { text: 'hello' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL })
1311
+
1312
+ // turn off disappearing messages
1313
+ await sock.sendMessage(
1314
+ jid,
1315
+ { disappearingMessagesInChat: false }
1316
+ )
1317
+ ```
1318
+
1319
+ ## User Querys
1320
+
1321
+ ### Check If ID Exists in Whatsapp
1322
+ ```ts
1323
+ const [result] = await sock.onWhatsApp(jid)
1324
+ if (result.exists) console.log (`${jid} exists on WhatsApp, as jid: ${result.jid}`)
1325
+ ```
1326
+
1327
+ ### Query Chat History (groups too)
1328
+
1329
+ - You need to have oldest message in chat
1330
+ ```ts
1331
+ const msg = await getOldestMessageInChat(jid) // implement this on your end
1332
+ await sock.fetchMessageHistory(
1333
+ 50, //quantity (max: 50 per query)
1334
+ msg.key,
1335
+ msg.messageTimestamp
1336
+ )
1337
+ ```
1338
+ - Messages will be received in `messaging.history-set` event
1339
+
1340
+ ### Fetch Status
1341
+ ```ts
1342
+ const status = await sock.fetchStatus(jid)
1343
+ console.log('status: ' + status)
1344
+ ```
1345
+
1346
+ ### Fetch Profile Picture (groups too)
1347
+ - To get the display picture of some person/group
1348
+ ```ts
1349
+ // for low res picture
1350
+ const ppUrl = await sock.profilePictureUrl(jid)
1351
+ console.log(ppUrl)
1352
+
1353
+ // for high res picture
1354
+ const ppUrl = await sock.profilePictureUrl(jid, 'image')
1355
+ ```
1356
+
1357
+ ### Fetch Bussines Profile (such as description or category)
1358
+ ```ts
1359
+ const profile = await sock.getBusinessProfile(jid)
1360
+ console.log('business description: ' + profile.description + ', category: ' + profile.category)
1361
+ ```
1362
+
1363
+ ### Fetch Someone's Presence (if they're typing or online)
1364
+ ```ts
1365
+ // the presence update is fetched and called here
1366
+ sock.ev.on('presence.update', console.log)
1367
+
1368
+ // request updates for a chat
1369
+ await sock.presenceSubscribe(jid)
1370
+ ```
1371
+
1372
+ ## Change Profile
1373
+
1374
+ ### Change Profile Status
1375
+ ```ts
1376
+ await sock.updateProfileStatus('Hello World!')
1377
+ ```
1378
+ ### Change Profile Name
1379
+ ```ts
1380
+ await sock.updateProfileName('My name')
1381
+ ```
1382
+ ### Change Display Picture (groups too)
1383
+ - To change your display picture or a group's
1384
+
1385
+ > [!NOTE]
1386
+ > Like media messages, you can pass `{ stream: Stream }` or `{ url: Url }` or `Buffer` directly, you can see more in the [WAMediaUpload type alias](src/Types)
1387
+
1388
+ ```ts
1389
+ await sock.updateProfilePicture(jid, { url: './new-profile-picture.jpeg' })
1390
+ ```
1391
+ ### Remove display picture (groups too)
1392
+ ```ts
1393
+ await sock.removeProfilePicture(jid)
1394
+ ```
1395
+
1396
+ ## Groups
1397
+
1398
+ - To change group properties you need to be admin
1399
+
1400
+ ### Create a Group
1401
+ ```ts
1402
+ // title & participants
1403
+ const group = await sock.groupCreate('My Fab Group', ['1234@s.whatsapp.net', '4564@s.whatsapp.net'])
1404
+ console.log('created group with id: ' + group.gid)
1405
+ await sock.sendMessage(group.id, { text: 'hello there' }) // say hello to everyone on the group
1406
+ ```
1407
+ ### Add/Remove or Demote/Promote
1408
+ ```ts
1409
+ // id & people to add to the group (will throw error if it fails)
1410
+ await sock.groupParticipantsUpdate(
1411
+ jid,
1412
+ ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
1413
+ 'add' // replace this parameter with 'remove' or 'demote' or 'promote'
1414
+ )
1415
+ ```
1416
+ ### Change Subject (name)
1417
+ ```ts
1418
+ await sock.groupUpdateSubject(jid, 'New Subject!')
1419
+ ```
1420
+ ### Change Description
1421
+ ```ts
1422
+ await sock.groupUpdateDescription(jid, 'New Description!')
1423
+ ```
1424
+ ### Change Settings
1425
+ ```ts
1426
+ // only allow admins to send messages
1427
+ await sock.groupSettingUpdate(jid, 'announcement')
1428
+ // allow everyone to send messages
1429
+ await sock.groupSettingUpdate(jid, 'not_announcement')
1430
+ // allow everyone to modify the group's settings -- like display picture etc.
1431
+ await sock.groupSettingUpdate(jid, 'unlocked')
1432
+ // only allow admins to modify the group's settings
1433
+ await sock.groupSettingUpdate(jid, 'locked')
1434
+ ```
1435
+ ### Leave a Group
1436
+ ```ts
1437
+ // will throw error if it fails
1438
+ await sock.groupLeave(jid)
1439
+ ```
1440
+ ### Get Invite Code
1441
+ - To create link with code use `'https://chat.whatsapp.com/' + code`
1442
+ ```ts
1443
+ const code = await sock.groupInviteCode(jid)
1444
+ console.log('group code: ' + code)
1445
+ ```
1446
+ ### Revoke Invite Code
1447
+ ```ts
1448
+ const code = await sock.groupRevokeInvite(jid)
1449
+ console.log('New group code: ' + code)
1450
+ ```
1451
+ ### Join Using Invitation Code
1452
+ - Code can't have `https://chat.whatsapp.com/`, only code
1453
+ ```ts
1454
+ const response = await sock.groupAcceptInvite(code)
1455
+ console.log('joined to: ' + response)
1456
+ ```
1457
+ ### Get Group Info by Invite Code
1458
+ ```ts
1459
+ const response = await sock.groupGetInviteInfo(code)
1460
+ console.log('group information: ' + response)
1461
+ ```
1462
+ ### Query Metadata (participants, name, description...)
1463
+ ```ts
1464
+ const metadata = await sock.groupMetadata(jid)
1465
+ console.log(metadata.id + ', title: ' + metadata.subject + ', description: ' + metadata.desc)
1466
+ ```
1467
+ ### Join using `groupInviteMessage`
1468
+ ```ts
1469
+ const response = await sock.groupAcceptInviteV4(jid, groupInviteMessage)
1470
+ console.log('joined to: ' + response)
1471
+ ```
1472
+ ### Get Request Join List
1473
+ ```ts
1474
+ const response = await sock.groupRequestParticipantsList(jid)
1475
+ console.log(response)
1476
+ ```
1477
+ ### Approve/Reject Request Join
1478
+ ```ts
1479
+ const response = await sock.groupRequestParticipantsUpdate(
1480
+ jid, // group id
1481
+ ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
1482
+ 'approve' // or 'reject'
1483
+ )
1484
+ console.log(response)
1485
+ ```
1486
+ ### Get All Participating Groups Metadata
1487
+ ```ts
1488
+ const response = await sock.groupFetchAllParticipating()
1489
+ console.log(response)
1490
+ ```
1491
+ ### Toggle Ephemeral
1492
+
1493
+ - Ephemeral can be:
1494
+
1495
+ | Time | Seconds |
1496
+ |-------|----------------|
1497
+ | Remove | 0 |
1498
+ | 24h | 86.400 |
1499
+ | 7d | 604.800 |
1500
+ | 90d | 7.776.000 |
1501
+
1502
+ ```ts
1503
+ await sock.groupToggleEphemeral(jid, 86400)
1504
+ ```
1505
+
1506
+ ### Change Add Mode
1507
+ ```ts
1508
+ await sock.groupMemberAddMode(
1509
+ jid,
1510
+ 'all_member_add' // or 'admin_add'
1511
+ )
1512
+ ```
1513
+
1514
+ ## Privacy
1515
+
1516
+ ### Block/Unblock User
1517
+ ```ts
1518
+ await sock.updateBlockStatus(jid, 'block') // Block user
1519
+ await sock.updateBlockStatus(jid, 'unblock') // Unblock user
1520
+ ```
1521
+ ### Get Privacy Settings
1522
+ ```ts
1523
+ const privacySettings = await sock.fetchPrivacySettings(true)
1524
+ console.log('privacy settings: ' + privacySettings)
1525
+ ```
1526
+ ### Get BlockList
1527
+ ```ts
1528
+ const response = await sock.fetchBlocklist()
1529
+ console.log(response)
1530
+ ```
1531
+ ### Update LastSeen Privacy
1532
+ ```ts
1533
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
1534
+ await sock.updateLastSeenPrivacy(value)
1535
+ ```
1536
+ ### Update Online Privacy
1537
+ ```ts
1538
+ const value = 'all' // 'match_last_seen'
1539
+ await sock.updateOnlinePrivacy(value)
1540
+ ```
1541
+ ### Update Profile Picture Privacy
1542
+ ```ts
1543
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
1544
+ await sock.updateProfilePicturePrivacy(value)
1545
+ ```
1546
+ ### Update Status Privacy
1547
+ ```ts
1548
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
1549
+ await sock.updateStatusPrivacy(value)
1550
+ ```
1551
+ ### Update Read Receipts Privacy
1552
+ ```ts
1553
+ const value = 'all' // 'none'
1554
+ await sock.updateReadReceiptsPrivacy(value)
1555
+ ```
1556
+ ### Update Groups Add Privacy
1557
+ ```ts
1558
+ const value = 'all' // 'contacts' | 'contact_blacklist'
1559
+ await sock.updateGroupsAddPrivacy(value)
1560
+ ```
1561
+ ### Update Default Disappearing Mode
1562
+
1563
+ - Like [this](#disappearing-messages), ephemeral can be:
1564
+
1565
+ | Time | Seconds |
1566
+ |-------|----------------|
1567
+ | Remove | 0 |
1568
+ | 24h | 86.400 |
1569
+ | 7d | 604.800 |
1570
+ | 90d | 7.776.000 |
1571
+
1572
+ ```ts
1573
+ const ephemeral = 86400
1574
+ await sock.updateDefaultDisappearingMode(ephemeral)
1575
+ ```
1576
+
1577
+ ## Broadcast Lists & Stories
1578
+
1579
+ ### Send Broadcast & Stories
1580
+ - Messages can be sent to broadcasts & stories. You need to add the following message options in sendMessage, like this:
1581
+ ```ts
1582
+ await sock.sendMessage(
1583
+ jid,
1584
+ {
1585
+ image: {
1586
+ url: url
1587
+ },
1588
+ caption: caption
1589
+ },
1590
+ {
1591
+ backgroundColor: backgroundColor,
1592
+ font: font,
1593
+ statusJidList: statusJidList,
1594
+ broadcast: true
1595
+ }
1596
+ )
1597
+ ```
1598
+ - Message body can be a `extendedTextMessage` or `imageMessage` or `videoMessage` or `voiceMessage`, see the [AnyRegularMessageContent type alias](src/Types)
1599
+ - You can add `backgroundColor` and other options in the message options, see the [MiscMessageGenerationOptions type alias](src/Types)
1600
+ - `broadcast: true` enables broadcast mode
1601
+ - `statusJidList`: a list of people that you can get which you need to provide, which are the people who will get this status message.
1602
+
1603
+ - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
1604
+ - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
1605
+ - Broadcast IDs are in the format `12345678@broadcast`
1606
+ ### Query a Broadcast List's Recipients & Name
1607
+ ```ts
1608
+ const bList = await sock.getBroadcastListInfo('1234@broadcast')
1609
+ console.log (`list name: ${bList.name}, recps: ${bList.recipients}`)
1610
+ ```
1611
+
1612
+ ## Writing Custom Functionality
1613
+ Yui-Bails is written with custom functionality in mind. You can write your own extensions without re-writing the internals.
1614
+
1615
+ ### Enabling Debug Level in Yui-Bails Logs
1616
+ First, enable the logging of unhandled messages from WhatsApp by setting:
1617
+ ```ts
1618
+ const sock = makeWASocket({
1619
+ logger: P({ level: 'debug' }),
1620
+ })
1621
+ ```
1622
+ This will enable you to see all sorts of messages WhatsApp sends in the console.
1623
+
1624
+ ### How Whatsapp Communicate With Us
1625
+
1626
+ > [!TIP]
1627
+ > If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
1628
+
1629
+ - **Example:** Functionality to track the battery percentage of your phone. You enable logging and you'll see a message about your battery pop up in the console:
1630
+ ```
1631
+ {
1632
+ "level": 10,
1633
+ "fromMe": false,
1634
+ "frame": {
1635
+ "tag": "ib",
1636
+ "attrs": {
1637
+ "from": "@s.whatsapp.net"
1638
+ },
1639
+ "content": [
1640
+ {
1641
+ "tag": "edge_routing",
1642
+ "attrs": {},
1643
+ "content": [
1644
+ {
1645
+ "tag": "routing_info",
1646
+ "attrs": {},
1647
+ "content": {
1648
+ "type": "Buffer",
1649
+ "data": [8,2,8,5]
1650
+ }
1651
+ }
1652
+ ]
1653
+ }
1654
+ ]
1655
+ },
1656
+ "msg":"communication"
1657
+ }
1658
+ ```
1659
+
1660
+ The `'frame'` is what the message received is, it has three components:
1661
+ - `tag` -- what this frame is about (eg. message will have 'message')
1662
+ - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
1663
+ - `content` -- the actual data (eg. a message node will have the actual message content in it)
1664
+ - read more about this format [here](/src/WABinary/readme.md)
1665
+
1666
+ ### Register a Callback for Websocket Events
1667
+
1668
+ > [!TIP]
1669
+ > Recommended to see `onMessageReceived` function in `socket.ts` file to understand how websockets events are fired
1670
+
1671
+ ```ts
1672
+ // for any message with tag 'edge_routing'
1673
+ sock.ws.on('CB:edge_routing', (node: BinaryNode) => { })
1674
+
1675
+ // for any message with tag 'edge_routing' and id attribute = abcd
1676
+ sock.ws.on('CB:edge_routing,id:abcd', (node: BinaryNode) => { })
1677
+
1678
+ // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
1679
+ sock.ws.on('CB:edge_routing,id:abcd,routing_info', (node: BinaryNode) => { })
1680
+ ```
1681
+
1682
+ # Licencia
1683
+
1684
+ Licencia MIT. Consulta el archivo [LICENSE](LICENSE).
1685
+
1686
+ Creado por [AmilcarGit](https://github.com/AmilcarGit).