MCPcopy Index your code
hub / github.com/Auties00/Cobalt

github.com/Auties00/Cobalt @whatsappweb4j-2.2.7

Chat with this repo
repository ↗ · DeepWiki ↗ · release whatsappweb4j-2.2.7 ↗ · + Follow
741 symbols 2,576 edges 169 files 381 documented · 51%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

WhatsappWeb4j

What is WhatsappWeb4j

WhatsappWeb4j is a standalone library built to interact with WhatsappWeb. This means that no browser, application or any additional software is necessary to use this library. This library was built for Java 17.

How to install

Maven

Add this dependency to your dependencies in the pom:

<dependency>
    <groupId>com.github.auties00</groupId>
    <artifactId>whatsappweb4j</artifactId>
    <version>2.2.6</version>
</dependency>

Gradle

Add this dependency to your build.gradle:

implementation 'com.github.auties00:whatsappweb4j:2.2.6'

Examples

If you need some examples to get started, check the examples' directory in this project. There are several easy and documented projects and more will come.

Javadocs

Javadocs for WhatsappWeb4j are available here, all contributions are welcomed!

How to contribute

As of today, no additional configuration is needed to edit this project. I recommend using the latest version of IntelliJ.

  1. Fork this project
  2. Clone the new repo
  3. Create a new branch
  4. Once you have implemented the new feature, create a new merge request

If you are trying to implement a feature that is present on WhatsappWeb's WebClient, for example audio or video calls, consider using WhatsappWeb4jRequestAnalyzer, a tool I built for this exact purpose.

How to configure WhatsappWeb4j

To use this library, start by initializing an instance of WhatsappAPI:

var api = new WhatsappAPI();

Alternatively, you can provide a custom WhatsappConfiguration:

var configuration = WhatsappConfiguration.builder()
        .whatsappUrl("wss://web.whatsapp.com/ws") // WhatsappWeb's WebSocket URL
        .requestTag("requestTag") // The tag used for requests made to WhatsappWeb's WebSocket
        .description("Whatsapp4j") // The description provided to Whatsapp during the authentication process
        .shortDescription("W4J") // An acronym for the description
        .reconnectWhenDisconnected((reason) -> true) // Determines whether the connection should be reclaimed
        .async(true) // Determines whether requests sent to whatsapp should be asyncronous or not
        .build(); // Builds an instance of WhatsappConfiguration

var api = new WhatsappAPI(configuration);

Now create a WhatsappListener, remember to implement only the methods that you need:

public class YourAwesomeListener implements WhatsappListener {
   public void onLoggedIn(@NonNull UserInformationResponse info) {
      System.out.println("Connected :)");
   }

   public void onDisconnected() {
      System.out.println("Disconnected :(");
   }
}

There are two ways to register listeners: 1. Manually

```java
api.registerListener(new YourAwesomeListener());
```
  1. Automatically > IMPORTANT: Only listeners that provide a no arguments' constructor can be discovered automatically

    Annotate your listener using @RegisterListener: ```java import it.auties.whatsapp4j.listener.RegisterListener; import it.auties.whatsapp4j.listener.WhatsappListener;

    @RegisterListener public class YourAwesomeListener implements WhatsappListener { } ```

    then enable auto-detection: java api.autodetectListeners();

Now open a connection with WhatsappWeb:

api.connect();

When your program is done, disconnect from WhatsappWeb:

api.disconnect();

Or logout:

api.logout();

In memory data

All the messages, chats and contacts stored in memory can be accessed using the singleton WhatsappDataManager:

var manager = api.manager(); // Get an instance of WhatsappDataManager
var chats = manager.chats(); // Get all the chats in memory
var contacts = manager.contacts(); // Get all the contacts in memory
var number = manager.phoneNumberJid(); // Get your phone number as a jid

IMPORTANT: When your program first starts up, these fields will be empty. To be notified when they are populated, implement the corresponding method in a WhatsappListener

This class also exposes various methods to query data as explained in the javadocs:

Optional<Contact> findContactByJid(String jid);
Optional<Contact> findContactByName(String name);
Set<Contact> findContactsByName(String name);

Optional<Chat> findChatByJid(String jid);
Optional<Chat> findChatByName(String name);
Set<Chat> findChatsByName(String name);
Optional<Chat> findChatByMessage(MessageInfo message);

Optional<MessageInfo> findMessageById(Chat chat, String id);

The keys linked to an active session can be accessed using WhatsappKeysManager.

Send a message

Simple text message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name
api.sendMessage(chat, "Hello my friend :)"); // Send the text message
Rich text message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name
var message = TextMessage.newTextMessage() // Create a new text message builder
        .text("Check this video out: https://www.youtube.com/watch?v=dQw4w9WgXcQ") // Set the text to "A nice and complex message"
        .canonicalUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ") // Set the url
        .matchedText("https://www.youtube.com/watch?v=dQw4w9WgXcQ") // Set the matched text for the url in the message
        .title("A nice suprise") // Set the title of the url
        .description("Check me out") // Set the description of the url
        .create(); // Create the message
api.sendMessage(chat, message); // Send the rich text message
Image message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name

// Read the file you want to send as an array of bytes, here are two common examples
var fileMedia = Files.readAllBytes(file.toPath()); // Read a media from a file 
var urlMedia = new URL(url).openStream().readAllBytes(); // Read a media from an url 

var image = ImageMessage.newImageMessage() // Create a new image message builder
        .media(urlMedia) // Set the image of this message
        .caption("A nice image") // Set the caption of this message
        .create(); // Create the message
api.sendMessage(chat, image); // Send the image message
Audio message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name

// Read the file you want to send as an array of bytes, here are two common examples
var fileMedia = Files.readAllBytes(file.toPath()); // Read a media from a file 
var urlMedia = new URL(url).openStream().readAllBytes(); // Read a media from an url 

var audio = AudioMessage.newAudioMessage() // Create a new audio message builder
        .media(urlMedia) // Set the audio of this message
        .voiceMessage(false) // Set whether this message is a voice message or a standard audio message
        .create(); // Create the message
api.sendMessage(chat, audio); // Send the audio message
Video message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name

// Read the file you want to send as an array of bytes, here are two common examples
var fileMedia = Files.readAllBytes(file.toPath()); // Read a media from a file 
var urlMedia = new URL(url).openStream().readAllBytes(); // Read a media from an url 

var video = VideoMessage.newVideoMessage() // 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
        .create(); // Create the message
api.sendMessage(chat, video); // Send the video message
Gif message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name

// Read the file you want to send as an array of bytes, here are two common examples
var fileMedia = Files.readAllBytes(file.toPath()); // Read a media from a file 
var urlMedia = new URL(url).openStream().readAllBytes(); // Read a media from an url 

var gif = VideoMessage.newGifMessage() // Create a new gif message builder
        .media(urlMedia) // Set the gif of this message
        .caption("A nice video") // Set the caption of this message
        .gifAttribution(VideoMessageAttribution.TENOR) // Set the source of the gif
        .create(); // Create the message
api.sendMessage(chat, gif); // Send the gif message

IMPORTANT: Whatsapp doesn't support conventional gifs. Instead, videos can be played as gifs if particular attributes are set. This is the reason why the gif builder is under the VideoMessage class. Sending a conventional gif will result in an exception if detected or in undefined behaviour.

Document message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name

// Read the file you want to send as an array of bytes, here are two common examples
var fileMedia = Files.readAllBytes(file.toPath()); // Read a media from a file 
var urlMedia = new URL(url).openStream().readAllBytes(); // Read a media from an url 

var document = DocumentMessage.newDocumentMessage() // 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 number of pages of the document
        .create(); // Create the message
api.sendMessage(chat, document); // Send the docuemnt message
Location message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name
var location = LocationMessage.newLocationMessage() // Create a new location message
        .caption("Look at this!") // Set the caption of the message, that is the text below the file. Not available if this message is live
        .degreesLatitude(38.9193) // Set the longitude of the location to share
        .degreesLongitude(1183.1389) // Set the latitude of the location to share
        .live(false) // Set whether this location is live or not
        .create(); // Create the message
api.sendMessage(chat, location); // Send the location message
Live location message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name
var location = LiveLocationMessage.newLiveLocationMessage() // Create a new live location message
        .caption("Look at this!") // Set the caption of the message, that is the text below the file. Not available if this message is live
        .degreesLatitude(38.9193) // Set the longitude of the location to share
        .degreesLongitude(1183.1389) // Set the latitude of the location to share
        .accuracyInMeters(10) // Set the accuracy of the location in meters
        .speedInMps(12) // Set the speed of the device sharing the location in meter per seconds
        .create(); // Create the message
api.sendMessage(chat, location); // Send the location message

IMPORTANT: Updating the position of a live location message is not supported as of now out of the box. The tools to do so are in the API though so, if you'd like to write a developer friendly method to do so, know that all contributions are welcomed!

Group invite message
var chat = api.findChatByName("My Awesome Friend").orElseThrow(); // Query a chat by name
var group = api.findChatByName("Fellow Programmers 1.0").orElseThrow(); // Query a group

var groupCode = api.queryGroupInviteCode(group).get().code(); // Query the invitation code of the group
var groupInvite = GroupInviteMessage.newGroupInviteMessage() // Create a new group invite message
        .caption("Come join my group of fellow programmers") // Set the caption of this message
        .groupName(group.displayName()) // Set the name of the group
        .groupJid(group.jid())) // Set the jid of the group
        .inviteExpiration(ZonedDateTime.now().plusDays(3).toInstant().toEpochMilli()) // Set the expiration of this invite
        .inviteCode(code) // Set the code of the group, this can be obtained also when a contact cannot be added as a member to a group
        .create(); // Create the message
api.sendMessage(chat, groupInvite); // Send the invite message
Con

Extension points exported contracts — how you extend this code

JsonResponseModel (Interface)
An interface to represent a class that may represent a JSON String sent by WhatsappWeb's WebSocket [22 implementers]
src/main/java/it/auties/whatsapp4j/response/model/json/JsonResponseModel.java
Command (Interface)
(no doc) [2 implementers]
examples/commands/src/main/java/org/example/whatsapp/command/Command.java
Sodium (Interface)
(no doc)
src/test/java/it/auties/whatsapp4j/test/sodium/Sodium.java
WhatsappListener (Interface)
This interface can be used to listen for events fired when new information is sent by WhatsappWeb's socket. A WhatsappLi [5 …
src/main/java/it/auties/whatsapp4j/listener/WhatsappListener.java
BusinessMessage (Interface)
A model interface that represents a WhatsappMessage sent by a WhatsappBusiness account. This interface is sealed to pre [4 …
src/main/java/it/auties/whatsapp4j/protobuf/message/model/BusinessMessage.java
PaymentMessage (Interface)
A model interface that represents a WhatsappMessage sent by a WhatsappBusiness account or by yourself regarding a paymen [4 …
src/main/java/it/auties/whatsapp4j/protobuf/message/model/PaymentMessage.java
DeviceMessage (Interface)
A model interface that represents a WhatsappMessage sent by the device linked to this whatsapp web session. This interf [2 …
src/main/java/it/auties/whatsapp4j/protobuf/message/model/DeviceMessage.java

Core symbols most depended-on inside this repo

attr
called by 131
src/main/java/it/auties/whatsapp4j/utils/WhatsappUtils.java
data
called by 51
src/main/java/it/auties/whatsapp4j/protobuf/chat/GroupAction.java
attributes
called by 49
src/main/java/it/auties/whatsapp4j/utils/WhatsappUtils.java
isTrue
called by 43
src/main/java/it/auties/whatsapp4j/utils/internal/Validate.java
session
called by 41
src/main/java/it/auties/whatsapp4j/whatsapp/internal/WhatsappWebSocket.java
send
called by 40
src/main/java/it/auties/whatsapp4j/request/model/Request.java
status
called by 38
src/main/java/it/auties/whatsapp4j/response/impl/json/UserStatusResponse.java
callListeners
called by 31
src/main/java/it/auties/whatsapp4j/manager/WhatsappDataManager.java

Shape

Method 550
Class 147
Enum 33
Interface 11

Languages

Java100%

Modules by API surface

src/test/java/it/auties/whatsapp4j/test/ci/WhatsappTest.java55 symbols
src/main/java/it/auties/whatsapp4j/whatsapp/WhatsappAPI.java53 symbols
src/main/java/it/auties/whatsapp4j/manager/WhatsappDataManager.java48 symbols
src/main/java/it/auties/whatsapp4j/whatsapp/internal/WhatsappWebSocket.java39 symbols
src/main/java/it/auties/whatsapp4j/listener/WhatsappListener.java32 symbols
src/main/java/it/auties/whatsapp4j/binary/BinaryDecoder.java24 symbols
src/main/java/it/auties/whatsapp4j/binary/BinaryEncoder.java21 symbols
src/main/java/it/auties/whatsapp4j/binary/BinaryArray.java18 symbols
src/main/java/it/auties/whatsapp4j/protobuf/chat/Chat.java15 symbols
src/main/java/it/auties/whatsapp4j/protobuf/info/MessageInfo.java14 symbols
src/main/java/it/auties/whatsapp4j/utils/internal/CypherUtils.java12 symbols
src/main/java/it/auties/whatsapp4j/response/model/json/JsonResponse.java12 symbols

For agents

$ claude mcp add Cobalt \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page