### Install Dependencies Source: https://github.com/vljnh-new/zca-custom/blob/main/README.md Run this command in your terminal to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Real-time Event Listener Setup Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sets up a WebSocket listener to receive real-time Zalo events such as messages, reactions, and group events. Requires successful login and calling `listener.start()`. Includes basic event handlers for connection status and message processing. ```javascript import { Zalo, ThreadType } from "./index.js"; const zalo = new Zalo({ selfListen: false }); const api = await zalo.login({ imei: "...", cookie: "...", userAgent: "..." }); const { listener } = api; listener.onConnected(() => console.log("WebSocket đã kết nối")); listener.onClosed(() => console.log("WebSocket đã đóng")); listener.onError((err) => console.error("Lỗi WebSocket:", err)); listener.onMessage((msg) => { // msg là Message (cá nhân) hoặc GroupMessage (nhóm) console.log(`[${msg.type === 1 ? "Nhóm" : "Cá nhân"}] ${msg.data.uidFrom}: ${msg.data.content}`); // Trả lời tự động if (msg.data.content === "ping") { const threadType = msg.type === 1 ? ThreadType.Group : ThreadType.User; api.sendMessage("pong", msg.threadId, threadType); } }); listener.on("reaction", (reaction) => { console.log(`Reaction: ${reaction.data.content?.rIcon} từ ${reaction.data.uidFrom}`); }); listener.on("group_event", (event) => { console.log("Sự kiện nhóm:", event.type, event.data); }); listener.on("undo", (undo) => { console.log("Tin nhắn đã bị thu hồi:", undo.data.msgId); }); listener.start(); ``` -------------------------------- ### Get User Information Source: https://context7.com/vljnh-new/zca-custom/llms.txt Fetches user profile information by UID or phone number. Supports retrieving multiple UIDs at once and finding users by Zalo username or last online status. ```javascript // Lấy thông tin theo UID (hỗ trợ nhiều UID) const info = await api.getUserInfo(["1234567890", "9876543210"]); console.log(info.data); // Tìm theo số điện thoại const user = await api.findUser("0901234567"); // số VN, tự động đổi thành 84... console.log(user?.displayName, user?.avatar); // Tìm theo tên đăng nhập Zalo const byUsername = await api.findUserByUsername("ten_nguoi_dung"); // Lấy trạng thái online lần cuối const lastOnline = await api.lastOnline("1234567890"); console.log("Lần cuối online:", lastOnline); ``` -------------------------------- ### Manage Groups Source: https://context7.com/vljnh-new/zca-custom/llms.txt Provides functions to retrieve all groups, get detailed group information (including members), and manage group settings. ```javascript // Lấy tất cả nhóm const groups = await api.getAllGroups(); for (const g of groups.data?.groups || []) { console.log(g.groupId, g.name); } // Lấy thông tin chi tiết (hỗ trợ nhiều groupId) const info = await api.getGroupInfo(["GROUP_ID_1", "GROUP_ID_2"]); // Lấy thành viên nhóm const members = await api.getGroupMembers("GROUP_ID"); ``` -------------------------------- ### Get All Friends Source: https://context7.com/vljnh-new/zca-custom/llms.txt Retrieves the complete list of friends for the currently logged-in account. Iterates through the friend list to display basic information. ```javascript const friends = await api.getAllFriends(); for (const f of friends.data || []) { console.log(f.uid, f.zaloName, f.avatar); } ``` -------------------------------- ### Get Recent Messages Source: https://context7.com/vljnh-new/zca-custom/llms.txt Retrieves a list of recent messages from a conversation. Requires the thread ID and pagination parameters. ```javascript const messages = await api.getRecentMessage("GROUP_ID", 0, 30); // messages.data chứa mảng tin nhắn console.log(messages); ``` -------------------------------- ### Send Link with Preview Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send a link with a preview that includes a title, description, and thumbnail image. The API automatically generates the preview if these fields are not provided. ```javascript await api.sendLink( { msg: "Xem bài viết hay này!", link: "https://example.com/article", title: "Tiêu đề bài viết", desc: "Mô tả ngắn về nội dung", thumb: "https://example.com/thumbnail.jpg", }, "1234567890", ThreadType.User ); ``` -------------------------------- ### Login using QR Code Source: https://context7.com/vljnh-new/zca-custom/llms.txt Logs in interactively using a QR code. The callback handles events for each step of the login process. ```APIDOC ## Login using QR Code ### Description Logs in interactively using a QR code. The callback handles events for each step of the login process, such as QR code generation, scanning, and login confirmation. ### Method POST (Implicit, for initiating QR login) ### Endpoint (Not explicitly defined, assumed to be part of the Zalo class initialization) ### Parameters #### Request Body (Implicit for `loginQR` method) - **userAgent** (string) - Required - The user agent string. - **qrPath** (string) - Required - The path to save the QR code image. #### Callback Function - **event** (object) - An object representing the current event in the QR login process. It has a `type` property and an `actions` object. - **type** (string) - The type of event (e.g., `QRCodeGenerated`, `QRCodeScanned`, `QRCodeDeclined`, `GotLoginInfo`). - **actions** (object) - An object with methods to control the login flow (e.g., `saveToFile`, `retry`). - **data** (object) - Contains login information when `GotLoginInfo` event occurs. ### Request Example ```javascript import { Zalo, LoginQRCallbackEventType } from "./index.js"; import fs from "fs"; const zalo = new Zalo(); const api = await zalo.loginQR( { userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", qrPath: "qr.png" }, (event) => { switch (event.type) { case LoginQRCallbackEventType.QRCodeGenerated: // Lưu QR ra file hoặc hiển thị base64 event.actions.saveToFile("qr.png"); console.log("QR đã được tạo, vui lòng quét."); break; case LoginQRCallbackEventType.QRCodeExpired: console.log("QR hết hạn, thử lại..."); event.actions.retry(); break; case LoginQRCallbackEventType.QRCodeScanned: console.log("Đã quét QR, chờ xác nhận trên điện thoại..."); break; case LoginQRCallbackEventType.QRCodeDeclined: console.log("Từ chối đăng nhập."); break; case LoginQRCallbackEventType.GotLoginInfo: // Lưu thông tin để dùng cho lần đăng nhập tiếp theo bằng cookie fs.writeFileSync("credentials.json", JSON.stringify(event.data, null, 2)); console.log("Thông tin đăng nhập:", event.data); break; } } ); console.log("Đã đăng nhập:", api.getContext().uid); ``` ### Response #### Success Response - **api** (object) - An API object with methods for interacting with Zalo. - **uid** (string) - The user ID obtained after successful login. ``` -------------------------------- ### Zalo QR Code Login Source: https://github.com/vljnh-new/zca-custom/blob/main/README.md This snippet demonstrates how to log in using a QR code. It includes a callback function to handle login events, such as receiving login information. ```javascript import { Zalo } from "./index.js"; const zalo = new Zalo(); async function startQR() { const api = await zalo.loginQR({ userAgent: "your-user-agent", }, (event) => { if (event.type === "GotLoginInfo") { console.log("Đã lấy thông tin đăng nhập QR", event.data); } }); console.log("Đăng nhập QR thành công", api.getContext().uid); } startQR().catch(console.error); ``` -------------------------------- ### Login using Cookie/IMEI Source: https://context7.com/vljnh-new/zca-custom/llms.txt Initializes the Zalo object and logs in using provided cookie, IMEI, and userAgent. Returns an API object for subsequent calls. ```APIDOC ## Login using Cookie/IMEI ### Description Initializes the Zalo object and logs in using provided cookie, IMEI, and userAgent. Returns an API object for subsequent calls. ### Method POST (Implicit, as it's an initialization and login process) ### Endpoint (Not explicitly defined, assumed to be part of the Zalo class initialization) ### Parameters #### Request Body (Implicit for `Zalo` constructor and `login` method) - **selfListen** (boolean) - Optional - If true, the listener will also listen to your own messages. - **logging** (boolean) - Optional - If true, enables logging. - **imei** (string) - Required - The IMEI for login. - **cookie** (string) - Required - The cookie string for login. - **userAgent** (string) - Required - The user agent string. - **language** (string) - Optional - The language setting. - **timeMessage** (number) - Optional - Default is 0, meaning messages are not auto-deleted. ### Request Example ```javascript import { Zalo } from "./index.js"; const zalo = new Zalo({ selfListen: false, logging: true }); const api = await zalo.login({ imei: "a1b2c3d4-e5f6-7890-abcd-ef1234567890", cookie: '[{"key":"zpw_sek","value":"abc123","domain":"chat.zalo.me"}]', userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", language: "vi", timeMessage: 0, // TTL mặc định 0 = không tự xoá }); console.log("UID:", api.getContext().uid); ``` ### Response #### Success Response - **api** (object) - An API object with methods for interacting with Zalo. - **uid** (string) - The user ID obtained after successful login. ``` -------------------------------- ### Login with Cookie/IMEI Source: https://context7.com/vljnh-new/zca-custom/llms.txt Initiates a Zalo session using provided IMEI, cookie, and user agent. Returns an API object for subsequent operations. Ensure correct cookie format and valid credentials. ```javascript import { Zalo } from "./index.js"; const zalo = new Zalo({ selfListen: false, logging: true }); const api = await zalo.login({ imei: "a1b2c3d4-e5f6-7890-abcd-ef1234567890", cookie: '[{"key":"zpw_sek","value":"abc123","domain":"chat.zalo.me"}]', userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", language: "vi", timeMessage: 0, // TTL mặc định 0 = không tự xoá }); console.log("UID:", api.getContext().uid); ``` -------------------------------- ### Login with QR Code Source: https://context7.com/vljnh-new/zca-custom/llms.txt Handles interactive login via QR code. The callback function processes events like QR code generation, scanning, expiration, and successful login, allowing for saving credentials. ```javascript import { Zalo, LoginQRCallbackEventType } from "./index.js"; import fs from "fs"; const zalo = new Zalo(); const api = await zalo.loginQR( { userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", qrPath: "qr.png" }, (event) => { switch (event.type) { case LoginQRCallbackEventType.QRCodeGenerated: // Lưu QR ra file hoặc hiển thị base64 event.actions.saveToFile("qr.png"); console.log("QR đã được tạo, vui lòng quét."); break; case LoginQRCallbackEventType.QRCodeExpired: console.log("QR hết hạn, thử lại..."); event.actions.retry(); break; case LoginQRCallbackEventType.QRCodeScanned: console.log("Đã quét QR, chờ xác nhận trên điện thoại..."); break; case LoginQRCallbackEventType.QRCodeDeclined: console.log("Từ chối đăng nhập."); break; case LoginQRCallbackEventType.GotLoginInfo: // Lưu thông tin để dùng cho lần đăng nhập tiếp theo bằng cookie fs.writeFileSync("credentials.json", JSON.stringify(event.data, null, 2)); console.log("Thông tin đăng nhập:", event.data); break; } } ); console.log("Đã đăng nhập:", api.getContext().uid); ``` -------------------------------- ### Basic Zalo Login Source: https://github.com/vljnh-new/zca-custom/blob/main/README.md Use this snippet for basic login using IMEI, cookie, and user agent. Ensure you replace placeholder values with your actual credentials. ```javascript import { Zalo } from "./index.js"; const zalo = new Zalo(); async function start() { const api = await zalo.login({ imei: "your-imei", cookie: "your-cookie-string", userAgent: "your-user-agent", }); console.log("Đã đăng nhập với UID:", api.getContext().uid); } start().catch(console.error); ``` -------------------------------- ### Create Group Source: https://context7.com/vljnh-new/zca-custom/llms.txt Creates a new group with a specified list of members, group name, and an optional description. Returns the new group's ID. ```javascript const newGroup = await api.createGroup( ["UID_1", "UID_2", "UID_3"], "Nhóm Dự Án ABC", "Nhóm dành cho dự án ABC" ); console.log("GroupID mới:", newGroup.data?.groupId); ``` -------------------------------- ### Listener - Real-time Event Handling Source: https://context7.com/vljnh-new/zca-custom/llms.txt The Listener class connects to Zalo's WebSocket server to emit real-time events like messages, reactions, and group events. It requires `listener.start()` to be called after successful login. ```APIDOC ## Listener — Real-time Event Handling ### Description The `Listener` class connects to Zalo's WebSocket server and emits real-time events such as `message`, `undo`, `reaction`, `group_event`, and `upload_attachment`. You need to call `listener.start()` after a successful login. ### Method (Not explicitly defined, listener is part of the API object) ### Endpoint (Not explicitly defined, WebSocket connection) ### Parameters (Listener methods do not take direct parameters in this context, but event handlers receive data) ### Request Example ```javascript import { Zalo, ThreadType } from "./index.js"; const zalo = new Zalo({ selfListen: false }); const api = await zalo.login({ imei: "...", cookie: "...", userAgent: "..." }); const { listener } = api; listener.onConnected(() => console.log("WebSocket đã kết nối")); listener.onClosed(() => console.log("WebSocket đã đóng")); listener.onError((err) => console.error("Lỗi WebSocket:", err)); listener.onMessage((msg) => { // msg là Message (cá nhân) hoặc GroupMessage (nhóm) console.log(`[${msg.type === 1 ? "Nhóm" : "Cá nhân"}] ${msg.data.uidFrom}: ${msg.data.content}`); // Trả lời tự động if (msg.data.content === "ping") { const threadType = msg.type === 1 ? ThreadType.Group : ThreadType.User; api.sendMessage("pong", msg.threadId, threadType); } }); listener.on("reaction", (reaction) => { console.log(`Reaction: ${reaction.data.content?.rIcon} từ ${reaction.data.uidFrom}`); }); listener.on("group_event", (event) => { console.log("Sự kiện nhóm:", event.type, event.data); }); listener.on("undo", (undo) => { console.log("Tin nhắn đã bị thu hồi:", undo.data.msgId); }); listener.start(); ``` ### Response (No direct response, but events are emitted) #### Event Data Examples - **onMessage**: `msg` object containing message details (sender, content, thread ID, type). - **onReaction**: `reaction` object with reaction details. - **onGroupEvent**: `event` object with group event details. - **onUndo**: `undo` object with information about the recalled message. ``` -------------------------------- ### api.joinGroupByLink / api.leaveGroup Source: https://context7.com/vljnh-new/zca-custom/llms.txt Join a group using an invitation link or leave an existing group. ```APIDOC ## api.joinGroupByLink / api.leaveGroup — Join / Leave Group Join a group via an invitation link or leave a group. ### Description Enables users to join groups using shared invitation links, optionally answering security questions, or to exit groups they are a part of. Includes an option for silent group departure. ### Method `api.joinGroupByLink(invitationLink: string, securityAnswer?: string): Promise` `api.leaveGroup(groupId: string, silent?: boolean): Promise` `api.disperseGroup(groupId: string): Promise` ### Parameters #### joinGroupByLink - **invitationLink** (string) - Required - The invitation link to the group. - **securityAnswer** (string) - Optional - The answer to a security question if required by the group. #### leaveGroup - **groupId** (string) - Required - The ID of the group to leave. - **silent** (boolean) - Optional - If true, leaves the group without notifying other members. Defaults to false. #### disperseGroup - **groupId** (string) - Required - The ID of the group to disband. Only available to the group owner. ``` -------------------------------- ### sendVideo Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sends a video from a local file or URL. Supports metadata extraction (width, height, duration) via ffprobe for local files. ```APIDOC ## api.sendVideo — Gửi video Gửi video từ file cục bộ hoặc URL HTTP(S). Hỗ trợ tự động đọc metadata (width, height, duration) qua ffprobe khi gửi file cục bộ. ### Parameters - **videoSource**: (string | object) - The video source. Can be a local file path, a URL, or an object with `src`, `msg`, `duration`, `width`, `height`, and `thumb` properties. - **threadId**: (string) - The ID of the chat thread. - **threadType**: (ThreadType) - The type of the thread. ### Request Example ```js // Gửi video từ URL (không cần upload) await api.sendVideo( { src: "https://example.com/clip.mp4", msg: "Xem video này!", duration: 30, width: 1280, height: 720, thumb: "https://example.com/thumb.jpg", }, "GROUP_ID", ThreadType.Group ); // Gửi video từ file cục bộ await api.sendVideo("./video/clip.mp4", "1234567890", ThreadType.User); ``` ``` -------------------------------- ### api.createGroup Source: https://context7.com/vljnh-new/zca-custom/llms.txt Creates a new group with a list of members and a group name. ```APIDOC ## api.createGroup — Tạo nhóm Tạo nhóm mới với danh sách thành viên và tên nhóm. ```js const newGroup = await api.createGroup( ["UID_1", "UID_2", "UID_3"], "Nhóm Dự Án ABC", "Nhóm dành cho dự án ABC" ); console.log("GroupID mới:", newGroup.data?.groupId); ``` ``` -------------------------------- ### Send Video from URL or Local File Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send videos from local files or HTTP(S) URLs. For local files, the API can automatically read metadata (width, height, duration) using ffprobe. Metadata can also be provided manually when sending from a URL. ```javascript // Gửi video từ URL (không cần upload) await api.sendVideo( { src: "https://example.com/clip.mp4", msg: "Xem video này!", duration: 30, width: 1280, height: 720, thumb: "https://example.com/thumb.jpg", }, "GROUP_ID", ThreadType.Group ); // Gửi video từ file cục bộ await api.sendVideo("./video/clip.mp4", "1234567890", ThreadType.User); ``` -------------------------------- ### sendLink Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sends a link with a preview (title, description, thumbnail) to a chat. ```APIDOC ## api.sendLink — Gửi liên kết Gửi liên kết có preview (tiêu đề, mô tả, ảnh thumbnail) tới cuộc trò chuyện. ### Parameters - **linkInfo**: (object) - Link details including `msg`, `link`, `title`, `desc`, and `thumb`. - **threadId**: (string) - The ID of the chat thread. - **threadType**: (ThreadType) - The type of the thread. ### Request Example ```js await api.sendLink( { msg: "Xem bài viết hay này!", link: "https://example.com/article", title: "Tiêu đề bài viết", desc: "Mô tả ngắn về nội dung", thumb: "https://example.com/thumbnail.jpg", }, "1234567890", ThreadType.User ); ``` ``` -------------------------------- ### Send Sticker Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send Zalo stickers using `stickerId` and `cateId`. Also supports sending custom stickers from static and animated image URLs. ```javascript await api.sendSticker( { id: "12345", cateId: "100", type: 7 }, "1234567890", ThreadType.User ); // Gửi sticker tuỳ chỉnh từ URL ảnh (custom sticker) await api.sendCustomerSticker( "https://example.com/sticker-static.png", // URL ảnh tĩnh "https://example.com/sticker-anim.webp", // URL ảnh động "GROUP_ID", ThreadType.Group, { width: 512, height: 512, ttl: 0 } ); ``` -------------------------------- ### sendSticker Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sends a Zalo sticker to a chat using `stickerId` and `cateId`. Also supports sending custom stickers from URLs. ```APIDOC ## api.sendSticker — Gửi sticker Gửi sticker Zalo đến cuộc trò chuyện cá nhân hoặc nhóm bằng `stickerId` và `cateId`. ### Parameters - **stickerInfo**: (object) - Sticker details including `id`, `cateId`, and `type`. - **threadId**: (string) - The ID of the chat thread. - **threadType**: (ThreadType) - The type of the thread. ### Request Example ```js await api.sendSticker( { id: "12345", cateId: "100", type: 7 }, "1234567890", ThreadType.User ); // Gửi sticker tuỳ chỉnh từ URL ảnh (custom sticker) await api.sendCustomerSticker( "https://example.com/sticker-static.png", // URL ảnh tĩnh "https://example.com/sticker-anim.webp", // URL ảnh động "GROUP_ID", ThreadType.Group, { width: 512, height: 512, ttl: 0 } ); ``` ``` -------------------------------- ### Manage Friend Aliases Source: https://context7.com/vljnh-new/zca-custom/llms.txt Allows setting, retrieving, and removing custom aliases (nicknames) for friends. Requires friend UIDs and alias strings. ```javascript // Đặt biệt danh await api.changeFriendAlias("1234567890", "Bạn Thân"); // Lấy danh sách biệt danh const aliasList = await api.getAliasList(); // Xoá biệt danh await api.removeFriendAlias("1234567890"); ``` -------------------------------- ### sendVoice Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sends an audio file as a voice message. Files under 9MB are sent via the voice endpoint; larger files are handled asynchronously. ```APIDOC ## api.sendVoice — Gửi tin nhắn thoại Gửi file âm thanh dạng voice message (AAC, MP3, M4A) tới cuộc trò chuyện. File nhỏ hơn 9MB gửi qua endpoint voice, lớn hơn tự chuyển sang asyncfile. ### Parameters - **audioSource**: (string | object) - The audio source. Can be a local file path or a URL. - **threadId**: (string) - The ID of the chat thread. - **threadType**: (ThreadType) - The type of the thread. ### Request Example ```js // Gửi voice từ file cục bộ await api.sendVoice("./audio/message.aac", "1234567890", ThreadType.User); // Gửi voice từ URL (native msgType=3) await api.sendVoiceNative({ voiceUrl: "https://example.com/audio.aac", threadId: "1234567890", threadType: ThreadType.User, duration: 15, fileSize: 50000, ttl: 1800000, }); ``` ``` -------------------------------- ### Cài đặt nhóm Source: https://context7.com/vljnh-new/zca-custom/llms.txt Cập nhật các tùy chọn cài đặt của nhóm như khoá gửi tin, yêu cầu duyệt thành viên, ẩn lịch sử tin nhắn, hoặc giới hạn quyền thêm thành viên chỉ cho quản trị viên. Cần import `GroupSetting`. ```javascript import { GroupSetting } from "./index.js"; await api.changeGroupSetting("GROUP_ID", { [GroupSetting.lockSendMsg]: 1, [GroupSetting.joinAppr]: 1, [GroupSetting.enableMsgHistory]: 0, [GroupSetting.addMemberOnly]: 1, }); ``` -------------------------------- ### api.getAllGroups / api.getGroupInfo Source: https://context7.com/vljnh-new/zca-custom/llms.txt Retrieves a list of all groups, detailed group information, or a list of group members. ```APIDOC ## api.getAllGroups / api.getGroupInfo — Quản lý nhóm Lấy danh sách tất cả nhóm, thông tin chi tiết nhóm hoặc danh sách thành viên. ```js // Lấy tất cả nhóm const groups = await api.getAllGroups(); for (const g of groups.data?.groups || []) { console.log(g.groupId, g.name); } // Lấy thông tin chi tiết (hỗ trợ nhiều groupId) const info = await api.getGroupInfo(["GROUP_ID_1", "GROUP_ID_2"]); // Lấy thành viên nhóm const members = await api.getGroupMembers("GROUP_ID"); ``` ``` -------------------------------- ### MessageMention / MessageStyle / MultiMsgStyle — Message Formatting Utilities Source: https://context7.com/vljnh-new/zca-custom/llms.txt Helper functions to create mention and style data structures for text messages. ```APIDOC ## MessageMention / MessageStyle / MultiMsgStyle — Message Formatting Utilities ### Description Helper functions to create mention and style data structures for text messages. ### Method `MessageMention(uid: string, length: number, pos: number): MentionObject` `MessageStyle(options: { offset: number, length: number, bold?: boolean, color?: string, size?: string, italic?: boolean, underline?: boolean }): StyleObject` `MultiMsgStyle(styles: StyleObject[]): CombinedStyleObject` ### Examples ```js import { MessageMention, MessageStyle, MultiMsgStyle } from "./index.js"; // Create a mention for a user at offset=1, length=5 const mention = MessageMention("USER_UID", 5, 1); // => { pos: 1, len: 5, uid: "USER_UID", type: 0 } // Mention @all (entire group) const mentionAll = MessageMention("-1", 4, 0); // Create style: bold, red color, size 20 const style1 = MessageStyle({ offset: 0, length: 5, bold: true, color: "ff0000", size: "20" }); // Create style: italic, underline const style2 = MessageStyle({ offset: 6, length: 5, italic: true, underline: true }); // Combine multiple styles for server const combinedStyle = MultiMsgStyle([style1, style2]); await api.sendMessage( { msg: "Hello World from bot!", mentions: [mention], style: combinedStyle, }, "GROUP_ID", ThreadType.Group ); ``` ``` -------------------------------- ### api.createAutoReply Source: https://context7.com/vljnh-new/zca-custom/llms.txt Manage auto-reply rules for incoming messages, including creation, retrieval, and deletion. ```APIDOC ## api.createAutoReply — Auto-Reply Create, update, or delete auto-reply rules for incoming messages. ### Description Provides functionality to set up automatic responses to messages based on keywords. Users can create new rules, retrieve a list of existing rules, and delete specific rules. ### Method `api.createAutoReply(rule: AutoReplyRule): Promise` `api.getAutoReplyList(): Promise` `api.deleteAutoReply(ruleId: string): Promise` ### Parameters #### createAutoReply - **rule** (AutoReplyRule) - Required - An object defining the auto-reply rule: - `keyword` (string): The keyword to trigger the reply. - `reply` (string): The content of the auto-reply message. - `type` (1 | 2): The matching type (`1` for exact match, `2` for contains keyword). #### deleteAutoReply - **ruleId** (string) - Required - The ID of the auto-reply rule to delete. ``` -------------------------------- ### Send File from URL or Local Path Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send document files (PDF, ZIP, DOCX, etc.) from a local path or URL. The API supports chunked uploads (3MB per chunk) and automatic retries on failure. ```javascript // Gửi file từ đường dẫn cục bộ await api.sendFile("./documents/report.pdf", "1234567890", ThreadType.User); // Gửi file từ URL kèm tin nhắn await api.sendFile( { src: "https://example.com/data.zip", msg: "Đây là file dữ liệu" }, "GROUP_ID", ThreadType.Group ); ``` -------------------------------- ### api.sendFriendRequest / api.acceptFriendRequest Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sends a friend request, accepts, rejects, or removes a friend. ```APIDOC ## api.sendFriendRequest / api.acceptFriendRequest — Kết bạn Gửi lời mời kết bạn, chấp nhận, từ chối hoặc xoá kết bạn. ```js // Gửi lời mời await api.sendFriendRequest("Xin chào, mình muốn kết bạn!", "1234567890"); // Chấp nhận lời mời await api.acceptFriendRequest("1234567890"); // Từ chối lời mời await api.rejectFriendRequest("1234567890"); // Thu hồi lời mời đã gửi await api.undoFriendRequest("1234567890"); // Xoá bạn bè await api.removeFriend("1234567890"); // Chặn / Bỏ chặn await api.blockUser("1234567890"); await api.unblockUser("1234567890"); ``` ``` -------------------------------- ### Error Handling with ZaloApiError Source: https://context7.com/vljnh-new/zca-custom/llms.txt Details on how to handle errors using the ZaloApiError class and its subclasses. ```APIDOC ## Error Handling with ZaloApiError ### Description `ZaloApiError` is the main error class for the library. All API methods can throw this error for missing parameters or invalid responses. Specific subclasses exist for login-related errors. ### Error Classes - `ZaloApiError`: Base error class for API operations. - `ZaloApiLoginQRAborted`: Thrown when QR login is aborted. - `ZaloApiLoginQRDeclined`: Thrown when the user declines QR login on their phone. ### Examples ```js import { Zalo, ZaloApiError, ZaloApiLoginQRAborted, ZaloApiLoginQRDeclined } from "./index.js"; const api = await new Zalo().login({ imei: "...", cookie: "...", userAgent: "..." }); try { await api.sendMessage("", ""); // Missing threadId and content } catch (err) { if (err instanceof ZaloApiError) { console.error("ZaloApiError:", err.message, "| code:", err.code); } else { console.error("Unknown error:", err); } } // QR Login Error Handling try { const api2 = await new Zalo().loginQR({}); } catch (err) { if (err instanceof ZaloApiLoginQRAborted) { console.log("QR login aborted"); } else if (err instanceof ZaloApiLoginQRDeclined) { console.log("User declined QR login on phone"); } else { console.error("Login error:", err.message); } } ``` ``` -------------------------------- ### sendFile Source: https://context7.com/vljnh-new/zca-custom/llms.txt Sends a document file (PDF, ZIP, DOCX, etc.) from a local path or URL. Supports chunked uploads and retries. ```APIDOC ## api.sendFile — Gửi file Gửi file tài liệu (PDF, ZIP, DOCX, …) từ đường dẫn cục bộ hoặc URL. Upload theo từng chunk 3MB song song, tự retry nếu thất bại. ### Parameters - **fileSource**: (string | object) - The file source. Can be a local file path, a URL, or an object with `src` and `msg` properties. - **threadId**: (string) - The ID of the chat thread. - **threadType**: (ThreadType) - The type of the thread. ### Request Example ```js // Gửi file từ đường dẫn cục bộ await api.sendFile("./documents/report.pdf", "1234567890", ThreadType.User); // Gửi file từ URL kèm tin nhắn await api.sendFile( { src: "https://example.com/data.zip", msg: "Đây là file dữ liệu" }, "GROUP_ID", ThreadType.Group ); ``` ``` -------------------------------- ### Send Text Message with Mentions and Styling Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send text messages to users or groups. Supports mentions, message styling (bold, color, size), TTL for self-deleting messages, and auto-detected links. Requires importing Zalo, ThreadType, MessageMention, and MessageStyle. ```javascript import { Zalo, ThreadType, MessageMention, MessageStyle } from "./index.js"; const api = await new Zalo().login({ imei: "...", cookie: "...", userAgent: "..." }); // Tin nhắn đơn giản đến cá nhân await api.sendMessage("Xin chào!", "1234567890"); // Tin nhắn đến nhóm với mention thành viên const mention = MessageMention("9876543210", 5, 0); // uid, độ dài, vị trí bắt đầu await api.sendMessage( { msg: "@Bạn Ơi, hello!", mentions: [mention] }, "GROUP_ID_HERE", ThreadType.Group ); // Tin nhắn có định dạng in đậm const style = MessageStyle({ offset: 0, length: 5, bold: true, color: "ff0000", size: "20" }); await api.sendMessage( { msg: "Hello world", style }, "1234567890", ThreadType.User ); // Tin nhắn có trích dẫn (quote) một tin cũ const previousMessage = { msgId: "111", cliMsgId: "222", uidFrom: "333", content: "Tin gốc", ts: Date.now() }; const result = await api.sendMessage( { msg: "Đây là trả lời", quote: previousMessage }, "1234567890" ); // result = { message: {...}, attachment: [], link: null } console.log("Đã gửi, msgId:", result.message?.data?.msgId); ``` -------------------------------- ### Xử lý lỗi API Zalo Source: https://context7.com/vljnh-new/zca-custom/llms.txt Bắt và xử lý các lỗi API chung (`ZaloApiError`) và các lỗi đăng nhập QR cụ thể (`ZaloApiLoginQRAborted`, `ZaloApiLoginQRDeclined`). ```javascript import { Zalo, ZaloApiError } from "./index.js"; const api = await new Zalo().login({ imei: "...", cookie: "...", userAgent: "..." }); try { await api.sendMessage("", ""); } catch (err) { if (err instanceof ZaloApiError) { console.error("ZaloApiError:", err.message, "| code:", err.code); } else { console.error("Lỗi không xác định:", err); } } import { ZaloApiLoginQRAborted, ZaloApiLoginQRDeclined } from "./index.js"; try { const api2 = await new Zalo().loginQR({}); } catch (err) { if (err instanceof ZaloApiLoginQRAborted) { console.log("Đăng nhập QR bị huỷ"); } else if (err instanceof ZaloApiLoginQRDeclined) { console.log("Người dùng từ chối đăng nhập QR trên điện thoại"); } else { console.error("Lỗi đăng nhập:", err.message); } } ``` -------------------------------- ### api.changeGroupSetting Source: https://context7.com/vljnh-new/zca-custom/llms.txt Update various group settings, including message sending permissions, history visibility, and membership approval. ```APIDOC ## api.changeGroupSetting — Group Settings Update group settings such as message sending lock, history hiding, and membership approval requirements. ### Description Allows modification of group configurations like locking message sending, hiding chat history, requiring approval for new members, and restricting member additions to administrators. ### Method `api.changeGroupSetting(groupId: string, settings: Record): Promise` ### Parameters - **groupId** (string) - Required - The ID of the group to modify. - **settings** (Record) - Required - An object containing the settings to update. Possible keys include `GroupSetting.lockSendMsg`, `GroupSetting.joinAppr`, `GroupSetting.enableMsgHistory`, `GroupSetting.addMemberOnly`, with values `1` for enabled and `0` for disabled. ``` -------------------------------- ### api.handleGroupPendingMembers Source: https://context7.com/vljnh-new/zca-custom/llms.txt Approve or reject pending member requests to join a group. ```APIDOC ## api.handleGroupPendingMembers — Approve Pending Members Approve or reject requests for members to join a group. ### Description Manages join requests for a group. It allows administrators to approve or deny users who have requested to join. The operation first retrieves pending requests and then processes them based on the provided action. ### Method `api.handleGroupPendingMembers(groupId: string, memberIds: string[], approve: boolean): Promise` ### Parameters - **groupId** (string) - Required - The ID of the group. - **memberIds** (string[]) - Required - An array of member IDs to approve or reject. - **approve** (boolean) - Required - `true` to approve requests, `false` to reject. ``` -------------------------------- ### api.getUserInfo / api.findUser Source: https://context7.com/vljnh-new/zca-custom/llms.txt Retrieves profile information for one or more users by UID or phone number. ```APIDOC ## api.getUserInfo / api.findUser — Lấy thông tin người dùng Lấy thông tin hồ sơ của một hoặc nhiều người dùng theo UID hoặc số điện thoại. ```js // Lấy thông tin theo UID (hỗ trợ nhiều UID) const info = await api.getUserInfo(["1234567890", "9876543210"]); console.log(info.data); // Tìm theo số điện thoại const user = await api.findUser("0901234567"); // số VN, tự động đổi thành 84... console.log(user?.displayName, user?.avatar); // Tìm theo tên đăng nhập Zalo const byUsername = await api.findUserByUsername("ten_nguoi_dung"); // Lấy trạng thái online lần cuối const lastOnline = await api.lastOnline("1234567890"); console.log("Lần cuối online:", lastOnline); ``` ``` -------------------------------- ### api.getAllFriends Source: https://context7.com/vljnh-new/zca-custom/llms.txt Retrieves the entire list of friends for the currently logged-in account. ```APIDOC ## api.getAllFriends — Lấy danh sách bạn bè Lấy toàn bộ danh sách bạn bè của tài khoản đang đăng nhập. ```js const friends = await api.getAllFriends(); for (const f of friends.data || []) { console.log(f.uid, f.zaloName, f.avatar); } ``` ``` -------------------------------- ### api.sendBusinessCard / api.sendCard — Send Business Card Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send a user's business card (with Zalo QR code) to a conversation. ```APIDOC ## api.sendBusinessCard / api.sendCard — Send Business Card ### Description Send a user's business card (with Zalo QR code) to a conversation. ### Method `api.sendBusinessCard(userUidToSend: string, recipientThreadId: string, threadType: ThreadType)` `api.sendCard(cardInfo: { userId: string, phoneNumber?: string, ttl?: number }, threadId: string, threadType: ThreadType)` ### Examples ```js // Send a simple business card await api.sendBusinessCard("USER_UID_TO_SEND", "RECIPIENT_THREAD_ID", ThreadType.User); // Send a full business card (including QR code) await api.sendCard( { userId: "USER_UID_TO_SEND", phoneNumber: "0901234567", ttl: 0 }, "GROUP_ID", ThreadType.Group ); ``` ``` -------------------------------- ### Send Image from URL or Local File Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send images to chats from a local file path or an HTTP(S) URL. The API automatically uploads the image and extracts metadata like width and height. Supports sending multiple images at once. ```javascript // Gửi ảnh từ URL await api.sendImage( { src: "https://example.com/photo.jpg", msg: "Ảnh đẹp!" }, "1234567890", ThreadType.User ); // Gửi ảnh từ file cục bộ đến nhóm await api.sendImage("./images/avatar.png", "GROUP_ID", ThreadType.Group); // Gửi nhiều ảnh cùng lúc await api.sendMultiImage( ["https://example.com/img1.jpg", "https://example.com/img2.jpg"], "GROUP_ID", ThreadType.Group ); ``` -------------------------------- ### Manage Friend Requests and Relationships Source: https://context7.com/vljnh-new/zca-custom/llms.txt Handles sending, accepting, rejecting, and undoing friend requests. Also includes functionality to remove friends, block, and unblock users. ```javascript // Gửi lời mời await api.sendFriendRequest("Xin chào, mình muốn kết bạn!", "1234567890"); // Chấp nhận lời mời await api.acceptFriendRequest("1234567890"); // Từ chối lời mời await api.rejectFriendRequest("1234567890"); // Thu hồi lời mời đã gửi await api.undoFriendRequest("1234567890"); // Xoá bạn bè await api.removeFriend("1234567890"); // Chặn / Bỏ chặn await api.blockUser("1234567890"); await api.unblockUser("1234567890"); ``` -------------------------------- ### api.sendTypingEvent / api.sendSeenEvent — Status Events Source: https://context7.com/vljnh-new/zca-custom/llms.txt Send 'typing', 'seen', or 'delivered' status events for a conversation. ```APIDOC ## api.sendTypingEvent / api.sendSeenEvent — Status Events ### Description Send 'typing', 'seen', or 'delivered' status events for a conversation. ### Method `api.sendTypingEvent(threadId: string, threadType: ThreadType)` `api.sendSeenEvent(messages: Array<{ msgId: string, cliMsgId: string, uidFrom: string }>, threadId: string, threadType: ThreadType)` `api.keepAlive()` ### Examples ```js // Send typing event await api.sendTypingEvent("1234567890", ThreadType.User); // Send message seen event await api.sendSeenEvent( [{ msgId: "111222", cliMsgId: "333444", uidFrom: "SENDER_UID" }], "1234567890", ThreadType.User ); // Keepalive connection await api.keepAlive(); ``` ```