@yui-bails/yui-bails 0.0.0-stage → 1.1.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 (465) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +1837 -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 +111 -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 +188 -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/automation.d.ts +34 -0
  198. package/lib/Utils/automation.d.ts.map +1 -0
  199. package/lib/Utils/automation.js +44 -0
  200. package/lib/Utils/automation.js.map +1 -0
  201. package/lib/Utils/banner.d.ts +28 -0
  202. package/lib/Utils/banner.d.ts.map +1 -0
  203. package/lib/Utils/banner.js +99 -0
  204. package/lib/Utils/banner.js.map +1 -0
  205. package/lib/Utils/browser-utils.d.ts +4 -0
  206. package/lib/Utils/browser-utils.d.ts.map +1 -0
  207. package/lib/Utils/browser-utils.js +29 -0
  208. package/lib/Utils/browser-utils.js.map +1 -0
  209. package/lib/Utils/business.d.ts +23 -0
  210. package/lib/Utils/business.d.ts.map +1 -0
  211. package/lib/Utils/business.js +231 -0
  212. package/lib/Utils/business.js.map +1 -0
  213. package/lib/Utils/button-builder.d.ts +10 -0
  214. package/lib/Utils/button-builder.d.ts.map +1 -0
  215. package/lib/Utils/button-builder.js +48 -0
  216. package/lib/Utils/button-builder.js.map +1 -0
  217. package/lib/Utils/chat-utils.d.ts +100 -0
  218. package/lib/Utils/chat-utils.d.ts.map +1 -0
  219. package/lib/Utils/chat-utils.js +872 -0
  220. package/lib/Utils/chat-utils.js.map +1 -0
  221. package/lib/Utils/companion-reg-client-utils.d.ts +17 -0
  222. package/lib/Utils/companion-reg-client-utils.d.ts.map +1 -0
  223. package/lib/Utils/companion-reg-client-utils.js +35 -0
  224. package/lib/Utils/companion-reg-client-utils.js.map +1 -0
  225. package/lib/Utils/console-filter.d.ts +10 -0
  226. package/lib/Utils/console-filter.d.ts.map +1 -0
  227. package/lib/Utils/console-filter.js +44 -0
  228. package/lib/Utils/console-filter.js.map +1 -0
  229. package/lib/Utils/crypto.d.ts +37 -0
  230. package/lib/Utils/crypto.d.ts.map +1 -0
  231. package/lib/Utils/crypto.js +118 -0
  232. package/lib/Utils/crypto.js.map +1 -0
  233. package/lib/Utils/decode-wa-message.d.ts +66 -0
  234. package/lib/Utils/decode-wa-message.d.ts.map +1 -0
  235. package/lib/Utils/decode-wa-message.js +317 -0
  236. package/lib/Utils/decode-wa-message.js.map +1 -0
  237. package/lib/Utils/event-buffer.d.ts +36 -0
  238. package/lib/Utils/event-buffer.d.ts.map +1 -0
  239. package/lib/Utils/event-buffer.js +622 -0
  240. package/lib/Utils/event-buffer.js.map +1 -0
  241. package/lib/Utils/generics.d.ts +92 -0
  242. package/lib/Utils/generics.d.ts.map +1 -0
  243. package/lib/Utils/generics.js +395 -0
  244. package/lib/Utils/generics.js.map +1 -0
  245. package/lib/Utils/group-cache.d.ts +22 -0
  246. package/lib/Utils/group-cache.d.ts.map +1 -0
  247. package/lib/Utils/group-cache.js +31 -0
  248. package/lib/Utils/group-cache.js.map +1 -0
  249. package/lib/Utils/group-fetch.d.ts +19 -0
  250. package/lib/Utils/group-fetch.d.ts.map +1 -0
  251. package/lib/Utils/group-fetch.js +43 -0
  252. package/lib/Utils/group-fetch.js.map +1 -0
  253. package/lib/Utils/group-tools.d.ts +38 -0
  254. package/lib/Utils/group-tools.d.ts.map +1 -0
  255. package/lib/Utils/group-tools.js +75 -0
  256. package/lib/Utils/group-tools.js.map +1 -0
  257. package/lib/Utils/helpers.d.ts +180 -0
  258. package/lib/Utils/helpers.d.ts.map +1 -0
  259. package/lib/Utils/helpers.js +279 -0
  260. package/lib/Utils/helpers.js.map +1 -0
  261. package/lib/Utils/history.d.ts +24 -0
  262. package/lib/Utils/history.d.ts.map +1 -0
  263. package/lib/Utils/history.js +134 -0
  264. package/lib/Utils/history.js.map +1 -0
  265. package/lib/Utils/identity-change-handler.d.ts +44 -0
  266. package/lib/Utils/identity-change-handler.d.ts.map +1 -0
  267. package/lib/Utils/identity-change-handler.js +50 -0
  268. package/lib/Utils/identity-change-handler.js.map +1 -0
  269. package/lib/Utils/index.d.ts +35 -0
  270. package/lib/Utils/index.d.ts.map +1 -0
  271. package/lib/Utils/index.js +35 -0
  272. package/lib/Utils/index.js.map +1 -0
  273. package/lib/Utils/insights.d.ts +80 -0
  274. package/lib/Utils/insights.d.ts.map +1 -0
  275. package/lib/Utils/insights.js +188 -0
  276. package/lib/Utils/insights.js.map +1 -0
  277. package/lib/Utils/link-preview.d.ts +21 -0
  278. package/lib/Utils/link-preview.d.ts.map +1 -0
  279. package/lib/Utils/link-preview.js +85 -0
  280. package/lib/Utils/link-preview.js.map +1 -0
  281. package/lib/Utils/logger.d.ts +13 -0
  282. package/lib/Utils/logger.d.ts.map +1 -0
  283. package/lib/Utils/logger.js +9 -0
  284. package/lib/Utils/logger.js.map +1 -0
  285. package/lib/Utils/lt-hash.d.ts +8 -0
  286. package/lib/Utils/lt-hash.d.ts.map +1 -0
  287. package/lib/Utils/lt-hash.js +8 -0
  288. package/lib/Utils/lt-hash.js.map +1 -0
  289. package/lib/Utils/make-mutex.d.ts +9 -0
  290. package/lib/Utils/make-mutex.d.ts.map +1 -0
  291. package/lib/Utils/make-mutex.js +33 -0
  292. package/lib/Utils/make-mutex.js.map +1 -0
  293. package/lib/Utils/mentions.d.ts +11 -0
  294. package/lib/Utils/mentions.d.ts.map +1 -0
  295. package/lib/Utils/mentions.js +29 -0
  296. package/lib/Utils/mentions.js.map +1 -0
  297. package/lib/Utils/message-retry-manager.d.ts +115 -0
  298. package/lib/Utils/message-retry-manager.d.ts.map +1 -0
  299. package/lib/Utils/message-retry-manager.js +265 -0
  300. package/lib/Utils/message-retry-manager.js.map +1 -0
  301. package/lib/Utils/message-store.d.ts +19 -0
  302. package/lib/Utils/message-store.d.ts.map +1 -0
  303. package/lib/Utils/message-store.js +26 -0
  304. package/lib/Utils/message-store.js.map +1 -0
  305. package/lib/Utils/messages-media.d.ts +133 -0
  306. package/lib/Utils/messages-media.d.ts.map +1 -0
  307. package/lib/Utils/messages-media.js +788 -0
  308. package/lib/Utils/messages-media.js.map +1 -0
  309. package/lib/Utils/messages.d.ts +95 -0
  310. package/lib/Utils/messages.d.ts.map +1 -0
  311. package/lib/Utils/messages.js +1094 -0
  312. package/lib/Utils/messages.js.map +1 -0
  313. package/lib/Utils/noise-handler.d.ts +20 -0
  314. package/lib/Utils/noise-handler.d.ts.map +1 -0
  315. package/lib/Utils/noise-handler.js +201 -0
  316. package/lib/Utils/noise-handler.js.map +1 -0
  317. package/lib/Utils/offline-node-processor.d.ts +17 -0
  318. package/lib/Utils/offline-node-processor.d.ts.map +1 -0
  319. package/lib/Utils/offline-node-processor.js +40 -0
  320. package/lib/Utils/offline-node-processor.js.map +1 -0
  321. package/lib/Utils/pre-key-manager.d.ts +28 -0
  322. package/lib/Utils/pre-key-manager.d.ts.map +1 -0
  323. package/lib/Utils/pre-key-manager.js +106 -0
  324. package/lib/Utils/pre-key-manager.js.map +1 -0
  325. package/lib/Utils/pretty-log.d.ts +33 -0
  326. package/lib/Utils/pretty-log.d.ts.map +1 -0
  327. package/lib/Utils/pretty-log.js +117 -0
  328. package/lib/Utils/pretty-log.js.map +1 -0
  329. package/lib/Utils/process-message.d.ts +60 -0
  330. package/lib/Utils/process-message.d.ts.map +1 -0
  331. package/lib/Utils/process-message.js +630 -0
  332. package/lib/Utils/process-message.js.map +1 -0
  333. package/lib/Utils/replies.d.ts +60 -0
  334. package/lib/Utils/replies.d.ts.map +1 -0
  335. package/lib/Utils/replies.js +154 -0
  336. package/lib/Utils/replies.js.map +1 -0
  337. package/lib/Utils/reporting-utils.d.ts +11 -0
  338. package/lib/Utils/reporting-utils.d.ts.map +1 -0
  339. package/lib/Utils/reporting-utils.js +258 -0
  340. package/lib/Utils/reporting-utils.js.map +1 -0
  341. package/lib/Utils/send-queue.d.ts +50 -0
  342. package/lib/Utils/send-queue.d.ts.map +1 -0
  343. package/lib/Utils/send-queue.js +124 -0
  344. package/lib/Utils/send-queue.js.map +1 -0
  345. package/lib/Utils/signal.d.ts +47 -0
  346. package/lib/Utils/signal.d.ts.map +1 -0
  347. package/lib/Utils/signal.js +201 -0
  348. package/lib/Utils/signal.js.map +1 -0
  349. package/lib/Utils/stanza-ack.d.ts +11 -0
  350. package/lib/Utils/stanza-ack.d.ts.map +1 -0
  351. package/lib/Utils/stanza-ack.js +38 -0
  352. package/lib/Utils/stanza-ack.js.map +1 -0
  353. package/lib/Utils/sync-action-utils.d.ts +19 -0
  354. package/lib/Utils/sync-action-utils.d.ts.map +1 -0
  355. package/lib/Utils/sync-action-utils.js +49 -0
  356. package/lib/Utils/sync-action-utils.js.map +1 -0
  357. package/lib/Utils/tc-token-utils.d.ts +37 -0
  358. package/lib/Utils/tc-token-utils.d.ts.map +1 -0
  359. package/lib/Utils/tc-token-utils.js +164 -0
  360. package/lib/Utils/tc-token-utils.js.map +1 -0
  361. package/lib/Utils/use-multi-file-auth-state.d.ts +13 -0
  362. package/lib/Utils/use-multi-file-auth-state.d.ts.map +1 -0
  363. package/lib/Utils/use-multi-file-auth-state.js +154 -0
  364. package/lib/Utils/use-multi-file-auth-state.js.map +1 -0
  365. package/lib/Utils/validate-connection.d.ts +11 -0
  366. package/lib/Utils/validate-connection.d.ts.map +1 -0
  367. package/lib/Utils/validate-connection.js +210 -0
  368. package/lib/Utils/validate-connection.js.map +1 -0
  369. package/lib/Utils/wa-version.d.ts +33 -0
  370. package/lib/Utils/wa-version.d.ts.map +1 -0
  371. package/lib/Utils/wa-version.js +92 -0
  372. package/lib/Utils/wa-version.js.map +1 -0
  373. package/lib/WABinary/constants.d.ts +28 -0
  374. package/lib/WABinary/constants.d.ts.map +1 -0
  375. package/lib/WABinary/constants.js +1301 -0
  376. package/lib/WABinary/constants.js.map +1 -0
  377. package/lib/WABinary/decode.d.ts +7 -0
  378. package/lib/WABinary/decode.d.ts.map +1 -0
  379. package/lib/WABinary/decode.js +262 -0
  380. package/lib/WABinary/decode.js.map +1 -0
  381. package/lib/WABinary/encode.d.ts +3 -0
  382. package/lib/WABinary/encode.d.ts.map +1 -0
  383. package/lib/WABinary/encode.js +220 -0
  384. package/lib/WABinary/encode.js.map +1 -0
  385. package/lib/WABinary/generic-utils.d.ts +17 -0
  386. package/lib/WABinary/generic-utils.d.ts.map +1 -0
  387. package/lib/WABinary/generic-utils.js +213 -0
  388. package/lib/WABinary/generic-utils.js.map +1 -0
  389. package/lib/WABinary/index.d.ts +6 -0
  390. package/lib/WABinary/index.d.ts.map +1 -0
  391. package/lib/WABinary/index.js +6 -0
  392. package/lib/WABinary/index.js.map +1 -0
  393. package/lib/WABinary/jid-utils.d.ts +48 -0
  394. package/lib/WABinary/jid-utils.d.ts.map +1 -0
  395. package/lib/WABinary/jid-utils.js +96 -0
  396. package/lib/WABinary/jid-utils.js.map +1 -0
  397. package/lib/WABinary/types.d.ts +19 -0
  398. package/lib/WABinary/types.d.ts.map +1 -0
  399. package/lib/WABinary/types.js +2 -0
  400. package/lib/WABinary/types.js.map +1 -0
  401. package/lib/WAM/BinaryInfo.d.ts +9 -0
  402. package/lib/WAM/BinaryInfo.d.ts.map +1 -0
  403. package/lib/WAM/BinaryInfo.js +10 -0
  404. package/lib/WAM/BinaryInfo.js.map +1 -0
  405. package/lib/WAM/constants.d.ts +40 -0
  406. package/lib/WAM/constants.d.ts.map +1 -0
  407. package/lib/WAM/constants.js +22853 -0
  408. package/lib/WAM/constants.js.map +1 -0
  409. package/lib/WAM/encode.d.ts +3 -0
  410. package/lib/WAM/encode.d.ts.map +1 -0
  411. package/lib/WAM/encode.js +150 -0
  412. package/lib/WAM/encode.js.map +1 -0
  413. package/lib/WAM/index.d.ts +4 -0
  414. package/lib/WAM/index.d.ts.map +1 -0
  415. package/lib/WAM/index.js +4 -0
  416. package/lib/WAM/index.js.map +1 -0
  417. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts +10 -0
  418. package/lib/WAUSync/Protocols/USyncContactProtocol.d.ts.map +1 -0
  419. package/lib/WAUSync/Protocols/USyncContactProtocol.js +52 -0
  420. package/lib/WAUSync/Protocols/USyncContactProtocol.js.map +1 -0
  421. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts +23 -0
  422. package/lib/WAUSync/Protocols/USyncDeviceProtocol.d.ts.map +1 -0
  423. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js +54 -0
  424. package/lib/WAUSync/Protocols/USyncDeviceProtocol.js.map +1 -0
  425. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts +13 -0
  426. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.d.ts.map +1 -0
  427. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js +27 -0
  428. package/lib/WAUSync/Protocols/USyncDisappearingModeProtocol.js.map +1 -0
  429. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts +13 -0
  430. package/lib/WAUSync/Protocols/USyncStatusProtocol.d.ts.map +1 -0
  431. package/lib/WAUSync/Protocols/USyncStatusProtocol.js +38 -0
  432. package/lib/WAUSync/Protocols/USyncStatusProtocol.js.map +1 -0
  433. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts +10 -0
  434. package/lib/WAUSync/Protocols/USyncUsernameProtocol.d.ts.map +1 -0
  435. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js +25 -0
  436. package/lib/WAUSync/Protocols/USyncUsernameProtocol.js.map +1 -0
  437. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts +26 -0
  438. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.d.ts.map +1 -0
  439. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js +51 -0
  440. package/lib/WAUSync/Protocols/UsyncBotProfileProtocol.js.map +1 -0
  441. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts +10 -0
  442. package/lib/WAUSync/Protocols/UsyncLIDProtocol.d.ts.map +1 -0
  443. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js +29 -0
  444. package/lib/WAUSync/Protocols/UsyncLIDProtocol.js.map +1 -0
  445. package/lib/WAUSync/Protocols/index.d.ts +6 -0
  446. package/lib/WAUSync/Protocols/index.d.ts.map +1 -0
  447. package/lib/WAUSync/Protocols/index.js +6 -0
  448. package/lib/WAUSync/Protocols/index.js.map +1 -0
  449. package/lib/WAUSync/USyncQuery.d.ts +30 -0
  450. package/lib/WAUSync/USyncQuery.d.ts.map +1 -0
  451. package/lib/WAUSync/USyncQuery.js +98 -0
  452. package/lib/WAUSync/USyncQuery.js.map +1 -0
  453. package/lib/WAUSync/USyncUser.d.ts +17 -0
  454. package/lib/WAUSync/USyncUser.d.ts.map +1 -0
  455. package/lib/WAUSync/USyncUser.js +31 -0
  456. package/lib/WAUSync/USyncUser.js.map +1 -0
  457. package/lib/WAUSync/index.d.ts +4 -0
  458. package/lib/WAUSync/index.d.ts.map +1 -0
  459. package/lib/WAUSync/index.js +4 -0
  460. package/lib/WAUSync/index.js.map +1 -0
  461. package/lib/index.d.ts +13 -0
  462. package/lib/index.d.ts.map +1 -0
  463. package/lib/index.js +12 -0
  464. package/lib/index.js.map +1 -0
  465. package/package.json +150 -3
package/README.md CHANGED
@@ -1,3 +1,1838 @@
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
+ > ⚠️ **Experimental:** el carrusel está implementado y probado con tests, pero todavía no lo hemos visto funcionar en un teléfono real. WhatsApp puede cambiar o rechazar estos mensajes.
200
+
201
+ Hasta 10 tarjetas que se deslizan, cada una con su imagen o video, textos y botones.
202
+
203
+ ```js
204
+ await sock.sendCarousel(jid, {
205
+ text: 'Nuestro catálogo',
206
+ footer: 'Yui-Bails',
207
+ cards: [
208
+ {
209
+ image: { url: 'https://example.com/a.jpg' },
210
+ title: 'Plan básico',
211
+ body: 'Ideal para empezar',
212
+ buttons: [{ id: 'comprar_basico', text: 'Comprar' }, { text: 'Ver web', url: 'https://example.com' }]
213
+ },
214
+ { image: bufferDeImagen, title: 'Plan pro', body: 'Todo incluido', buttons: [{ id: 'comprar_pro', text: 'Comprar' }] }
215
+ ]
216
+ })
217
+ ```
218
+
219
+ ### Responder a botones y menús sin complicarte
220
+
221
+ ```js
222
+ // se ejecuta cuando alguien toca el botón o la fila con ese id (string, RegExp o función)
223
+ sock.onButton('comprar_basico', async (msg, reply) => {
224
+ await sock.reply(msg, `Elegiste: ${reply.text}`)
225
+ }, { once: true, onUsed: msg => sock.reply(msg, 'Este menú ya fue usado ✋') }) // solo el primer toque por menú
226
+
227
+ sock.onList(/^fila_/, async (msg, reply) => sock.reply(msg, `Fila ${reply.id}`))
228
+ sock.onReply(r => r.id.startsWith('x_'), handler) // botones y listas a la vez
229
+
230
+ // esperar la siguiente respuesta de la misma persona en el mismo chat
231
+ await sock.reply(msg, '¿Cómo te llamas?')
232
+ const respuesta = await sock.awaitReply(msg, { timeoutMs: 30_000 })
233
+ if (!respuesta) return sock.reply(msg, '⏱️ Se acabó el tiempo')
234
+ ```
235
+
236
+ `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.
237
+
238
+ ### Quitar los botones de un mensaje
239
+
240
+ ```js
241
+ const enviado = await sock.sendButtons(jid, { text: 'Elige', buttons })
242
+ // ...cuando ya lo usaron:
243
+ await sock.disableButtons(enviado, '✅ Opción elegida')
244
+ ```
245
+
246
+ `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`.
247
+
248
+ ### Icono de IA
249
+
250
+ > ⚠️ **Experimental:** el mensaje se envía con la marca de bot, pero no está confirmado que el icono aparezca en todos los teléfonos.
251
+
252
+ ```js
253
+ await sock.sendMessage(jid, { text: 'Hola, soy un bot', ai: true })
254
+ ```
255
+
256
+ 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.
257
+
258
+ ## 📊 Datos reales del bot
259
+
260
+ Nada estimado: son contadores y mediciones de lo que hace tu bot.
261
+
262
+ ```js
263
+ // Estado de la conexión, con un ping real a los servidores de WhatsApp
264
+ const salud = await sock.health()
265
+ // { state: 'open', uptimeMs, connectedMs, reconnects, queueSize,
266
+ // memory: { rssMB, heapUsedMB }, latencyMs: 142 } ← latencyMs se mide en ese momento
267
+ await sock.health({ ping: false }) // sin tocar la red
268
+
269
+ // Contadores desde que arrancó (o desde resetStats)
270
+ const stats = sock.getStats()
271
+ // { since, sent, received, failed, sentByType: { text: 12, image: 2 }, receivedByType: {...} }
272
+
273
+ // Hasta dónde llegó cada mensaje que enviaste
274
+ sock.ev.on('message.status', ({ key, status, userJid }) => {
275
+ // status: 'sent' | 'delivered' | 'read' | 'played' | 'failed'
276
+ // en grupos llega uno por miembro (userJid)
277
+ })
278
+ sock.getMessageStatus(mensaje.key) // último estado conocido
279
+ ```
280
+
281
+ `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.
282
+
283
+ ## 👮 Permisos de grupo (con LID)
284
+
285
+ Entienden los dos tipos de identidad de WhatsApp, así que funcionan aunque el grupo muestre LIDs en lugar de números.
286
+
287
+ ```js
288
+ await sock.isAdmin(grupo, msg) // msg, número, jid o el resultado de getSender
289
+ await sock.isAdmin(grupo, '51910227479')
290
+ await sock.isBotAdmin(grupo)
291
+ const admins = await sock.getAdmins(grupo)
292
+
293
+ await sock.kick(grupo, '51911111111') // números o jids, uno o varios
294
+ await sock.addMembers(grupo, ['51911111111', '51922222222'])
295
+ await sock.promote(grupo, '51911111111')
296
+ await sock.demote(grupo, '51911111111')
297
+ ```
298
+
299
+ 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.
300
+
301
+ ## 🏷️ Menciones automáticas
302
+
303
+ Escribe `@número` en un texto o pie de foto y se convierte en mención real; no hace falta armar `mentions`.
304
+
305
+ ```js
306
+ await sock.sendMessage(grupo, { text: 'Hola @51910227479, bienvenido' })
307
+ ```
308
+
309
+ 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`.
310
+
311
+ ## 🧱 Estabilidad integrada
312
+
313
+ Cosas que casi todos los bots acaban programando a mano, ya resueltas y activas por defecto:
314
+
315
+ - **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.
316
+ - **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.
317
+ - **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.
318
+ - **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).
319
+
320
+ ```js
321
+ const sock = makeWASocket({
322
+ auth: state,
323
+ messageStore: { max: 2000 }, // o false para desactivarlo
324
+ groupMetadataCache: { ttlMs: 10 * 60_000 } // o false para desactivarla
325
+ })
326
+
327
+ const r = await sock.sendSafe(jid, 'hola', undefined, { timeoutMs: 15_000 })
328
+ if (r.status === 'sent') console.log('enviado', r.message.key.id)
329
+ if (r.status === 'unknown') console.log('quizá llegó:', (await r.settled).status)
330
+ ```
331
+
332
+ ## 🛡️ Cola anti-ban (`sendQueue`)
333
+
334
+ 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.
335
+
336
+ ```js
337
+ const sock = makeWASocket({
338
+ auth: state,
339
+ sendQueue: true // o personaliza:
340
+ // sendQueue: { minDelayMs: 1000, maxDelayMs: 3000, perChatIntervalMs: 2000,
341
+ // perChatLimit: { max: 15, windowMs: 60_000 }, typing: true }
342
+ })
343
+
344
+ sock.queue.size // mensajes esperando
345
+ sock.queue.clear() // descarta los que faltan
346
+ sock.sendMessageNow(jid, { text: 'urgente' }) // salta la cola
347
+ ```
348
+
349
+ | Opción | Por defecto | Qué hace |
350
+ |---|---|---|
351
+ | `minDelayMs` / `maxDelayMs` | 800 / 2500 | Pausa aleatoria entre dos envíos |
352
+ | `perChatIntervalMs` | 1500 | Mínimo entre dos mensajes al mismo chat |
353
+ | `perChatLimit` | 20 por 60 s | Pasado el límite, los mensajes esperan |
354
+ | `typing` | `true` | "escribiendo…" antes de los textos |
355
+ | `typingMsPerChar` / `typingMinMs` / `typingMaxMs` | 30 / 500 / 3000 | Duración del "escribiendo…" |
356
+ | `maxQueueSize` | 500 | Con la cola llena, `sendMessage` falla con 429 |
357
+
358
+ Reduce el riesgo de bloqueo, pero no lo elimina: no escribas a números que no te conocen ni hagas spam.
359
+
360
+ ## 📱 Multi-sesión (`makeSessionManager`)
361
+
362
+ 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.
363
+
364
+ ```js
365
+ import { makeSessionManager } from 'yui-bails'
366
+
367
+ const sessions = makeSessionManager({
368
+ authDir: './sesiones',
369
+ config: { printQRInTerminal: false },
370
+ // se llama con cada socket nuevo (también tras reconectar)
371
+ setup: (sock, id) => {
372
+ sock.ev.on('messages.upsert', async ({ messages }) => {
373
+ await sock.reply(messages[0], `Hola desde la sesión ${id}`)
374
+ })
375
+ }
376
+ })
377
+
378
+ sessions.on('session.qr', ({ id, qr }) => console.log(id, 'escanea:', qr))
379
+ sessions.on('session.pairing-code', ({ id, code }) => console.log(id, 'código:', code))
380
+ sessions.on('session.open', ({ id, user }) => console.log(id, 'conectado como', user?.id))
381
+ sessions.on('session.logged-out', ({ id }) => console.log(id, 'cerró sesión'))
382
+
383
+ await sessions.start('ventas') // QR
384
+ await sessions.start('soporte', { pairingNumber: '51910227479' }) // código de vinculación
385
+ await sessions.startAll() // restaura todas las sesiones guardadas al arrancar
386
+
387
+ sessions.get('ventas') // el socket
388
+ sessions.list() // estado de cada sesión
389
+ await sessions.stop('ventas') // cierra pero conserva el login
390
+ await sessions.logout('ventas') // cierra sesión en WhatsApp y borra el login
391
+ await sessions.stopAll()
392
+ ```
393
+
394
+ Los ids solo admiten letras, números, `_`, `-` y `.` (son nombres de carpeta).
395
+
396
+ ## 🖥️ Logs legibles y lectura automática
397
+
398
+ ```js
399
+ const sock = makeWASocket({
400
+ auth: state,
401
+ prettyLogs: true, // una línea por mensaje y por cambio de conexión
402
+ autoRead: true, // marca como leídos los mensajes nuevos
403
+ autoPresence: 'unavailable' // al conectar, no te muestra "en línea"
404
+ })
405
+ ```
406
+
407
+ `prettyLogs` imprime algo así:
408
+
409
+ ```
410
+ 12:30:01 🟢 Conectado a WhatsApp
411
+ 12:30:05 📩 grupo · 51925679896 · Amilcar: .ping
412
+ ```
413
+
414
+ - `autoRead` también acepta `{ groups: false, private: true, delayMs: 1500 }` para elegir dónde leer y esperar un poco antes. No marca como leídos el historial, tus propios mensajes ni los estados.
415
+ - `autoPresence` acepta `'available'` o `'unavailable'`. Con `'unavailable'` WhatsApp te sigue avisando en el teléfono.
416
+ - Todo viene desactivado por defecto.
417
+
418
+ Si quieres que los errores internos se lean en español en vez de JSON, usa el logger legible:
419
+
420
+ ```js
421
+ import makeWASocket, { makePrettyLogger } from 'yui-bails'
422
+
423
+ const sock = makeWASocket({ auth: state, logger: makePrettyLogger({ level: 'info' }) })
424
+ ```
425
+
426
+ Traduce los avisos más comunes (por ejemplo `No session found to decrypt message` pasa a "No pude leer un mensaje de 5731…: falta su clave de cifrado. Pídele que lo envíe otra vez.") y esconde el ruido interno que no necesitas.
427
+
428
+ ## 🎛️ Variables de entorno
429
+
430
+ | Variable | Efecto |
431
+ |---|---|
432
+ | `YUI_BAILS_BUTTONS_FORMAT=buttons` | Cambia el formato de botones a `ButtonsMessage` clásico (ver abajo) |
433
+ | `YUI_BAILS_LOG_LEVEL=info` | Reactiva los logs internos (por defecto: silencio total) |
434
+ | `YUI_BAILS_VERBOSE=1` | Muestra también el ruido de libsignal (desactiva el filtro) |
435
+ | `YUI_BAILS_NO_BANNER=1` | Oculta el banner de arranque |
436
+
437
+ <p align="center">
438
+ <img src="https://user-images.githubusercontent.com/74038190/212284100-561aa473-3905-4a80-b561-0d28506553ee.gif" width="100%" alt="divider" />
439
+ </p>
440
+
441
+ <h2 align="center">📚 Guía de uso</h2>
442
+
443
+ # Disclaimer
444
+ 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.
445
+ 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.
446
+
447
+ 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.
448
+ Use at your own discretion. Do not spam people with this. We discourage any stalkerware, bulk or automated messaging usage.
449
+
450
+ ##
451
+
452
+ - Yui-Bails does not require Selenium or any other browser to be interface with WhatsApp Web, it does so directly using a **WebSocket**.
453
+ - Not running Selenium or Chromium saves you like **half a gig** of ram :/
454
+ - Yui-Bails supports interacting with the multi-device & web versions of WhatsApp.
455
+
456
+ ## 🚀 Cómo agregar Yui-Bails a tu bot, paso a paso
457
+
458
+ Esta guía es para quien nunca lo ha hecho. Funciona en un PC, en un VPS o en Termux (Android).
459
+
460
+ ### 1. Prepara el entorno
461
+
462
+ Necesitas **Node.js 20 o más nuevo**. Compruébalo:
463
+
464
+ ```
465
+ node -v
466
+ ```
467
+
468
+ En Termux se instala con `pkg install nodejs git`.
469
+
470
+ ### 2. Crea la carpeta de tu bot
471
+
472
+ ```
473
+ mkdir mi-bot
474
+ cd mi-bot
475
+ npm init -y
476
+ ```
477
+
478
+ Abre el `package.json` que se creó y añade esta línea dentro, para poder usar `import`:
479
+
480
+ ```json
481
+ "type": "module"
482
+ ```
483
+
484
+ ### 3. Instala Yui-Bails
485
+
486
+ ```
487
+ npm install yui-bails@npm:@yui-bails/yui-bails
488
+ ```
489
+
490
+ El `yui-bails@npm:` deja el nombre corto, así `import ... from 'yui-bails'` funciona. Si prefieres la versión más nueva directamente de GitHub (puede tener cosas sin publicar):
491
+
492
+ ```
493
+ npm install github:AmilcarGit/Yui-Bails
494
+ ```
495
+
496
+ Para actualizar más adelante, repite el mismo comando que usaste.
497
+
498
+ ### 4. Crea `index.js`
499
+
500
+ Cambia `NUMERO` por el número que usará el bot (con código de país, sin `+` ni espacios):
501
+
502
+ ```js
503
+ import makeWASocket, { useMultiFileAuthState, DisconnectReason } from 'yui-bails'
504
+
505
+ const NUMERO = '51999999999'
506
+
507
+ async function iniciar() {
508
+ const { state, saveCreds } = await useMultiFileAuthState('./sesion')
509
+
510
+ const sock = makeWASocket({
511
+ auth: state,
512
+ prettyLogs: true, // logs legibles
513
+ sendQueue: true // cola anti-ban
514
+ })
515
+
516
+ sock.ev.on('creds.update', saveCreds)
517
+
518
+ // primera vez: pide el código para vincular el número
519
+ if (!sock.authState.creds.registered) {
520
+ const codigo = await sock.requestPairingCode(NUMERO)
521
+ console.log('Tu código de vinculación:', codigo)
522
+ }
523
+
524
+ sock.ev.on('connection.update', ({ connection, lastDisconnect }) => {
525
+ if (connection === 'close') {
526
+ const codigo = lastDisconnect?.error?.output?.statusCode
527
+ if (codigo !== DisconnectReason.loggedOut) iniciar() // reconectar
528
+ }
529
+ })
530
+
531
+ sock.ev.on('messages.upsert', async ({ messages, type }) => {
532
+ if (type !== 'notify') return
533
+
534
+ for (const msg of messages) {
535
+ const texto = msg.message?.conversation || msg.message?.extendedTextMessage?.text || ''
536
+ if (texto === '.ping') await sock.reply(msg, '¡pong! 🏓')
537
+ }
538
+ })
539
+ }
540
+
541
+ iniciar()
542
+ ```
543
+
544
+ ### 5. Inicia sesión
545
+
546
+ ```
547
+ node index.js
548
+ ```
549
+
550
+ La primera vez aparece un código de 8 caracteres. En el teléfono del bot abre WhatsApp > Dispositivos vinculados > Vincular un dispositivo > **Vincular con el número de teléfono** y escribe el código. Es lo más cómodo en Termux porque no hay que escanear nada.
551
+
552
+ La sesión queda guardada en la carpeta `sesion`. No la subas a GitHub ni la compartas: quien la tenga controla tu WhatsApp. Las siguientes veces entra solo, sin pedir código.
553
+
554
+ **¿Prefieres QR?** Instala `npm install qrcode-terminal`, quita el bloque de `requestPairingCode` y en `connection.update` añade `if (qr) qrcode.generate(qr, { small: true })`, recibiendo `qr` junto a `connection` y con `import qrcode from 'qrcode-terminal'` arriba.
555
+
556
+ ### 6. Pruébalo
557
+
558
+ Desde **otro** número, escribe `.ping` al número del bot. Debe responder `¡pong! 🏓`.
559
+
560
+ ### Problemas comunes
561
+
562
+ | Síntoma | Qué hacer |
563
+ |---|---|
564
+ | `sock.reply is not a function` o `sock.sendPoll is not a function` | Tienes una versión vieja. Actualiza con el comando del paso 3. |
565
+ | `Cannot use import statement` | Falta `"type": "module"` en el `package.json`. |
566
+ | `rate-overlimit` | Estás pidiendo demasiado a WhatsApp. Activa `sendQueue: true` y espera unos minutos. |
567
+ | `No session found to decrypt message` | No es tu bot: falta la clave de un miembro. Pídele que escriba de nuevo. |
568
+ | Se desconecta cada tanto | Es normal; el código del paso 4 reconecta solo. Si sale `loggedOut`, borra la carpeta `sesion` y vincula de nuevo. |
569
+
570
+ Para ver un bot completo con comandos, mira [BaseBot](https://github.com/AmilcarGit/BaseBot).
571
+
572
+ ## Example
573
+
574
+ Do check out & run [example.ts](Example/example.ts) to see an example usage of the library.
575
+ The script covers most common use cases.
576
+ To run the example script, download or clone the repo and then type the following in a terminal:
577
+ 1. ``` cd path/to/Yui-Bails ```
578
+ 2. ``` yarn ```
579
+ 3. ``` yarn example ```
580
+
581
+ ## Install
582
+
583
+ Use the stable version (npm):
584
+ ```
585
+ npm install yui-bails@npm:@yui-bails/yui-bails
586
+ ```
587
+ The `yui-bails@npm:` part keeps the short name, so `import ... from 'yui-bails'` works.
588
+
589
+ Use the edge version (no guarantee of stability, but latest fixes + features)
590
+ ```
591
+ yarn add github:AmilcarGit/Yui-Bails
592
+ ```
593
+
594
+ Then import your code using:
595
+ ```ts
596
+ import makeWASocket from 'yui-bails'
597
+ ```
598
+
599
+ # Index
600
+
601
+ - [Connecting Account](#connecting-account)
602
+ - [Connect with QR-CODE](#starting-socket-with-qr-code)
603
+ - [Connect with Pairing Code](#starting-socket-with-pairing-code)
604
+ - [Receive Full History](#receive-full-history)
605
+ - [Important Notes About Socket Config](#important-notes-about-socket-config)
606
+ - [Caching Group Metadata (Recommended)](#caching-group-metadata-recommended)
607
+ - [Improve Retry System & Decrypt Poll Votes](#improve-retry-system--decrypt-poll-votes)
608
+ - [Receive Notifications in Whatsapp App](#receive-notifications-in-whatsapp-app)
609
+
610
+ - [Save Auth Info](#saving--restoring-sessions)
611
+ - [Handling Events](#handling-events)
612
+ - [Example to Start](#example-to-start)
613
+ - [Decrypt Poll Votes](#decrypt-poll-votes)
614
+ - [Summary of Events on First Connection](#summary-of-events-on-first-connection)
615
+ - [Implementing a Data Store](#implementing-a-data-store)
616
+ - [Whatsapp IDs Explain](#whatsapp-ids-explain)
617
+ - [Utility Functions](#utility-functions)
618
+ - [Sending Messages](#sending-messages)
619
+ - [Non-Media Messages](#non-media-messages)
620
+ - [Text Message](#text-message)
621
+ - [Quote Message](#quote-message-works-with-all-types)
622
+ - [Mention User](#mention-user-works-with-most-types)
623
+ - [Forward Messages](#forward-messages)
624
+ - [Location Message](#location-message)
625
+ - [Contact Message](#contact-message)
626
+ - [Reaction Message](#reaction-message)
627
+ - [Pin Message](#pin-message)
628
+ - [Poll Message](#poll-message)
629
+ - [Sending with Link Preview](#sending-messages-with-link-previews)
630
+ - [Media Messages](#media-messages)
631
+ - [Gif Message](#gif-message)
632
+ - [Video Message](#video-message)
633
+ - [Audio Message](#audio-message)
634
+ - [Image Message](#image-message)
635
+ - [ViewOnce Message](#view-once-message)
636
+ - [Modify Messages](#modify-messages)
637
+ - [Delete Messages (for everyone)](#deleting-messages-for-everyone)
638
+ - [Edit Messages](#editing-messages)
639
+ - [Manipulating Media Messages](#manipulating-media-messages)
640
+ - [Thumbnail in Media Messages](#thumbnail-in-media-messages)
641
+ - [Downloading Media Messages](#downloading-media-messages)
642
+ - [Re-upload Media Message to Whatsapp](#re-upload-media-message-to-whatsapp)
643
+ - [Reject Call](#reject-call)
644
+ - [Send States in Chat](#send-states-in-chat)
645
+ - [Reading Messages](#reading-messages)
646
+ - [Update Presence](#update-presence)
647
+ - [Modifying Chats](#modifying-chats)
648
+ - [Archive a Chat](#archive-a-chat)
649
+ - [Mute/Unmute a Chat](#muteunmute-a-chat)
650
+ - [Mark a Chat Read/Unread](#mark-a-chat-readunread)
651
+ - [Delete a Message for Me](#delete-a-message-for-me)
652
+ - [Delete a Chat](#delete-a-chat)
653
+ - [Star/Unstar a Message](#starunstar-a-message)
654
+ - [Disappearing Messages](#disappearing-messages)
655
+ - [User Querys](#user-querys)
656
+ - [Check If ID Exists in Whatsapp](#check-if-id-exists-in-whatsapp)
657
+ - [Query Chat History (groups too)](#query-chat-history-groups-too)
658
+ - [Fetch Status](#fetch-status)
659
+ - [Fetch Profile Picture (groups too)](#fetch-profile-picture-groups-too)
660
+ - [Fetch Bussines Profile (such as description or category)](#fetch-bussines-profile-such-as-description-or-category)
661
+ - [Fetch Someone's Presence (if they're typing or online)](#fetch-someones-presence-if-theyre-typing-or-online)
662
+ - [Change Profile](#change-profile)
663
+ - [Change Profile Status](#change-profile-status)
664
+ - [Change Profile Name](#change-profile-name)
665
+ - [Change Display Picture (groups too)](#change-display-picture-groups-too)
666
+ - [Remove display picture (groups too)](#remove-display-picture-groups-too)
667
+ - [Groups](#groups)
668
+ - [Create a Group](#create-a-group)
669
+ - [Add/Remove or Demote/Promote](#addremove-or-demotepromote)
670
+ - [Change Subject (name)](#change-subject-name)
671
+ - [Change Description](#change-description)
672
+ - [Change Settings](#change-settings)
673
+ - [Leave a Group](#leave-a-group)
674
+ - [Get Invite Code](#get-invite-code)
675
+ - [Revoke Invite Code](#revoke-invite-code)
676
+ - [Join Using Invitation Code](#join-using-invitation-code)
677
+ - [Get Group Info by Invite Code](#get-group-info-by-invite-code)
678
+ - [Query Metadata (participants, name, description...)](#query-metadata-participants-name-description)
679
+ - [Join using groupInviteMessage](#join-using-groupinvitemessage)
680
+ - [Get Request Join List](#get-request-join-list)
681
+ - [Approve/Reject Request Join](#approvereject-request-join)
682
+ - [Get All Participating Groups Metadata](#get-all-participating-groups-metadata)
683
+ - [Toggle Ephemeral](#toggle-ephemeral)
684
+ - [Change Add Mode](#change-add-mode)
685
+ - [Privacy](#privacy)
686
+ - [Block/Unblock User](#blockunblock-user)
687
+ - [Get Privacy Settings](#get-privacy-settings)
688
+ - [Get BlockList](#get-blocklist)
689
+ - [Update LastSeen Privacy](#update-lastseen-privacy)
690
+ - [Update Online Privacy](#update-online-privacy)
691
+ - [Update Profile Picture Privacy](#update-profile-picture-privacy)
692
+ - [Update Status Privacy](#update-status-privacy)
693
+ - [Update Read Receipts Privacy](#update-read-receipts-privacy)
694
+ - [Update Groups Add Privacy](#update-groups-add-privacy)
695
+ - [Update Default Disappearing Mode](#update-default-disappearing-mode)
696
+ - [Broadcast Lists & Stories](#broadcast-lists--stories)
697
+ - [Send Broadcast & Stories](#send-broadcast--stories)
698
+ - [Query a Broadcast List's Recipients & Name](#query-a-broadcast-lists-recipients--name)
699
+ - [Writing Custom Functionality](#writing-custom-functionality)
700
+ - [Enabling Debug Level in Yui-Bails Logs](#enabling-debug-level-in-yui-bails-logs)
701
+ - [How Whatsapp Communicate With Us](#how-whatsapp-communicate-with-us)
702
+ - [Register a Callback for Websocket Events](#register-a-callback-for-websocket-events)
703
+
704
+ ## Connecting Account
705
+
706
+ 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.
707
+
708
+ > [!NOTE]
709
+ > **[Here](#example-to-start) is a simple example of event handling**
710
+
711
+ > [!TIP]
712
+ > **You can see all supported socket configs in the [SocketConfig type alias](src/Types) (Recommended)**
713
+
714
+ ### Starting socket with **QR-CODE**
715
+
716
+ > [!TIP]
717
+ > 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)**
718
+
719
+ ```ts
720
+ import makeWASocket from 'yui-bails'
721
+
722
+ const sock = makeWASocket({
723
+ // can provide additional config here
724
+ browser: Browsers.ubuntu('My App'),
725
+ printQRInTerminal: true
726
+ })
727
+ ```
728
+
729
+ 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!
730
+
731
+ ### Starting socket with **Pairing Code**
732
+
733
+
734
+ > [!IMPORTANT]
735
+ > 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)
736
+
737
+ The phone number can't have `+` or `()` or `-`, only numbers, you must provide country code
738
+
739
+ ```ts
740
+ import makeWASocket from 'yui-bails'
741
+
742
+ const sock = makeWASocket({
743
+ // can provide additional config here
744
+ printQRInTerminal: false //need to be false
745
+ })
746
+
747
+ if (!sock.authState.creds.registered) {
748
+ const number = 'XXXXXXXXXXX'
749
+ const code = await sock.requestPairingCode(number)
750
+ console.log(code)
751
+ }
752
+ ```
753
+
754
+ ### Receive Full History
755
+
756
+ 1. Set `syncFullHistory` as `true`
757
+ 2. Yui-Bails, by default, use chrome browser config
758
+ - If you'd like to emulate a desktop connection (and receive more message history), this browser setting to your Socket config:
759
+
760
+ ```ts
761
+ const sock = makeWASocket({
762
+ ...otherOpts,
763
+ // can use Windows, Ubuntu here too
764
+ browser: Browsers.macOS('Desktop'),
765
+ syncFullHistory: true
766
+ })
767
+ ```
768
+
769
+ ## Important Notes About Socket Config
770
+
771
+ ### WhatsApp Web Version (fix for `405` / `428` on pairing)
772
+ 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.
773
+
774
+ 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.
775
+
776
+ ```ts
777
+ // nothing to do: no `version` means "always the live one"
778
+ const sock = makeWASocket({ auth: state })
779
+ ```
780
+
781
+ - 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`.
782
+ - If WA can't be reached, the connection goes ahead with the version bundled in the library.
783
+ - Passing `version` pins it and turns the sync off. To pin a fallback but still prefer the live version, set `syncWaWebVersion: true` as well:
784
+ ```ts
785
+ const sock = makeWASocket({
786
+ auth: state,
787
+ version: [2, 3000, 1035194821], // used only if WA can't be reached
788
+ syncWaWebVersion: true
789
+ })
790
+ ```
791
+ - To opt out entirely, set `syncWaWebVersion: false`.
792
+
793
+ ### Caching Group Metadata (Recommended)
794
+ - If you use yui-bails for groups, we recommend you to set `cachedGroupMetadata` in socket config, you need to implement a cache like this:
795
+
796
+ ```ts
797
+ const groupCache = new NodeCache({stdTTL: 5 * 60, useClones: false})
798
+
799
+ const sock = makeWASocket({
800
+ cachedGroupMetadata: async (jid) => groupCache.get(jid)
801
+ })
802
+
803
+ sock.ev.on('groups.update', async ([event]) => {
804
+ const metadata = await sock.groupMetadata(event.id)
805
+ groupCache.set(event.id, metadata)
806
+ })
807
+
808
+ sock.ev.on('group-participants.update', async (event) => {
809
+ const metadata = await sock.groupMetadata(event.id)
810
+ groupCache.set(event.id, metadata)
811
+ })
812
+ ```
813
+
814
+ ### Improve Retry System & Decrypt Poll Votes
815
+ - 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:
816
+ ```ts
817
+ const sock = makeWASocket({
818
+ getMessage: async (key) => await getMessageFromStore(key)
819
+ })
820
+ ```
821
+
822
+ ### Receive Notifications in Whatsapp App
823
+ - If you want to receive notifications in whatsapp app, set `markOnlineOnConnect` to `false`
824
+ ```ts
825
+ const sock = makeWASocket({
826
+ markOnlineOnConnect: false
827
+ })
828
+ ```
829
+ ## Saving & Restoring Sessions
830
+
831
+ You obviously don't want to keep scanning the QR code every time you want to connect.
832
+
833
+ So, you can load the credentials to log back in:
834
+ ```ts
835
+ import makeWASocket, { useMultiFileAuthState } from 'yui-bails'
836
+
837
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_yui')
838
+
839
+ // will use the given state to connect
840
+ // so if valid credentials are available -- it'll connect without QR
841
+ const sock = makeWASocket({ auth: state })
842
+
843
+ // this will be called as soon as the credentials are updated
844
+ sock.ev.on('creds.update', saveCreds)
845
+ ```
846
+
847
+ > [!IMPORTANT]
848
+ > `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.
849
+
850
+ > [!NOTE]
851
+ > 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.
852
+
853
+ ## Handling Events
854
+
855
+ - Yui-Bails uses the EventEmitter syntax for events.
856
+ They're all nicely typed up, so you shouldn't have any issues with an Intellisense editor like VS Code.
857
+
858
+ > [!IMPORTANT]
859
+ > **The events are in the [YuiEventMap type alias](src/Types)**, it's important you see all events
860
+
861
+ You can listen to these events like this:
862
+ ```ts
863
+ const sock = makeWASocket()
864
+ sock.ev.on('messages.upsert', ({ messages }) => {
865
+ console.log('got messages', messages)
866
+ })
867
+ ```
868
+
869
+ ### Example to Start
870
+
871
+ > [!NOTE]
872
+ > This example includes basic auth storage too
873
+
874
+ > [!NOTE]
875
+ > For reliable serialization of the authentication state, especially when storing as JSON, always use the BufferJSON utility.
876
+
877
+ ```ts
878
+ import makeWASocket, { DisconnectReason, useMultiFileAuthState } from 'yui-bails'
879
+ import { Boom } from '@hapi/boom'
880
+
881
+ async function connectToWhatsApp () {
882
+ const { state, saveCreds } = await useMultiFileAuthState('auth_info_yui')
883
+ const sock = makeWASocket({
884
+ // can provide additional config here
885
+ auth: state,
886
+ printQRInTerminal: true
887
+ })
888
+ sock.ev.on('connection.update', (update) => {
889
+ const { connection, lastDisconnect } = update
890
+ if(connection === 'close') {
891
+ const shouldReconnect = (lastDisconnect.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
892
+ console.log('connection closed due to ', lastDisconnect.error, ', reconnecting ', shouldReconnect)
893
+ // reconnect if not logged out
894
+ if(shouldReconnect) {
895
+ connectToWhatsApp()
896
+ }
897
+ } else if(connection === 'open') {
898
+ console.log('opened connection')
899
+ }
900
+ })
901
+ sock.ev.on('messages.upsert', event => {
902
+ for (const m of event.messages) {
903
+ console.log(JSON.stringify(m, undefined, 2))
904
+
905
+ console.log('replying to', m.key.remoteJid)
906
+ await sock.sendMessage(m.key.remoteJid!, { text: 'Hello Word' })
907
+ }
908
+ })
909
+
910
+ // to storage creds (session info) when it updates
911
+ sock.ev.on('creds.update', saveCreds)
912
+ }
913
+ // run in main file
914
+ connectToWhatsApp()
915
+ ```
916
+
917
+ > [!IMPORTANT]
918
+ > In `messages.upsert` it's recommended to use a loop like `for (const message of event.messages)` to handle all messages in array
919
+
920
+ ### Decrypt Poll Votes
921
+
922
+ - By default poll votes are encrypted and handled in `messages.update`
923
+ - That's a simple example
924
+ ```ts
925
+ sock.ev.on('messages.update', event => {
926
+ for(const { key, update } of event) {
927
+ if(update.pollUpdates) {
928
+ const pollCreation = await getMessage(key)
929
+ if(pollCreation) {
930
+ console.log(
931
+ 'got poll update, aggregation: ',
932
+ getAggregateVotesInPollMessage({
933
+ message: pollCreation,
934
+ pollUpdates: update.pollUpdates,
935
+ })
936
+ )
937
+ }
938
+ }
939
+ }
940
+ })
941
+ ```
942
+
943
+ - `getMessage` is a [store](#implementing-a-data-store) implementation (in your end)
944
+
945
+ ### Summary of Events on First Connection
946
+
947
+ 1. When you connect first time, `connection.update` will be fired requesting you to restart sock
948
+ 2. Then, history messages will be received in `messaging.history-set`
949
+
950
+ ## Implementing a Data Store
951
+
952
+ - 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.
953
+
954
+ > [!IMPORTANT]
955
+ > I highly recommend building your own data store, as storing someone's entire chat history in memory is a terrible waste of RAM.
956
+
957
+ It can be used as follows:
958
+
959
+ ```ts
960
+ import makeWASocket, { makeInMemoryStore } from 'yui-bails'
961
+ // the store maintains the data of the WA connection in memory
962
+ // can be written out to a file & read from it
963
+ const store = makeInMemoryStore({ })
964
+ // can be read from a file
965
+ store.readFromFile('./yui_store.json')
966
+ // saves the state to a file every 10s
967
+ setInterval(() => {
968
+ store.writeToFile('./yui_store.json')
969
+ }, 10_000)
970
+
971
+ const sock = makeWASocket({ })
972
+ // will listen from this socket
973
+ // the store can listen from a new socket once the current socket outlives its lifetime
974
+ store.bind(sock.ev)
975
+
976
+ sock.ev.on('chats.upsert', () => {
977
+ // can use 'store.chats' however you want, even after the socket dies out
978
+ // 'chats' => a KeyedDB instance
979
+ console.log('got chats', store.chats.all())
980
+ })
981
+
982
+ sock.ev.on('contacts.upsert', () => {
983
+ console.log('got contacts', Object.values(store.contacts))
984
+ })
985
+
986
+ ```
987
+
988
+ The store also provides some simple functions such as `loadMessages` that utilize the store to speed up data retrieval.
989
+
990
+ ## Whatsapp IDs Explain
991
+
992
+ - `id` is the WhatsApp ID, called `jid` too, of the person or group you're sending the message to.
993
+ - It must be in the format ```[country code][phone number]@s.whatsapp.net```
994
+ - Example for people: ```+19999999999@s.whatsapp.net```.
995
+ - For groups, it must be in the format ``` 123456789-123345@g.us ```.
996
+ - For broadcast lists, it's `[timestamp of creation]@broadcast`.
997
+ - For stories, the ID is `status@broadcast`.
998
+
999
+ ## Utility Functions
1000
+
1001
+ - `getContentType`, returns the content type for any message
1002
+ - `getDevice`, returns the device from message
1003
+ - `makeCacheableSignalKeyStore`, make auth store more fast
1004
+ - `downloadContentFromMessage`, download content from any message
1005
+
1006
+ ## Sending Messages
1007
+
1008
+ - Send all types of messages with a single function
1009
+ - **In the [AnyMessageContent type alias](src/Types) you can see all message contents supported, like text message**
1010
+ - **In the [MiscMessageGenerationOptions type alias](src/Types) you can see all options supported, like quote message**
1011
+
1012
+ ```ts
1013
+ const jid: string
1014
+ const content: AnyMessageContent
1015
+ const options: MiscMessageGenerationOptions
1016
+
1017
+ sock.sendMessage(jid, content, options)
1018
+ ```
1019
+
1020
+ ### Non-Media Messages
1021
+
1022
+ #### Text Message
1023
+ ```ts
1024
+ await sock.sendMessage(jid, { text: 'hello word' })
1025
+ ```
1026
+
1027
+ #### Quote Message (works with all types)
1028
+ ```ts
1029
+ await sock.sendMessage(jid, { text: 'hello word' }, { quoted: message })
1030
+ ```
1031
+
1032
+ #### Mention User (works with most types)
1033
+ - @number is to mention in text, it's optional
1034
+ ```ts
1035
+ await sock.sendMessage(
1036
+ jid,
1037
+ {
1038
+ text: '@12345678901',
1039
+ mentions: ['12345678901@s.whatsapp.net']
1040
+ }
1041
+ )
1042
+ ```
1043
+
1044
+ #### Forward Messages
1045
+ - You need to have message object, can be retrieved from [store](#implementing-a-data-store) or use a [message](src/Types) object
1046
+ ```ts
1047
+ const msg = getMessageFromStore() // implement this on your end
1048
+ await sock.sendMessage(jid, { forward: msg }) // WA forward the message!
1049
+ ```
1050
+
1051
+ #### Location Message
1052
+ ```ts
1053
+ await sock.sendMessage(
1054
+ jid,
1055
+ {
1056
+ location: {
1057
+ degreesLatitude: 24.121231,
1058
+ degreesLongitude: 55.1121221
1059
+ }
1060
+ }
1061
+ )
1062
+ ```
1063
+ #### Contact Message
1064
+ ```ts
1065
+ const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
1066
+ + 'VERSION:3.0\n'
1067
+ + 'FN:Jeff Singh\n' // full name
1068
+ + 'ORG:Ashoka Uni;\n' // the organization of the contact
1069
+ + 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890\n' // WhatsApp ID + phone number
1070
+ + 'END:VCARD'
1071
+
1072
+ await sock.sendMessage(
1073
+ id,
1074
+ {
1075
+ contacts: {
1076
+ displayName: 'Jeff',
1077
+ contacts: [{ vcard }]
1078
+ }
1079
+ }
1080
+ )
1081
+ ```
1082
+
1083
+ #### Reaction Message
1084
+ - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](src/Types) object
1085
+ ```ts
1086
+ await sock.sendMessage(
1087
+ jid,
1088
+ {
1089
+ react: {
1090
+ text: '💖', // use an empty string to remove the reaction
1091
+ key: message.key
1092
+ }
1093
+ }
1094
+ )
1095
+ ```
1096
+
1097
+ #### Pin Message
1098
+ - You need to pass the key of message, you can retrieve from [store](#implementing-a-data-store) or use a [key](src/Types) object
1099
+
1100
+ - Time can be:
1101
+
1102
+ | Time | Seconds |
1103
+ |-------|----------------|
1104
+ | 24h | 86.400 |
1105
+ | 7d | 604.800 |
1106
+ | 30d | 2.592.000 |
1107
+
1108
+ ```ts
1109
+ await sock.sendMessage(
1110
+ jid,
1111
+ {
1112
+ pin: {
1113
+ type: 1, // 0 to remove
1114
+ time: 86400
1115
+ key: message.key
1116
+ }
1117
+ }
1118
+ )
1119
+ ```
1120
+
1121
+ #### Poll Message
1122
+ ```ts
1123
+ await sock.sendMessage(
1124
+ jid,
1125
+ {
1126
+ poll: {
1127
+ name: 'My Poll',
1128
+ values: ['Option 1', 'Option 2', ...],
1129
+ selectableCount: 1,
1130
+ toAnnouncementGroup: false // or true
1131
+ }
1132
+ }
1133
+ )
1134
+ ```
1135
+
1136
+ ### Sending Messages with Link Previews
1137
+
1138
+ 1. By default, wa does not have link generation when sent from the web
1139
+ 2. Yui-Bails has a function to generate the content for these link previews
1140
+ 3. To enable this function's usage, add `link-preview-js` as a dependency to your project with `yarn add link-preview-js`
1141
+ 4. Send a link:
1142
+ ```ts
1143
+ await sock.sendMessage(
1144
+ jid,
1145
+ {
1146
+ text: 'Hi, this was sent using https://github.com/AmilcarGit/Yui-Bails'
1147
+ }
1148
+ )
1149
+ ```
1150
+
1151
+ ### Media Messages
1152
+
1153
+ Sending media (video, stickers, images) is easier & more efficient than ever.
1154
+
1155
+ > [!NOTE]
1156
+ > 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)
1157
+
1158
+ - When specifying a media url, Yui-Bails never loads the entire buffer into memory; it even encrypts the media as a readable stream.
1159
+
1160
+ > [!TIP]
1161
+ > It's recommended to use Stream or Url to save memory
1162
+
1163
+ #### Gif Message
1164
+ - Whatsapp doesn't support `.gif` files, that's why we send gifs as common `.mp4` video with `gifPlayback` flag
1165
+ ```ts
1166
+ await sock.sendMessage(
1167
+ jid,
1168
+ {
1169
+ video: fs.readFileSync('Media/ma_gif.mp4'),
1170
+ caption: 'hello word',
1171
+ gifPlayback: true
1172
+ }
1173
+ )
1174
+ ```
1175
+
1176
+ #### Video Message
1177
+ ```ts
1178
+ await sock.sendMessage(
1179
+ id,
1180
+ {
1181
+ video: {
1182
+ url: './Media/ma_gif.mp4'
1183
+ },
1184
+ caption: 'hello word',
1185
+ ptv: false // if set to true, will send as a `video note`
1186
+ }
1187
+ )
1188
+ ```
1189
+
1190
+ #### Audio Message
1191
+ - To audio message work in all devices you need to convert with some tool like `ffmpeg` with this flags:
1192
+ ```bash
1193
+ codec: libopus //ogg file
1194
+ ac: 1 //one channel
1195
+ avoid_negative_ts
1196
+ make_zero
1197
+ ```
1198
+ - Example:
1199
+ ```bash
1200
+ ffmpeg -i input.mp4 -avoid_negative_ts make_zero -ac 1 output.ogg
1201
+ ```
1202
+ ```ts
1203
+ await sock.sendMessage(
1204
+ jid,
1205
+ {
1206
+ audio: {
1207
+ url: './Media/audio.mp3'
1208
+ },
1209
+ mimetype: 'audio/mp4'
1210
+ }
1211
+ )
1212
+ ```
1213
+
1214
+ #### Image Message
1215
+ ```ts
1216
+ await sock.sendMessage(
1217
+ id,
1218
+ {
1219
+ image: {
1220
+ url: './Media/ma_img.png'
1221
+ },
1222
+ caption: 'hello word'
1223
+ }
1224
+ )
1225
+ ```
1226
+
1227
+ #### View Once Message
1228
+
1229
+ - You can send all messages above as `viewOnce`, you only need to pass `viewOnce: true` in content object
1230
+
1231
+ ```ts
1232
+ await sock.sendMessage(
1233
+ id,
1234
+ {
1235
+ image: {
1236
+ url: './Media/ma_img.png'
1237
+ },
1238
+ viewOnce: true, //works with video, audio too
1239
+ caption: 'hello word'
1240
+ }
1241
+ )
1242
+ ```
1243
+
1244
+ ## Modify Messages
1245
+
1246
+ ### Deleting Messages (for everyone)
1247
+
1248
+ ```ts
1249
+ const msg = await sock.sendMessage(jid, { text: 'hello word' })
1250
+ await sock.sendMessage(jid, { delete: msg.key })
1251
+ ```
1252
+
1253
+ **Note:** deleting for oneself is supported via `chatModify`, see in [this section](#modifying-chats)
1254
+
1255
+ ### Editing Messages
1256
+
1257
+ - You can pass all editable contents here
1258
+ ```ts
1259
+ await sock.sendMessage(jid, {
1260
+ text: 'updated text goes here',
1261
+ edit: response.key,
1262
+ });
1263
+ ```
1264
+
1265
+ ## Manipulating Media Messages
1266
+
1267
+ ### Thumbnail in Media Messages
1268
+ - 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`.
1269
+ - Thumbnails for videos can also be generated automatically, though, you need to have `ffmpeg` installed on your system.
1270
+
1271
+ ### Downloading Media Messages
1272
+
1273
+ If you want to save the media you received
1274
+ ```ts
1275
+ import { createWriteStream } from 'fs'
1276
+ import { downloadMediaMessage, getContentType } from 'yui-bails'
1277
+
1278
+ sock.ev.on('messages.upsert', async ({ [m] }) => {
1279
+ if (!m.message) return // if there is no text or media message
1280
+ const messageType = getContentType(m) // get what type of message it is (text, image, video...)
1281
+
1282
+ // if the message is an image
1283
+ if (messageType === 'imageMessage') {
1284
+ // download the message
1285
+ const stream = await downloadMediaMessage(
1286
+ m,
1287
+ 'stream', // can be 'buffer' too
1288
+ { },
1289
+ {
1290
+ logger,
1291
+ // pass this so that yui-bails can request a reupload of media
1292
+ // that has been deleted
1293
+ reuploadRequest: sock.updateMediaMessage
1294
+ }
1295
+ )
1296
+ // save to file
1297
+ const writeStream = createWriteStream('./my-download.jpeg')
1298
+ stream.pipe(writeStream)
1299
+ }
1300
+ }
1301
+ ```
1302
+
1303
+ ### Re-upload Media Message to Whatsapp
1304
+
1305
+ - 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:
1306
+ ```ts
1307
+ await sock.updateMediaMessage(msg)
1308
+ ```
1309
+
1310
+ ## Reject Call
1311
+
1312
+ - You can obtain `callId` and `callFrom` from `call` event
1313
+
1314
+ ```ts
1315
+ await sock.rejectCall(callId, callFrom)
1316
+ ```
1317
+
1318
+ ## Send States in Chat
1319
+
1320
+ ### Reading Messages
1321
+ - A set of message [keys](src/Types) must be explicitly marked read now.
1322
+ - You cannot mark an entire 'chat' read as it were with Yui-Bails Web.
1323
+ This means you have to keep track of unread messages.
1324
+
1325
+ ```ts
1326
+ const key: WAMessageKey
1327
+ // can pass multiple keys to read multiple messages as well
1328
+ await sock.readMessages([key])
1329
+ ```
1330
+
1331
+ The message ID is the unique identifier of the message that you are marking as read.
1332
+ On a `WAMessage`, the `messageID` can be accessed using ```messageID = message.key.id```.
1333
+
1334
+ ### Update Presence
1335
+
1336
+ - ``` presence ``` can be one of the values in the [WAPresence type alias](src/Types)
1337
+ - The presence expires after about 10 seconds.
1338
+ - This lets the person/group with `jid` know whether you're online, offline, typing etc.
1339
+
1340
+ ```ts
1341
+ await sock.sendPresenceUpdate('available', jid)
1342
+ ```
1343
+
1344
+ > [!NOTE]
1345
+ > 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')`
1346
+
1347
+ ## Modifying Chats
1348
+
1349
+ WA uses an encrypted form of communication to send chat/app updates. This has been implemented mostly and you can send the following updates:
1350
+
1351
+ > [!IMPORTANT]
1352
+ > 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.
1353
+
1354
+ ### Archive a Chat
1355
+ ```ts
1356
+ const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
1357
+ await sock.chatModify({ archive: true, lastMessages: [lastMsgInChat] }, jid)
1358
+ ```
1359
+ ### Mute/Unmute a Chat
1360
+
1361
+ - Supported times:
1362
+
1363
+ | Time | Miliseconds |
1364
+ |-------|-----------------|
1365
+ | Remove | null |
1366
+ | 8h | 86.400.000 |
1367
+ | 7d | 604.800.000 |
1368
+
1369
+ ```ts
1370
+ // mute for 8 hours
1371
+ await sock.chatModify({ mute: 8 * 60 * 60 * 1000 }, jid)
1372
+ // unmute
1373
+ await sock.chatModify({ mute: null }, jid)
1374
+ ```
1375
+ ### Mark a Chat Read/Unread
1376
+ ```ts
1377
+ const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
1378
+ // mark it unread
1379
+ await sock.chatModify({ markRead: false, lastMessages: [lastMsgInChat] }, jid)
1380
+ ```
1381
+
1382
+ ### Delete a Message for Me
1383
+ ```ts
1384
+ await sock.chatModify(
1385
+ {
1386
+ clear: {
1387
+ messages: [
1388
+ {
1389
+ id: 'ATWYHDNNWU81732J',
1390
+ fromMe: true,
1391
+ timestamp: '1654823909'
1392
+ }
1393
+ ]
1394
+ }
1395
+ },
1396
+ jid
1397
+ )
1398
+
1399
+ ```
1400
+ ### Delete a Chat
1401
+ ```ts
1402
+ const lastMsgInChat = await getLastMessageInChat(jid) // implement this on your end
1403
+ await sock.chatModify({
1404
+ delete: true,
1405
+ lastMessages: [
1406
+ {
1407
+ key: lastMsgInChat.key,
1408
+ messageTimestamp: lastMsgInChat.messageTimestamp
1409
+ }
1410
+ ]
1411
+ },
1412
+ jid
1413
+ )
1414
+ ```
1415
+ ### Pin/Unpin a Chat
1416
+ ```ts
1417
+ await sock.chatModify({
1418
+ pin: true // or `false` to unpin
1419
+ },
1420
+ jid
1421
+ )
1422
+ ```
1423
+ ### Star/Unstar a Message
1424
+ ```ts
1425
+ await sock.chatModify({
1426
+ star: {
1427
+ messages: [
1428
+ {
1429
+ id: 'messageID',
1430
+ fromMe: true // or `false`
1431
+ }
1432
+ ],
1433
+ star: true // - true: Star Message; false: Unstar Message
1434
+ }
1435
+ },
1436
+ jid
1437
+ )
1438
+ ```
1439
+
1440
+ ### Disappearing Messages
1441
+
1442
+ - Ephemeral can be:
1443
+
1444
+ | Time | Seconds |
1445
+ |-------|----------------|
1446
+ | Remove | 0 |
1447
+ | 24h | 86.400 |
1448
+ | 7d | 604.800 |
1449
+ | 90d | 7.776.000 |
1450
+
1451
+ - You need to pass in **Seconds**, default is 7 days
1452
+
1453
+ ```ts
1454
+ // turn on disappearing messages
1455
+ await sock.sendMessage(
1456
+ jid,
1457
+ // this is 1 week in seconds -- how long you want messages to appear for
1458
+ { disappearingMessagesInChat: WA_DEFAULT_EPHEMERAL }
1459
+ )
1460
+
1461
+ // will send as a disappearing message
1462
+ await sock.sendMessage(jid, { text: 'hello' }, { ephemeralExpiration: WA_DEFAULT_EPHEMERAL })
1463
+
1464
+ // turn off disappearing messages
1465
+ await sock.sendMessage(
1466
+ jid,
1467
+ { disappearingMessagesInChat: false }
1468
+ )
1469
+ ```
1470
+
1471
+ ## User Querys
1472
+
1473
+ ### Check If ID Exists in Whatsapp
1474
+ ```ts
1475
+ const [result] = await sock.onWhatsApp(jid)
1476
+ if (result.exists) console.log (`${jid} exists on WhatsApp, as jid: ${result.jid}`)
1477
+ ```
1478
+
1479
+ ### Query Chat History (groups too)
1480
+
1481
+ - You need to have oldest message in chat
1482
+ ```ts
1483
+ const msg = await getOldestMessageInChat(jid) // implement this on your end
1484
+ await sock.fetchMessageHistory(
1485
+ 50, //quantity (max: 50 per query)
1486
+ msg.key,
1487
+ msg.messageTimestamp
1488
+ )
1489
+ ```
1490
+ - Messages will be received in `messaging.history-set` event
1491
+
1492
+ ### Fetch Status
1493
+ ```ts
1494
+ const status = await sock.fetchStatus(jid)
1495
+ console.log('status: ' + status)
1496
+ ```
1497
+
1498
+ ### Fetch Profile Picture (groups too)
1499
+ - To get the display picture of some person/group
1500
+ ```ts
1501
+ // for low res picture
1502
+ const ppUrl = await sock.profilePictureUrl(jid)
1503
+ console.log(ppUrl)
1504
+
1505
+ // for high res picture
1506
+ const ppUrl = await sock.profilePictureUrl(jid, 'image')
1507
+ ```
1508
+
1509
+ ### Fetch Bussines Profile (such as description or category)
1510
+ ```ts
1511
+ const profile = await sock.getBusinessProfile(jid)
1512
+ console.log('business description: ' + profile.description + ', category: ' + profile.category)
1513
+ ```
1514
+
1515
+ ### Fetch Someone's Presence (if they're typing or online)
1516
+ ```ts
1517
+ // the presence update is fetched and called here
1518
+ sock.ev.on('presence.update', console.log)
1519
+
1520
+ // request updates for a chat
1521
+ await sock.presenceSubscribe(jid)
1522
+ ```
1523
+
1524
+ ## Change Profile
1525
+
1526
+ ### Change Profile Status
1527
+ ```ts
1528
+ await sock.updateProfileStatus('Hello World!')
1529
+ ```
1530
+ ### Change Profile Name
1531
+ ```ts
1532
+ await sock.updateProfileName('My name')
1533
+ ```
1534
+ ### Change Display Picture (groups too)
1535
+ - To change your display picture or a group's
1536
+
1537
+ > [!NOTE]
1538
+ > 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)
1539
+
1540
+ ```ts
1541
+ await sock.updateProfilePicture(jid, { url: './new-profile-picture.jpeg' })
1542
+ ```
1543
+ ### Remove display picture (groups too)
1544
+ ```ts
1545
+ await sock.removeProfilePicture(jid)
1546
+ ```
1547
+
1548
+ ## Groups
1549
+
1550
+ - To change group properties you need to be admin
1551
+
1552
+ ### Create a Group
1553
+ ```ts
1554
+ // title & participants
1555
+ const group = await sock.groupCreate('My Fab Group', ['1234@s.whatsapp.net', '4564@s.whatsapp.net'])
1556
+ console.log('created group with id: ' + group.gid)
1557
+ await sock.sendMessage(group.id, { text: 'hello there' }) // say hello to everyone on the group
1558
+ ```
1559
+ ### Add/Remove or Demote/Promote
1560
+ ```ts
1561
+ // id & people to add to the group (will throw error if it fails)
1562
+ await sock.groupParticipantsUpdate(
1563
+ jid,
1564
+ ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
1565
+ 'add' // replace this parameter with 'remove' or 'demote' or 'promote'
1566
+ )
1567
+ ```
1568
+ ### Change Subject (name)
1569
+ ```ts
1570
+ await sock.groupUpdateSubject(jid, 'New Subject!')
1571
+ ```
1572
+ ### Change Description
1573
+ ```ts
1574
+ await sock.groupUpdateDescription(jid, 'New Description!')
1575
+ ```
1576
+ ### Change Settings
1577
+ ```ts
1578
+ // only allow admins to send messages
1579
+ await sock.groupSettingUpdate(jid, 'announcement')
1580
+ // allow everyone to send messages
1581
+ await sock.groupSettingUpdate(jid, 'not_announcement')
1582
+ // allow everyone to modify the group's settings -- like display picture etc.
1583
+ await sock.groupSettingUpdate(jid, 'unlocked')
1584
+ // only allow admins to modify the group's settings
1585
+ await sock.groupSettingUpdate(jid, 'locked')
1586
+ ```
1587
+ ### Leave a Group
1588
+ ```ts
1589
+ // will throw error if it fails
1590
+ await sock.groupLeave(jid)
1591
+ ```
1592
+ ### Get Invite Code
1593
+ - To create link with code use `'https://chat.whatsapp.com/' + code`
1594
+ ```ts
1595
+ const code = await sock.groupInviteCode(jid)
1596
+ console.log('group code: ' + code)
1597
+ ```
1598
+ ### Revoke Invite Code
1599
+ ```ts
1600
+ const code = await sock.groupRevokeInvite(jid)
1601
+ console.log('New group code: ' + code)
1602
+ ```
1603
+ ### Join Using Invitation Code
1604
+ - Code can't have `https://chat.whatsapp.com/`, only code
1605
+ ```ts
1606
+ const response = await sock.groupAcceptInvite(code)
1607
+ console.log('joined to: ' + response)
1608
+ ```
1609
+ ### Get Group Info by Invite Code
1610
+ ```ts
1611
+ const response = await sock.groupGetInviteInfo(code)
1612
+ console.log('group information: ' + response)
1613
+ ```
1614
+ ### Query Metadata (participants, name, description...)
1615
+ ```ts
1616
+ const metadata = await sock.groupMetadata(jid)
1617
+ console.log(metadata.id + ', title: ' + metadata.subject + ', description: ' + metadata.desc)
1618
+ ```
1619
+ ### Join using `groupInviteMessage`
1620
+ ```ts
1621
+ const response = await sock.groupAcceptInviteV4(jid, groupInviteMessage)
1622
+ console.log('joined to: ' + response)
1623
+ ```
1624
+ ### Get Request Join List
1625
+ ```ts
1626
+ const response = await sock.groupRequestParticipantsList(jid)
1627
+ console.log(response)
1628
+ ```
1629
+ ### Approve/Reject Request Join
1630
+ ```ts
1631
+ const response = await sock.groupRequestParticipantsUpdate(
1632
+ jid, // group id
1633
+ ['abcd@s.whatsapp.net', 'efgh@s.whatsapp.net'],
1634
+ 'approve' // or 'reject'
1635
+ )
1636
+ console.log(response)
1637
+ ```
1638
+ ### Get All Participating Groups Metadata
1639
+ ```ts
1640
+ const response = await sock.groupFetchAllParticipating()
1641
+ console.log(response)
1642
+ ```
1643
+ ### Toggle Ephemeral
1644
+
1645
+ - Ephemeral can be:
1646
+
1647
+ | Time | Seconds |
1648
+ |-------|----------------|
1649
+ | Remove | 0 |
1650
+ | 24h | 86.400 |
1651
+ | 7d | 604.800 |
1652
+ | 90d | 7.776.000 |
1653
+
1654
+ ```ts
1655
+ await sock.groupToggleEphemeral(jid, 86400)
1656
+ ```
1657
+
1658
+ ### Change Add Mode
1659
+ ```ts
1660
+ await sock.groupMemberAddMode(
1661
+ jid,
1662
+ 'all_member_add' // or 'admin_add'
1663
+ )
1664
+ ```
1665
+
1666
+ ## Privacy
1667
+
1668
+ ### Block/Unblock User
1669
+ ```ts
1670
+ await sock.updateBlockStatus(jid, 'block') // Block user
1671
+ await sock.updateBlockStatus(jid, 'unblock') // Unblock user
1672
+ ```
1673
+ ### Get Privacy Settings
1674
+ ```ts
1675
+ const privacySettings = await sock.fetchPrivacySettings(true)
1676
+ console.log('privacy settings: ' + privacySettings)
1677
+ ```
1678
+ ### Get BlockList
1679
+ ```ts
1680
+ const response = await sock.fetchBlocklist()
1681
+ console.log(response)
1682
+ ```
1683
+ ### Update LastSeen Privacy
1684
+ ```ts
1685
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
1686
+ await sock.updateLastSeenPrivacy(value)
1687
+ ```
1688
+ ### Update Online Privacy
1689
+ ```ts
1690
+ const value = 'all' // 'match_last_seen'
1691
+ await sock.updateOnlinePrivacy(value)
1692
+ ```
1693
+ ### Update Profile Picture Privacy
1694
+ ```ts
1695
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
1696
+ await sock.updateProfilePicturePrivacy(value)
1697
+ ```
1698
+ ### Update Status Privacy
1699
+ ```ts
1700
+ const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
1701
+ await sock.updateStatusPrivacy(value)
1702
+ ```
1703
+ ### Update Read Receipts Privacy
1704
+ ```ts
1705
+ const value = 'all' // 'none'
1706
+ await sock.updateReadReceiptsPrivacy(value)
1707
+ ```
1708
+ ### Update Groups Add Privacy
1709
+ ```ts
1710
+ const value = 'all' // 'contacts' | 'contact_blacklist'
1711
+ await sock.updateGroupsAddPrivacy(value)
1712
+ ```
1713
+ ### Update Default Disappearing Mode
1714
+
1715
+ - Like [this](#disappearing-messages), ephemeral can be:
1716
+
1717
+ | Time | Seconds |
1718
+ |-------|----------------|
1719
+ | Remove | 0 |
1720
+ | 24h | 86.400 |
1721
+ | 7d | 604.800 |
1722
+ | 90d | 7.776.000 |
1723
+
1724
+ ```ts
1725
+ const ephemeral = 86400
1726
+ await sock.updateDefaultDisappearingMode(ephemeral)
1727
+ ```
1728
+
1729
+ ## Broadcast Lists & Stories
1730
+
1731
+ ### Send Broadcast & Stories
1732
+ - Messages can be sent to broadcasts & stories. You need to add the following message options in sendMessage, like this:
1733
+ ```ts
1734
+ await sock.sendMessage(
1735
+ jid,
1736
+ {
1737
+ image: {
1738
+ url: url
1739
+ },
1740
+ caption: caption
1741
+ },
1742
+ {
1743
+ backgroundColor: backgroundColor,
1744
+ font: font,
1745
+ statusJidList: statusJidList,
1746
+ broadcast: true
1747
+ }
1748
+ )
1749
+ ```
1750
+ - Message body can be a `extendedTextMessage` or `imageMessage` or `videoMessage` or `voiceMessage`, see the [AnyRegularMessageContent type alias](src/Types)
1751
+ - You can add `backgroundColor` and other options in the message options, see the [MiscMessageGenerationOptions type alias](src/Types)
1752
+ - `broadcast: true` enables broadcast mode
1753
+ - `statusJidList`: a list of people that you can get which you need to provide, which are the people who will get this status message.
1754
+
1755
+ - You can send messages to broadcast lists the same way you send messages to groups & individual chats.
1756
+ - Right now, WA Web does not support creating broadcast lists, but you can still delete them.
1757
+ - Broadcast IDs are in the format `12345678@broadcast`
1758
+ ### Query a Broadcast List's Recipients & Name
1759
+ ```ts
1760
+ const bList = await sock.getBroadcastListInfo('1234@broadcast')
1761
+ console.log (`list name: ${bList.name}, recps: ${bList.recipients}`)
1762
+ ```
1763
+
1764
+ ## Writing Custom Functionality
1765
+ Yui-Bails is written with custom functionality in mind. You can write your own extensions without re-writing the internals.
1766
+
1767
+ ### Enabling Debug Level in Yui-Bails Logs
1768
+ First, enable the logging of unhandled messages from WhatsApp by setting:
1769
+ ```ts
1770
+ const sock = makeWASocket({
1771
+ logger: P({ level: 'debug' }),
1772
+ })
1773
+ ```
1774
+ This will enable you to see all sorts of messages WhatsApp sends in the console.
1775
+
1776
+ ### How Whatsapp Communicate With Us
1777
+
1778
+ > [!TIP]
1779
+ > If you want to learn whatsapp protocol, we recommend to study about Libsignal Protocol and Noise Protocol
1780
+
1781
+ - **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:
1782
+ ```
1783
+ {
1784
+ "level": 10,
1785
+ "fromMe": false,
1786
+ "frame": {
1787
+ "tag": "ib",
1788
+ "attrs": {
1789
+ "from": "@s.whatsapp.net"
1790
+ },
1791
+ "content": [
1792
+ {
1793
+ "tag": "edge_routing",
1794
+ "attrs": {},
1795
+ "content": [
1796
+ {
1797
+ "tag": "routing_info",
1798
+ "attrs": {},
1799
+ "content": {
1800
+ "type": "Buffer",
1801
+ "data": [8,2,8,5]
1802
+ }
1803
+ }
1804
+ ]
1805
+ }
1806
+ ]
1807
+ },
1808
+ "msg":"communication"
1809
+ }
1810
+ ```
1811
+
1812
+ The `'frame'` is what the message received is, it has three components:
1813
+ - `tag` -- what this frame is about (eg. message will have 'message')
1814
+ - `attrs` -- a string key-value pair with some metadata (contains ID of the message usually)
1815
+ - `content` -- the actual data (eg. a message node will have the actual message content in it)
1816
+ - read more about this format [here](/src/WABinary/readme.md)
1817
+
1818
+ ### Register a Callback for Websocket Events
1819
+
1820
+ > [!TIP]
1821
+ > Recommended to see `onMessageReceived` function in `socket.ts` file to understand how websockets events are fired
1822
+
1823
+ ```ts
1824
+ // for any message with tag 'edge_routing'
1825
+ sock.ws.on('CB:edge_routing', (node: BinaryNode) => { })
1826
+
1827
+ // for any message with tag 'edge_routing' and id attribute = abcd
1828
+ sock.ws.on('CB:edge_routing,id:abcd', (node: BinaryNode) => { })
1829
+
1830
+ // for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
1831
+ sock.ws.on('CB:edge_routing,id:abcd,routing_info', (node: BinaryNode) => { })
1832
+ ```
1833
+
1834
+ # Licencia
1835
+
1836
+ Licencia MIT. Consulta el archivo [LICENSE](LICENSE).
1837
+
1838
+ Creado por [AmilcarGit](https://github.com/AmilcarGit).