### Create Web Connection Builder Source: https://github.com/auties00/cobalt/blob/master/README.md Use this to start building a web connection. No specific setup is required beyond this initial call. ```java Whatsapp.webBuilder() ``` -------------------------------- ### Register Multiple Listeners and Connect Source: https://github.com/auties00/cobalt/blob/master/README.md Chain listener registrations and connection calls for a compact application setup. This example demonstrates adding logged-in and new message listeners, then connecting. ```java Whatsapp.newConnection() .addLoggedInListener(() -> System.out.println("Connected")) .addNewMessageListener((whatsapp, info) -> whatsapp.sendMessage(info.chatJid(), "Automatic answer", info)) .connect() .join(); ``` -------------------------------- ### Create Mobile Connection Builder Source: https://github.com/auties00/cobalt/blob/master/README.md Use this to start building a mobile connection. No specific setup is required beyond this initial call. ```java Whatsapp.mobileBuilder() ``` -------------------------------- ### Start Call Source: https://github.com/auties00/cobalt/blob/master/README.md Initiates a call to a specified contact. ```APIDOC ## Start Call ### Description Initiates a call to a specified contact. Currently, there is no audio/video support. ### Method ```java api.startCall(contact) ``` ### Parameters #### Path Parameters - **contact** (Contact) - Required - The contact to call. ``` -------------------------------- ### Start Call Source: https://github.com/auties00/cobalt/blob/master/README.md Initiate a call to a specified contact. Note: Audio/video support is not currently available. ```java var future = api.startCall(contact); ``` -------------------------------- ### builder().webClient() — Web Client (Pairing Code) Source: https://context7.com/auties00/cobalt/llms.txt Connects via a numeric pairing code instead of a QR code, which is useful for automated setups. ```APIDOC ## builder().webClient() — Web Client (Pairing Code) ### Description Connects via a numeric pairing code instead of a QR code, useful for automated setups. ### Code Example ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientVerificationHandler; long phoneNumber = 15551234567L; // include country code, no '+' or spaces WhatsAppClient client = WhatsAppClient.builder() .webClient() .loadOrCreateConnection(phoneNumber) .unregistered(phoneNumber, WhatsAppClientVerificationHandler.Web.PairingCode.toTerminal()) .addLoggedInListener(api -> System.out.println("Paired and connected")) .connect() .waitForDisconnection(); ``` ``` -------------------------------- ### Access WhatsAppClient Builder Source: https://context7.com/auties00/cobalt/llms.txt Obtain the singleton WhatsAppClientBuilder, which is the starting point for configuring WhatsApp client sessions. ```java WhatsAppClientBuilder builder = WhatsAppClient.builder(); ``` -------------------------------- ### Accessing and Querying WhatsAppStore Data Source: https://context7.com/auties00/cobalt/llms.txt Demonstrates how to access the `WhatsAppStore` to retrieve chats, find specific chats by JID, access contacts, get the current session JID, and list newsletters. Requires importing `WhatsAppStore` and `Jid`. ```java import com.github.auties00.cobalt.store.WhatsAppStore; import com.github.auties00.cobalt.model.jid.Jid; WhatsAppStore store = client.store(); // Query chats var chats = store.chats(); chats.forEach(chat -> System.out.println("Chat: " + chat.jid())); // Find a specific chat Jid targetJid = Jid.of("15551234567@s.whatsapp.net"); store.findChatByJid(targetJid) .ifPresent(chat -> System.out.println("Found: " + chat.name().orElse("N/A"))); // Access contacts store.contacts().forEach(contact -> System.out.printf("Contact: %s (%s)%n", contact.jid(), contact.chosenName().orElse("N/A"))); // Access current session JID store.jid().ifPresent(jid -> System.out.println("My JID: " + jid)); // Access newsletters store.newsletters().forEach(n -> System.out.println("Newsletter: " + n.jid())); ``` -------------------------------- ### Mobile Device Connection with SMS OTP Source: https://github.com/auties00/cobalt/blob/master/README.md Connect to WhatsApp using the Mobile API for a non-business iOS account. This example demonstrates registering the device, providing an SMS OTP, and handling connection events. ```java System.out.println("Enter the phone number(include the country code prefix, but no +, spaces or parenthesis):") var scanner = new Scanner(System.in); var phoneNumber = scanner.nextLong(); Whatsapp.mobileBuilder() .newConnection() .device(CompanionDevice.ios(false)) .unregistered() .verificationCodeMethod(VerificationCodeMethod.SMS) .verificationCodeSupplier(() -> { System.out.println("Enter OTP: "); var scanner = new Scanner(System.in); return scanner.nextLine(); }) .register(phoneNumber) .join() .whatsapp() .addLoggedInListener(api -> System.out.printf("Connected: %s%n", api.store().privacySettings())) .addDisconnectedListener(reason -> System.out.printf("Disconnected: %s%n", reason)) .addNewChatMessageListener(message -> System.out.printf("New message: %s%n", message.toJson())) .connect() .join() .awaitDisconnection(); ``` -------------------------------- ### Create Web Client via Pairing Code Source: https://context7.com/auties00/cobalt/llms.txt Establish a Web client connection using a numeric pairing code, suitable for automated setups. Requires the phone number associated with the WhatsApp account. ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientVerificationHandler; long phoneNumber = 15551234567L; // include country code, no '+' or spaces WhatsAppClient client = WhatsAppClient.builder() .webClient() .loadOrCreateConnection(phoneNumber) .unregistered(phoneNumber, WhatsAppClientVerificationHandler.Web.PairingCode.toTerminal()) .addLoggedInListener(api -> System.out.println("Paired and connected")) .connect() .waitForDisconnection(); ``` -------------------------------- ### Initiate and Terminate Voice/Video Calls (Mobile Only) Source: https://context7.com/auties00/cobalt/llms.txt Initiates or terminates voice or video calls with a contact. Includes an example of listening for incoming calls and automatically rejecting them. ```java import com.github.auties00.cobalt.model.jid.Jid; import com.github.auties00.cobalt.model.call.Call; Jid contact = Jid.of("15551234567@s.whatsapp.net"); // Start audio call Call call = client.startCall(contact, false); System.out.println("Calling: " + call.id()); // Start video call Call videoCall = client.startCall(contact, true); // Reject/stop call client.stopCall(call); // Listen for incoming calls client.addCallListener((api, incomingCall) -> { System.out.println("Incoming call from: " + incomingCall.callerJid()); api.stopCall(incomingCall); // reject automatically }); ``` -------------------------------- ### Getting Companion Phone Number Source: https://github.com/auties00/cobalt/blob/master/README.md Extract the phone number from the companion device's JID. ```java var phoneNumber = store.jid().toPhoneNumber(); ``` -------------------------------- ### Create Web Client via QR Code Source: https://context7.com/auties00/cobalt/llms.txt Configure and connect a Web client that uses QR code scanning for authentication. The QR code is displayed in the terminal by default. Sessions are automatically serialized and reused. ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientVerificationHandler; WhatsAppClient client = WhatsAppClient.builder() .webClient() // Web mode (linked device) .loadLastOrCreateConnection() // Resume last session or create new .name("MyBot") // Device name shown in "Linked Devices" .unregistered(WhatsAppClientVerificationHandler.Web.QrCode.toTerminal()) // Print QR to terminal .addLoggedInListener(api -> System.out.println("Connected!")) .addNewChatMessageListener(msg -> System.out.printf("New message from %s: %s%n", msg.senderJid(), msg.message().toJson())) .addDisconnectedListener((api, reason) -> System.out.println("Disconnected: " + reason)) .connect() .waitForDisconnection(); ``` -------------------------------- ### WhatsAppClient.builder() Source: https://context7.com/auties00/cobalt/llms.txt Access the `WhatsAppClientBuilder`, which is the entry point for configuring and creating WhatsApp client instances. ```APIDOC ## WhatsAppClient.builder() ### Description Returns the singleton `WhatsAppClientBuilder`, the starting point for all Web and Mobile client configurations. ### Code Example ```java // Access the builder WhatsAppClientBuilder builder = WhatsAppClient.builder(); ``` ``` -------------------------------- ### builder().webClient() — Web Client (QR Code) Source: https://context7.com/auties00/cobalt/llms.txt Creates a Web client that connects via QR code scan. The QR code is printed to the terminal by default. After the initial scan, the session is serialized and reused automatically. ```APIDOC ## builder().webClient() — Web Client (QR Code) ### Description Creates a Web client that connects via QR code scan. The QR is printed to the terminal by default. After the initial scan, the session is serialized and reused automatically. ### Code Example ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientVerificationHandler; WhatsAppClient client = WhatsAppClient.builder() .webClient() // Web mode (linked device) .loadLastOrCreateConnection() // Resume last session or create new .name("MyBot") // Device name shown in "Linked Devices" .unregistered(WhatsAppClientVerificationHandler.Web.QrCode.toTerminal()) // Print QR to terminal .addLoggedInListener(api -> System.out.println("Connected!")) .addNewChatMessageListener(msg -> System.out.printf("New message from %s: %s%n", msg.senderJid(), msg.message().toJson())) .addDisconnectedListener((api, reason) -> System.out.println("Disconnected: " + reason)) .connect() .waitForDisconnection(); ``` ``` -------------------------------- ### Query Group Metadata Source: https://github.com/auties00/cobalt/blob/master/README.md Fetches the metadata for a group. The result is a CompletableFuture that needs to be joined to get the metadata. ```java var metadata = api.queryGroupMetadata(group); // A completable future .join(); // Wait for the future to complete ``` -------------------------------- ### Register and Connect to WhatsApp Source: https://github.com/auties00/cobalt/blob/master/README.md This snippet shows how to register a phone number and connect to WhatsApp. It includes handling verification codes and awaiting disconnection. ```java .verificationCodeSupplier(() -> yourAsyncOrSyncLogic()) .register(yourPhoneNumberWithCountryCode) .connect() .awaitDisconnection() ``` -------------------------------- ### WhatsAppClientBuilder.Options.registered() Source: https://context7.com/auties00/cobalt/llms.txt Loads a previously registered session without re-scanning the QR code or re-entering OTP. Returns an Optional which can be used to resume an existing connection. ```APIDOC ## `WhatsAppClientBuilder.Options.registered()` — Resume Existing Session Loads a previously registered session without re-scanning the QR code or re-entering OTP. ```java import com.github.auties00.cobalt.client.WhatsAppClient; WhatsAppClient client = WhatsAppClient.builder() .webClient() .loadLastOrCreateConnection() .registered() // Returns Optional .orElseThrow(() -> new IllegalStateException("No registered session found")) .addLoggedInListener(api -> System.out.println("Resumed session")) .connect() .waitForDisconnection(); ``` ``` -------------------------------- ### Create Community Source: https://github.com/auties00/cobalt/blob/master/README.md Create a new community with a specified name and an optional description. ```java var future = api.createCommunity("New Community Name", "Optional community description"); ``` -------------------------------- ### Set Mobile Companion Device (Android Business) Source: https://github.com/auties00/cobalt/blob/master/README.md Configures the mobile connection to use a business Android companion device. Set the boolean to `true`. ```java .device(CompanionDevice.android(true)) ``` -------------------------------- ### Set Mobile Companion Device (iOS Business) Source: https://github.com/auties00/cobalt/blob/master/README.md Configures the mobile connection to use a business iOS companion device. Set the boolean to `true`. ```java .device(CompanionDevice.ios(true)) ``` -------------------------------- ### Enable 2FA Source: https://github.com/auties00/cobalt/blob/master/README.md Enable two-factor authentication for the account. Requires a verification code and an email address. ```java var future = api.enable2fa("000000", "mail@domain.com"); ``` -------------------------------- ### Set Mobile Companion Device (iOS Standard) Source: https://github.com/auties00/cobalt/blob/master/README.md Configures the mobile connection to use a standard iOS companion device. Set the boolean to `false`. ```java .device(CompanionDevice.ios(false)) ``` -------------------------------- ### Set Mobile Companion Device (Android Standard) Source: https://github.com/auties00/cobalt/blob/master/README.md Configures the mobile connection to use a standard Android companion device. Set the boolean to `false`. ```java .device(CompanionDevice.android(false)) ``` -------------------------------- ### Set Business Website Source: https://github.com/auties00/cobalt/blob/master/README.md Sets the business website URL for a mobile connection. Provide a valid URL. ```java .businessWebsite("https://google.com") ``` -------------------------------- ### Create Community Source: https://github.com/auties00/cobalt/blob/master/README.md Creates a new community with a specified name and an optional description. ```APIDOC ## Create Community ### Description Creates a new community with a specified name and an optional description. ### Method ```java api.createCommunity(name, description) ``` ### Parameters #### Path Parameters - **name** (String) - Required - The name of the new community. - **description** (String) - Optional - A description for the community. ``` -------------------------------- ### Retrieve First Connection or Create New Source: https://github.com/auties00/cobalt/blob/master/README.md Retrieves the first available serialized connection, or creates a new one if none exist. Useful for accessing the most recently used session. ```java .firstConnection() ``` -------------------------------- ### Enable 2FA Source: https://github.com/auties00/cobalt/blob/master/README.md Enables two-factor authentication for the user's account. ```APIDOC ## Enable 2FA ### Description Enables two-factor authentication for the user's account. This is a mobile API only feature. ### Method ```java api.enable2fa(code, email) ``` ### Parameters #### Path Parameters - **code** (String) - Required - The 2FA code. - **email** (String) - Required - The email address associated with the account. ``` -------------------------------- ### Subscribe to Contact Presence using client.subscribeToPresence() Source: https://context7.com/auties00/cobalt/llms.txt Requests WhatsApp to send presence updates for specified contacts. Requires setting up a listener to receive these updates. ```java import com.github.auties00.cobalt.model.jid.Jid; Jid contact1 = Jid.of("15551234567@s.whatsapp.net"); Jid contact2 = Jid.of("15559876543@s.whatsapp.net"); // Subscribe to one or many contacts client.subscribeToPresence(contact1, contact2); // Listen for updates client.addContactPresenceListener((api, conversation, participant) -> System.out.printf("Presence update in %s for %s%n", conversation, participant)); ``` -------------------------------- ### client.pinChat() / client.archiveChat() Source: https://context7.com/auties00/cobalt/llms.txt Pins a chat to the top of the list (max 3) or archives it. ```APIDOC ## `client.pinChat()` / `client.archiveChat()` — Pin and Archive Chats ### Description Pins a chat to the top of the list (max 3) or archives it. ### Method PUT (assumed, for pinning/archiving) ### Endpoint `/chats/{chatJid}/pin` or `/chats/{chatJid}/archive` (assumed) ### Parameters #### Path Parameters - **chatJid** (Jid) - Required - The JID of the chat to pin or archive. ### Request Example ```java import com.github.auties00.cobalt.model.jid.Jid; Jid chat = Jid.of("15551234567@s.whatsapp.net"); client.pinChat(chat); // Pin (max 3 pinned chats) client.unpinChat(chat); client.archiveChat(chat); // Archive client.unarchive(chat); // Unarchive ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful pin, unpin, archive, or unarchive operation. ``` -------------------------------- ### Set Business Description Source: https://github.com/auties00/cobalt/blob/master/README.md Provides a description for the business account in a mobile connection. Keep the description concise and informative. ```java .businessDescription("A nice description") ``` -------------------------------- ### Send Media Messages (Image, Audio, Document) Source: https://context7.com/auties00/cobalt/llms.txt Sends images, audio, video, documents, and other media by wrapping a builder in `MessageContainer`. Requires reading media files into byte arrays. ```java import com.github.auties00.cobalt.model.message.model.MessageContainer; import com.github.auties00.cobalt.model.message.standard.*; import java.nio.file.Files; import java.nio.file.Path; Jid chat = Jid.of("15551234567@s.whatsapp.net"); // Image message byte[] imageBytes = Files.readAllBytes(Path.of("/tmp/photo.jpg")); var image = new ImageMessageSimpleBuilder() .media(imageBytes) .caption("A nice photo!") .build(); client.sendChatMessage(chat, MessageContainer.of(image)); // Audio message byte[] audioBytes = Files.readAllBytes(Path.of("/tmp/audio.ogg")); var audio = new AudioMessageSimpleBuilder() .media(audioBytes) .voiceMessage(true) .build(); client.sendChatMessage(chat, MessageContainer.of(audio)); // Document message byte[] docBytes = Files.readAllBytes(Path.of("/tmp/report.pdf")); var document = new DocumentMessageSimpleBuilder() .media(docBytes) .title("Q3 Report") .fileName("report.pdf") .pageCount(10) .build(); client.sendChatMessage(chat, MessageContainer.of(document)); ``` -------------------------------- ### Configure Text Message Preview Handler Source: https://github.com/auties00/cobalt/blob/master/README.md Determines whether media previews are generated for text messages containing links. Options include `ENABLED_WITH_INFERENCE`. ```java .whatsappMessagePreviewHandler(TextPreviewSetting.ENABLED_WITH_INFERENCE) ``` -------------------------------- ### Accessing the Store Source: https://github.com/auties00/cobalt/blob/master/README.md Obtain the store object to access chats, contacts, and status. Note that these fields will be empty initially and populated via events. ```java var store = api.store(); ``` -------------------------------- ### Create a Group Source: https://github.com/auties00/cobalt/blob/master/README.md Creates a new group with a specified name and initial participants. This operation returns a CompletableFuture. ```java var future = api.createGroup("A nice name :)", friend, friend2); ``` -------------------------------- ### Create New Connection by UUID Source: https://github.com/auties00/cobalt/blob/master/README.md Initiates a new connection, requiring a unique identifier. This is for establishing a fresh session. ```java .newConnection(someUuid) ``` -------------------------------- ### Pin and Archive Chats using client.pinChat() / client.archiveChat() Source: https://context7.com/auties00/cobalt/llms.txt Manages chat organization by pinning chats to the top or archiving them. Note that a maximum of 3 chats can be pinned. ```java import com.github.auties00.cobalt.model.jid.Jid; Jid chat = Jid.of("15551234567@s.whatsapp.net"); client.pinChat(chat); // Pin (max 3 pinned chats) client.unpinChat(chat); client.archiveChat(chat); // Archive client.unarchive(chat); // Unarchive ``` -------------------------------- ### Retrieve or Create Connection by Alias Source: https://github.com/auties00/cobalt/blob/master/README.md Attempts to retrieve an existing connection using an alias; if not found, it creates a new one. Aliases provide a custom identifier. ```java .newConnection(alias) ``` -------------------------------- ### client.changePresence() Source: https://context7.com/auties00/cobalt/llms.txt Broadcasts the current user's availability and chat state to contacts. ```APIDOC ## `client.changePresence()` — Set Online/Offline and Typing Status ### Description Broadcasts the current user's availability and chat state to contacts. ### Method PUT (assumed, for updating status) ### Endpoint `/presence` or `/chats/{chatJid}/presence` (assumed) ### Parameters #### Global Presence (Optional) - **isOnline** (boolean) - Required - `true` to set online, `false` to set offline. #### Chat-Specific Presence (Optional) - **chatJid** (Jid) - Required - The JID of the chat to update presence for. - **status** (ContactStatus) - Required - The presence status (e.g., COMPOSING, RECORDING). ### Request Example ```java import com.github.auties00.cobalt.model.contact.ContactStatus; import com.github.auties00.cobalt.model.jid.Jid; // Set globally available client.changePresence(true); // Set globally offline client.changePresence(false); // Show "typing..." in a specific chat Jid chat = Jid.of("15551234567@s.whatsapp.net"); client.changePresence(chat, ContactStatus.COMPOSING); // Show "recording audio..." in a specific chat client.changePresence(chat, ContactStatus.RECORDING); ``` ### Response #### Success Response (200) - **status** (string) - Indicates success of the presence update. ``` -------------------------------- ### Implement WhatsApp Client Event Listener Source: https://context7.com/auties00/cobalt/llms.txt Implement the `WhatsAppClientListener` interface to handle various WhatsApp events such as login, disconnection, new messages, and status updates. All methods have default implementations, allowing selective overriding. ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientListener; import com.github.auties00.cobalt.client.WhatsAppClientDisconnectReason; import com.github.auties00.cobalt.model.info.*; import com.github.auties00.cobalt.model.chat.Chat; import com.github.auties00.cobalt.model.contact.Contact; import java.util.Collection; public class MyListener implements WhatsAppClientListener { @Override public void onLoggedIn(WhatsAppClient client) { System.out.println("Logged in successfully"); } @Override public void onDisconnected(WhatsAppClient client, WhatsAppClientDisconnectReason reason) { System.out.println("Disconnected: " + reason); // Reason can be: DISCONNECTED, RECONNECTING, LOGGED_OUT, BANNED } @Override public void onChats(WhatsAppClient client, Collection chats) { System.out.println("Loaded " + chats.size() + " chats"); } @Override public void onContacts(WhatsAppClient client, Collection contacts) { System.out.println("Loaded " + contacts.size() + " contacts"); } @Override public void onNewMessage(WhatsAppClient client, MessageInfo info) { if (info instanceof ChatMessageInfo chatMsg) { System.out.printf("[%s] %s: %s%n", chatMsg.chatJid(), chatMsg.senderJid(), chatMsg.message().toJson()); } } @Override public void onMessageStatus(WhatsAppClient client, MessageInfo info) { System.out.println("Message " + info.id() + " status: " + info.status()); } @Override public void onMessageDeleted(WhatsAppClient client, MessageInfo info, boolean everyone) { System.out.printf("Message %s deleted (everyone=%s)%n", info.id(), everyone); } @Override public void onNewStatus(WhatsAppClient client, ChatMessageInfo status) { System.out.println("New status from: " + status.senderJid()); } } // Register the listener client.addListener(new MyListener()); // Or use fluent lambda methods: client.addNewChatMessageListener((whatsapp, msg) -> System.out.println("New message: " + msg.message().toJson())); client.addLoggedInListener(whatsapp -> System.out.println("Connected")); client.addWebHistorySyncProgressListener((whatsapp, pct, recent) -> System.out.printf("History sync: %d%% (recent=%s)%n", pct, recent)); ``` -------------------------------- ### Send Document Message Source: https://github.com/auties00/cobalt/blob/master/README.md Constructs and sends a document message, specifying title, file name, and page count. Ensure media is pre-loaded. ```java var document = new DocumentMessageSimpleBuilder() // Create a new document message builder .media(urlMedia) // Set the document of this message .title("A nice pdf") // Set the title of the document .fileName("pdf-test.pdf") // Set the name of the document .pageCount(1) // Set the value of pages of the document .build(); // Create the message api.sendMessage(chat, document); ``` -------------------------------- ### Create WhatsApp Community Source: https://context7.com/auties00/cobalt/llms.txt Creates a new WhatsApp Community (super-group) with a specified name and an optional description. The creation might fail, so handle the Optional result. ```java var meta = client.createCommunity("Dev Community", "A community for developers") .orElseThrow(() -> new RuntimeException("Community creation failed")); System.out.println("Community JID: " + meta.jid()); ``` -------------------------------- ### Configure Proxy for Socket Connection Source: https://github.com/auties00/cobalt/blob/master/README.md Specifies a proxy server to be used for the socket connection. Provide a valid proxy object. ```java .proxy(someProxy) ``` -------------------------------- ### Query Recommended Newsletters Source: https://github.com/auties00/cobalt/blob/master/README.md Fetches a list of recommended newsletters for a given country and limit. Requires country code and limit as parameters. ```java var future = api.queryRecommendedNewsletters("US", 50); // Country code and limit ``` -------------------------------- ### Resume Existing WhatsApp Session Source: https://context7.com/auties00/cobalt/llms.txt Loads a previously registered session without re-scanning the QR code or re-entering OTP. Ensure a registered session exists, otherwise an exception is thrown. ```java import com.github.auties00.cobalt.client.WhatsAppClient; WhatsAppClient client = WhatsAppClient.builder() .webClient() .loadLastOrCreateConnection() .registered() // Returns Optional .orElseThrow(() -> new IllegalStateException("No registered session found")) .addLoggedInListener(api -> System.out.println("Resumed session")) .connect() .waitForDisconnection(); ``` -------------------------------- ### Accept Group Invite Source: https://github.com/auties00/cobalt/blob/master/README.md Use this method to accept a group invitation using the provided invite code. ```java var future = api.acceptGroupInvite(inviteCode); ``` -------------------------------- ### Set Mobile Companion Device (KaiOS) Source: https://github.com/auties00/cobalt/blob/master/README.md Configures the mobile connection to use a standard KaiOS companion device. ```java .device(CompanionDevice.kaiOs()) ``` -------------------------------- ### Retrieve First Optional Connection Source: https://github.com/auties00/cobalt/blob/master/README.md Safely retrieves the first available serialized connection, returning an empty Optional if none exist. Use when the first connection might be absent. ```java .firstOptionalConnection() ``` -------------------------------- ### Accessing Companion Device JID Source: https://github.com/auties00/cobalt/blob/master/README.md Retrieve the JID of the companion device. This JID includes device information to differentiate it from the main device. ```java var companion = store.jid(); ``` -------------------------------- ### Set Online/Offline and Typing Status using client.changePresence() Source: https://context7.com/auties00/cobalt/llms.txt Broadcasts the current user's availability and chat state to contacts. Can be used to set global online/offline status or indicate typing/recording in a specific chat. ```java import com.github.auties00.cobalt.model.contact.ContactStatus; import com.github.auties00.cobalt.model.jid.Jid; // Set globally available client.changePresence(true); // Set globally offline client.changePresence(false); // Show "typing..." in a specific chat Jid chat = Jid.of("15551234567@s.whatsapp.net"); client.changePresence(chat, ContactStatus.COMPOSING); // Show "recording audio..." in a specific chat client.changePresence(chat, ContactStatus.RECORDING); ``` -------------------------------- ### Register Mobile Client via SMS OTP Source: https://context7.com/auties00/cobalt/llms.txt Register a new mobile client session by simulating an Android or iOS device and verifying via SMS OTP. Requires the phone number and an OTP input mechanism. ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientVerificationHandler; import com.github.auties00.cobalt.model.jid.JidCompanion; import java.util.Scanner; long phoneNumber = 15551234567L; WhatsAppClient client = WhatsAppClient.builder() .mobileClient() .loadOrCreateConnection(phoneNumber) .device(JidCompanion.ios(false)) // Simulate standard iOS device .name("Cobalt User") .register(phoneNumber, WhatsAppClientVerificationHandler.Mobile.ofSms(() -> { System.out.print("Enter OTP: "); return new Scanner(System.in).nextLine(); })) .addLoggedInListener(api -> System.out.println("Mobile connected")) .addNewChatMessageListener(msg -> System.out.println("Received: " + msg.message().toJson())) .connect() .waitForDisconnection(); ``` -------------------------------- ### Set WhatsApp Version Source: https://github.com/auties00/cobalt/blob/master/README.md Specifies the WhatsApp version to use for the connection. Ensure the provided version string is valid. ```java .version(new Version("x.xx.xx")) ``` -------------------------------- ### Read Media File to Byte Array in Java Source: https://github.com/auties00/cobalt/blob/master/README.md Reads the content of a media file into a byte array. This is the first step before sending media. Requires Java's Files and Path classes. Ensure the file path is correct. ```java var media = Files.readAllBytes(Path.of("somewhere")); ``` -------------------------------- ### Community Creation Source: https://context7.com/auties00/cobalt/llms.txt Creates a new WhatsApp Community (super-group) with a specified name and an optional description. ```APIDOC ## `client.createCommunity()` ### Description Creates a new WhatsApp Community (super-group) with a given name and an optional description. ### Method - `createCommunity(String name, String description)` - `createCommunity(String name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java var meta = client.createCommunity("Dev Community", "A community for developers") .orElseThrow(() -> new RuntimeException("Community creation failed")); System.out.println("Community JID: " + meta.jid()); ``` ### Response Returns metadata about the created community, including its JID. ``` -------------------------------- ### WhatsAppClientListener Source: https://context7.com/auties00/cobalt/llms.txt An interface to implement for handling various WhatsApp events such as login, disconnection, new messages, message status updates, and more. All methods have default implementations. ```APIDOC ## `WhatsAppClientListener` — Event Listener Interface Implement this interface to handle all WhatsApp events. All methods have default (no-op) implementations so you only override what you need. ### Methods - **onLoggedIn(WhatsAppClient client)**: Called when the client successfully logs in. - **onDisconnected(WhatsAppClient client, WhatsAppClientDisconnectReason reason)**: Called when the client disconnects. `reason` can be DISCONNECTED, RECONNECTING, LOGGED_OUT, BANNED. - **onChats(WhatsAppClient client, Collection chats)**: Called when the list of chats is loaded. - **onContacts(WhatsAppClient client, Collection contacts)**: Called when the list of contacts is loaded. - **onNewMessage(WhatsAppClient client, MessageInfo info)**: Called when a new message is received. Handles `ChatMessageInfo` for chat messages. - **onMessageStatus(WhatsAppClient client, MessageInfo info)**: Called when a message's status changes. - **onMessageDeleted(WhatsAppClient client, MessageInfo info, boolean everyone)**: Called when a message is deleted. - **onNewStatus(WhatsAppClient client, ChatMessageInfo status)**: Called when a new status update is received. ### Usage ```java import com.github.auties00.cobalt.client.WhatsAppClient; import com.github.auties00.cobalt.client.WhatsAppClientListener; import com.github.auties00.cobalt.client.WhatsAppClientDisconnectReason; import com.github.auties00.cobalt.model.info.*; import com.github.auties00.cobalt.model.chat.Chat; import com.github.auties00.cobalt.model.contact.Contact; import java.util.Collection; public class MyListener implements WhatsAppClientListener { @Override public void onLoggedIn(WhatsAppClient client) { System.out.println("Logged in successfully"); } @Override public void onDisconnected(WhatsAppClient client, WhatsAppClientDisconnectReason reason) { System.out.println("Disconnected: " + reason); } @Override public void onChats(WhatsAppClient client, Collection chats) { System.out.println("Loaded " + chats.size() + " chats"); } @Override public void onContacts(WhatsAppClient client, Collection contacts) { System.out.println("Loaded " + contacts.size() + " contacts"); } @Override public void onNewMessage(WhatsAppClient client, MessageInfo info) { if (info instanceof ChatMessageInfo chatMsg) { System.out.printf("[%s] %s: %s%n", chatMsg.chatJid(), chatMsg.senderJid(), chatMsg.message().toJson()); } } @Override public void onMessageStatus(WhatsAppClient client, MessageInfo info) { System.out.println("Message " + info.id() + " status: " + info.status()); } @Override public void onMessageDeleted(WhatsAppClient client, MessageInfo info, boolean everyone) { System.out.printf("Message %s deleted (everyone=%s)%n", info.id(), everyone); } @Override public void onNewStatus(WhatsAppClient client, ChatMessageInfo status) { System.out.println("New status from: " + status.senderJid()); } } // Register the listener client.addListener(new MyListener()); // Or use fluent lambda methods: client.addNewChatMessageListener((whatsapp, msg) -> System.out.println("New message: " + msg.message().toJson())); client.addLoggedInListener(whatsapp -> System.out.println("Connected")); client.addWebHistorySyncProgressListener((whatsapp, pct, recent) -> System.out.printf("History sync: %d%% (recent=%s)%n", pct, recent)); ``` ``` -------------------------------- ### Web QR Pairing for WhatsApp Connection Source: https://github.com/auties00/cobalt/blob/master/README.md Connect to WhatsApp using the Web API by displaying a QR code in the terminal for pairing. Handles connection and disconnection events, and new chat messages. ```java Whatsapp.webBuilder() .newConnection() .unregistered(QrHandler.toTerminal()) .addLoggedInListener(api -> System.out.printf("Connected: %s%n", api.store().privacySettings())) .addDisconnectedListener(reason -> System.out.printf("Disconnected: %s%n", reason)) .addNewChatMessageListener(message -> System.out.printf("New message: %s%n", message.toJson())) .connect() .join() .awaitDisconnection(); ``` -------------------------------- ### client.subscribeToPresence() Source: https://context7.com/auties00/cobalt/llms.txt Requests WhatsApp to send presence updates (online/offline, last seen) for specific contacts. ```APIDOC ## `client.subscribeToPresence()` — Subscribe to Contact Presence ### Description Requests WhatsApp to send presence updates (online/offline, last seen) for specific contacts. ### Method POST (assumed, for subscribing) ### Endpoint `/presence/subscriptions` (assumed) ### Parameters #### Contacts - **contacts** (Array) - Required - A list of JIDs for the contacts to subscribe to presence updates for. ### Request Example ```java import com.github.auties00.cobalt.model.jid.Jid; Jid contact1 = Jid.of("15551234567@s.whatsapp.net"); Jid contact2 = Jid.of("15559876543@s.whatsapp.net"); // Subscribe to one or many contacts client.subscribeToPresence(contact1, contact2); // Listen for updates client.addContactPresenceListener((api, conversation, participant) -> System.out.printf("Presence update in %s for %s%n", conversation, participant)); ``` ### Response #### Success Response (200) - **status** (string) - Indicates successful subscription request. ``` -------------------------------- ### Promote Participants to Admin Source: https://github.com/auties00/cobalt/blob/master/README.md Promote one or more participants to admin roles within a community. ```java var future = api.promoteCommunityParticipants(communityJid, contactJid1, contactJid2); ``` -------------------------------- ### Send Video Message Source: https://github.com/auties00/cobalt/blob/master/README.md Constructs and sends a video message with optional dimensions and caption. Ensure media is pre-loaded. ```java var video = new VideoMessageSimpleBuilder() // Create a new video message builder .media(urlMedia) // Set the video of this message .caption("A nice video") // Set the caption of this message .width(100) // Set the width of the video .height(100) // Set the height of the video .build(); // Create the message api.sendMessage(chat, video); ``` -------------------------------- ### Create WhatsApp Group Source: https://context7.com/auties00/cobalt/llms.txt Create a new WhatsApp group with specified members. Optionally, an ephemeral timer can be set for the group. ```java import com.github.auties00.cobalt.model.chat.ChatEphemeralTimer; import com.github.auties00.cobalt.model.jid.Jid; Jid member1 = Jid.of("15551234567@s.whatsapp.net"); Jid member2 = Jid.of("15559876543@s.whatsapp.net"); // Basic group var metadata = client.createGroup("My Group", member1, member2) .orElseThrow(() -> new RuntimeException("Group creation failed")); System.out.println("Created group: " + metadata.jid()); // Group with 1-week ephemeral timer client.createGroup("Ephemeral Group", ChatEphemeralTimer.ONE_WEEK, member1, member2); ``` -------------------------------- ### Send Video Message Source: https://github.com/auties00/cobalt/blob/master/README.md Build and send a video message with optional caption, width, and height. Media can be provided as a URL. ```APIDOC ## Send Video Message ### Description Sends a video message with optional caption, width, and height. The media can be provided as a URL. ### Method ```java api.sendMessage(chat, video); ``` ### Parameters #### Request Body (VideoMessageSimpleBuilder) - **media** (URL or byte[]) - Required - The video data. - **caption** (String) - Optional - The caption for the video. - **width** (int) - Optional - The width of the video. - **height** (int) - Optional - The height of the video. ### Request Example ```java var video = new VideoMessageSimpleBuilder() .media(urlMedia) .caption("A nice video") .width(100) .height(100) .build(); api.sendMessage(chat, video); ``` ### Response This method does not return a value, but sends the message to the specified chat. ``` -------------------------------- ### Create WhatsApp Newsletter/Channel Source: https://context7.com/auties00/cobalt/llms.txt Creates a WhatsApp Newsletter (channel) with an optional description and profile picture. The profile picture must be provided as a byte array. ```java import java.nio.file.Files; import java.nio.file.Path; // Simple newsletter var newsletter = client.createNewsletter("My Channel") .orElseThrow(); System.out.println("Channel JID: " + newsletter.jid()); // Newsletter with description and picture byte[] pic = Files.readAllBytes(Path.of("/tmp/channel_icon.jpg")); var fullNewsletter = client.createNewsletter("Tech News", "Daily tech updates", pic) .orElseThrow(); ``` -------------------------------- ### client.createGroup() — Create Group Source: https://context7.com/auties00/cobalt/llms.txt Creates a new WhatsApp group with an optional ephemeral timer. Requires group name and participant JIDs. ```APIDOC ## `client.createGroup()` — Create Group Creates a new WhatsApp group with optional ephemeral timer. ### Method ```java client.createGroup(String groupName, ChatEphemeralTimer timer, Jid... participants) client.createGroup(String groupName, Jid... participants) ``` ### Parameters #### Common Parameters - **groupName** (String) - Required - The name of the group to be created. - **participants** (Jid...) - Required - A variable number of JIDs representing the initial participants of the group. #### Specific Parameter for Timed Groups - **timer** (ChatEphemeralTimer) - Optional - Specifies the ephemeral timer for the group (e.g., ONE_WEEK). ### Request Example ```java import com.github.auties00.cobalt.model.chat.ChatEphemeralTimer; import com.github.auties00.cobalt.model.jid.Jid; Jid member1 = Jid.of("15551234567@s.whatsapp.net"); Jid member2 = Jid.of("15559876543@s.whatsapp.net"); // Basic group var metadata = client.createGroup("My Group", member1, member2) .orElseThrow(() -> new RuntimeException("Group creation failed")); System.out.println("Created group: " + metadata.jid()); // Group with 1-week ephemeral timer client.createGroup("Ephemeral Group", ChatEphemeralTimer.ONE_WEEK, member1, member2); ``` ``` -------------------------------- ### Send Group Invite Message in Java Source: https://github.com/auties00/cobalt/blob/master/README.md Constructs and sends a message containing a group invite. This requires finding the group, querying its invite code, and then building the GroupInviteMessage. Ensure the group exists and the invite expiration is set appropriately. ```java var group = api.store() .findChatByName("Programmers") .filter(Chat::isGroup) .orElseThrow(() -> new NoSuchElementException("Hey, you don't exist")); var inviteCode = api.queryGroupInviteCode(group).join(); var groupInvite = new GroupInviteMessageBuilder() // Create a new group invite message .caption("Come join my group of fellow programmers") // Set the caption of this message .name(group.name()) // Set the name of the group .groupJid(group.jid())) // Set the value of the group .inviteExpiration(ZonedDateTime.now().plusDays(3).toEpochSecond()) // Set the expiration of this invite .inviteCode(inviteCode) // Set the code of the group .build(); // Create the message api.sendMessage(chat, groupInvite); ``` -------------------------------- ### Register Listener: Standalone Concrete Implementation Source: https://github.com/auties00/cobalt/blob/master/README.md Implement the `WhatsAppClientListener` interface in a separate class for complex applications. Remember to register the listener using `api.addListener()`. ```java import com.github.auties00.cobalt.listener.WhatsAppClientListener; public class MyListener implements com.github.auties00.cobalt.listener.WhatsAppClientListener { @Override public void onLoggedIn() { System.out.println("Hello :)"); } } ``` ```java api.addListener(new MyListener()); ``` -------------------------------- ### client.sendStatus() Source: https://context7.com/auties00/cobalt/llms.txt Posts a status update (story) to WhatsApp, supporting both text-based and media-based updates like images. ```APIDOC ## `client.sendStatus()` — Send WhatsApp Status Update Posts a status update (story) visible to contacts, supporting text and media. ```java import com.github.auties00.cobalt.model.message.model.MessageContainer; import com.github.auties00.cobalt.model.message.standard.ImageMessageSimpleBuilder; import java.nio.file.Files; import java.nio.file.Path; // Text status client.sendStatus("Good morning! ☀️"); // Image status byte[] imageBytes = Files.readAllBytes(Path.of("/tmp/banner.jpg")); var imageStatus = new ImageMessageSimpleBuilder() .media(imageBytes) .caption("Check this out!") .build(); client.sendStatus(MessageContainer.of(imageStatus)); ``` ``` -------------------------------- ### Add Participants to Community Source: https://github.com/auties00/cobalt/blob/master/README.md Add one or more participants to a community. They will be added to the announcement group. ```java var future = api.addCommunityParticipants(communityJid, contactJid1, contactJid2); ``` -------------------------------- ### Create Group Source: https://github.com/auties00/cobalt/blob/master/README.md Creates a new group with specified participants. ```APIDOC ## Create Group ### Description Creates a new group with a given name and initial participants. ### Method ```java api.createGroup("A nice name :)", friend, friend2); ``` ``` -------------------------------- ### Accept Newsletter Admin Invite Source: https://github.com/auties00/cobalt/blob/master/README.md Accepts an invitation to become a newsletter administrator. Requires newsletter JID. ```java var future = api.acceptNewsletterAdminInvite(newsletterJid); ``` -------------------------------- ### Querying All Status Source: https://github.com/auties00/cobalt/blob/master/README.md Retrieve all status information currently stored in memory. ```java var status = store.status(); ``` -------------------------------- ### Retrieve Optional Connection by UUID Source: https://github.com/auties00/cobalt/blob/master/README.md Safely retrieves an existing connection by UUID, returning an empty Optional if not found. Use this when a connection might not exist. ```java .newOptionalConnection(someUuid) ``` -------------------------------- ### Send Image Message Source: https://github.com/auties00/cobalt/blob/master/README.md Constructs and sends an image message with an optional caption. Ensure media is pre-loaded. ```java var image = new ImageMessageSimpleBuilder() // Create a new image message builder .media(media) // Set the image of this message .caption("A nice image") // Set the caption of this message .build(); // Create the message api.sendMessage(chat, image); ``` -------------------------------- ### Register Session as Registered Source: https://github.com/auties00/cobalt/blob/master/README.md Marks the session as registered, indicating that the QR code has been scanned or the OTP sent. Use when the session is already authenticated. ```java .registered() ``` -------------------------------- ### client.changeAbout() / client.changeName() — Profile Updates Source: https://context7.com/auties00/cobalt/llms.txt Updates the user's display name and about/status text. Also includes functionality to change the profile picture. ```APIDOC ## `client.changeAbout()` / `client.changeName()` — Profile Updates Updates the user's display name and about/status text. ### Method ```java client.changeName(String name) client.changeAbout(String about) client.changeProfilePicture(InputStream pictureStream) ``` ### Parameters #### `changeName` - **name** (String) - Required - The new display name for the user. #### `changeAbout` - **about** (String) - Required - The new about/status text for the user. #### `changeProfilePicture` - **pictureStream** (InputStream) - Required - An input stream containing the profile picture data. ### Request Example ```java client.changeName("Cobalt Bot"); client.changeAbout("Powered by the Cobalt library"); // Change profile picture try (var stream = new java.io.FileInputStream("/tmp/avatar.jpg")) { client.changeProfilePicture(stream); } ``` ``` -------------------------------- ### Send GIF Message Source: https://github.com/auties00/cobalt/blob/master/README.md Build and send a GIF message (which is a video with specific attributes) with an optional caption and attribution. Media can be provided as a URL. ```APIDOC ## Send GIF Message ### Description Sends a GIF message, which is essentially a video configured to play as a GIF. Supports optional caption and attribution. ### Method ```java api.sendMessage(chat, gif); ``` ### Parameters #### Request Body (GifMessageSimpleBuilder) - **media** (URL or byte[]) - Required - The GIF data (video format). - **caption** (String) - Optional - The caption for the GIF. - **gifAttribution** (VideoMessageAttribution) - Optional - The source of the GIF (e.g., TENOR). ### Request Example ```java var gif = new GifMessageSimpleBuilder() .media(urlMedia) .caption("A nice gif") .gifAttribution(VideoMessageAttribution.TENOR) .build(); api.sendMessage(chat, gif); ``` ### Response This method does not return a value, but sends the message to the specified chat. **Note:** Whatsapp does not support conventional GIFs. Videos must be used and configured appropriately. ``` -------------------------------- ### Register Session as Unregistered (Web QR Code) Source: https://github.com/auties00/cobalt/blob/master/README.md Creates an unregistered session for the Web API, prompting for QR code scanning. The QR code will be displayed in the terminal. ```java .unregistered(QrHandler.toTerminal()) ```