Ссылка русскоязычную инструкцию
whatsapp-api-client-java is a library for integration with WhatsApp messenger using the API service green-api.com. You should get a registration token and an account ID in your personal cabinet to use the library. There is a free developer account tariff.
The documentation for the REST API can be found at the link. The library is a wrapper for the REST API, so the documentation at the link above also applies.
To send a message or perform other Green API methods, the WhatsApp account in the phone app must be authorized. To authorize the account, go to your cabinet and scan the QR code using the WhatsApp app.
Maven
<dependency>
<groupId>com.green-api</groupId>
<artifactId>whatsapp-api-client-java</artifactId>
<version>version</version>
</dependency>
Gradle
implementation group: 'com.green-api', name: 'whatsapp-api-client-java', version: 'version'
You can configure your bean, use application.yml, or instantiate class via the constructor.
Via configuration:
@Configuration
public class GreenApiConf {
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder().build();
}
@Bean
public GreenApi greenApi(RestTemplate restTemplate) {
return new GreenApi(
restTemplate,
"https://media.greenapi.com",
"https://api.greenapi.com",
"{{YOUR-ID}}",
"{{YOUR-TOKEN}}");
}
}
Via application.yml:
To use a ready-made bean that is created based on application.yml parameters, specify the parameters of your instance in the application.yml file as follows:
green-api:
host: https://api.green-api.com
hostMedia: https://media.green-api.com
instanceId: {{yourInstance}}
token: {{yourToken}}
Make sure you have a RestTemplate
bean with your configuration, like this:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder){
return restTemplateBuilder.build();
}
And add com.greenapi.client
to the base scanning packages using the @ComponentScan
annotation:
@SpringBootApplication
@ComponentScan(basePackages = {"com.greenapi.client", "com.example"})
public class Application {
public static void main(String[] args) {
var context = SpringApplication.run(Application.class, args);
}
}
Via constructor:
var restTemplate = new RestTemplateBuilder().build();
var greenApi1 = new GreenApi(
restTemplate,
"https://media.green-api.com",
"https://api.green-api.com",
{{instanceId1}},
{{instanceToken1}});
var greenApi2 = new GreenApi(
restTemplate,
"https://media.greenapi.com",
"https://api.greenapi.com",
{{instanceId2}},
{{instanceToken2}});
Link to example: sendMessageExample.java.
@Log4j2
public class SendMessageExample {
private void sendMessageExample(GreenApi greenApi) {
var message = greenApi.sending.sendMessage(
OutgoingMessage.builder()
.chatId("111111111111@c.us")
.message("hola a todos")
.build());
if (message.getStatusCode().is2xxSuccessful()) {
log.info(message.getBody());
} else {
log.warn("Message isn't sent, status code: " + message.getStatusCode());
}
}
}
Link to example: CreateGroupSendMessageExample.java.
@Log4j2
class CreateGroupSendMessageExample {
private void createGroupAndSendMessage(GreenApi greenApi) {
var groupMembers = new ArrayList<String>();
groupMembers.add("11001234567@c.us");
groupMembers.add("11001234566@c.us");
groupMembers.add("11001234565@c.us");
var group = greenApi.groups.createGroup(
CreateGroupReq.builder()
.groupName("Test Group")
.chatIds(groupMembers)
.build()).getBody();
if (group != null) {
var message = greenApi.sending.sendMessage(
OutgoingMessage.builder()
.chatId(group.getChatId())
.message("hola a todos")
.build()).getBody();
if (message != null) {
log.info("Create group: " + group.isCreated() +
"\nSend message: " + message.getIdMessage());
}
}
}
}
To send a file, you need to give the path to the file.
Link to example: SendFileByUploadExample.java.
@Log4j2
public class SendFileByUploadExample {
private void sendFileByUploadExample(GreenApi greenApi) {
var file = new File("User/username/folder/Go-Logo_Blue.svg");
var response = greenApi.sending.sendFileByUpload(OutgoingFileByUpload.builder()
.file(file)
.fileName(file.getName())
.chatId("11001234567@c.us")
.build());
if (response.getStatusCode().isError()) {
log.warn("message sending is failed");
}
log.info("message sent, id: " + Objects.requireNonNull(response.getBody()).getIdMessage());
}
}
Link to example: SendFileByUrlExample.java.
@Log4j2
public class SendFileByUrlExample {
private void sendFileByUrlExample(GreenApi greenApi) {
var response = greenApi.sending.sendFileByUrl(OutgoingFileByUrl.builder()
.urlFile("https://go.dev/blog/go-brand/Go-Logo/SVG/Go-Logo_Blue.svg")
.fileName("Go-Logo_Blue.svg")
.chatId("11001234567@c.us")
.build());
if (response.getStatusCode().isError()) {
log.warn("message sending is failed");
}
log.info("message sent, id: " + Objects.requireNonNull(response.getBody()).getIdMessage());
}
}
Link to example: UploadFileAndSendByUrlExample.java.
@Log4j2
public class UploadFileAndSendByUrlExample {
private void uploadExample(GreenApi greenApi) throws IOException {
var file = new File("User/username/folder/Go-Logo_Blue.svg");
var response = greenApi.sending.uploadFile(file);
if (response.getStatusCode().isError()) {
log.error("upload file failed");
}
var responseEntity = greenApi.sending.sendFileByUrl(
OutgoingFileByUrl.builder()
.urlFile(Objects.requireNonNull(response.getBody()).getUrlFile())
.build());
log.info("file sent, message id: " + Objects.requireNonNull(responseEntity.getBody()).getIdMessage());
}
}
Link to example: SendPollExample.java.
@Log4j2
public class SendPollExample {
private void sendPollExample(GreenApi greenApi) {
var options = new ArrayList<Option>();
options.add(new Option("option 1"));
options.add(new Option("option 2"));
options.add(new Option("option 3"));
var dto = OutgoingPoll.builder()
.chatId("111111111111@c.us")
.message("text message")
.options(options)
.multipleAnswers(false)
.build();
var response = greenApi.sending.sendPoll(dto);
log.info(response);
}
}
To start receiving notifications, you need to pass a handler function to webhookConsumer.start()
.
The handler function should implement the WebhookHandler
interface.
When a new notification is received, your handler function will be executed.
To stop receiving notifications, you need to call the webhookConsumer.stop(
) function.
WebhookConsumer
is a class responsible for processing messages. For its correct functioning, it requires GreenApi
and NotificationMapper
.
You can inject them into it using beans or through the constructor.
NotificationMapper
is a bean responsible for converting a JSON object into a Java object.
It uses the ObjectMapper
from the com.fasterxml.jackson
library, which should be available as a bean in your configuration or set via the constructor.
WebhookHandler
is an interface. You can write any class to handle notifications; just implement the interface
and execute your logic in the handle()
method or use a lambda expression.
public interface WebhookHandler {
void handle(Notification notification);
}
Link to example: WebhookExample.java.
@SpringBootApplication
public class WebhookExample {
public static void main(String[] args) {
var context = SpringApplication.run(WebhookExample.class, args);
var webhookConsumer = (WebhookConsumer) context.getBean("webhookConsumer");
webhookConsumer.start(notification -> System.out.println("New webhook received: " + notification));
}
}
Since each notification is automatically cast to a java object, you can filter the notification by any field yourself. A description of the structure of notification objects can be found at this link: Documentation For convenience, all types of hooks and messages are named similarly to the documentation:
Java object | Webhook's json object |
---|---|
TextMessageWebhook |
TextMessage |
TemplateMessageWebhook |
TemplateMessage |
StickerMessageWebhook |
StickerMessage |
ReactionMessageWebhook |
ReactionMessage |
QuotedMessageWebhook |
QuotedMessage |
PollUpdateMessageWebhook |
PollUpdateMessage |
PollMessageWebhook |
PollMessage |
LocationMessageWebhook |
LocationMessage |
ListMessageWebhook |
ListMessage |
GroupInviteMessageWebhook |
GroupInviteMessage |
FileMessageWebhook |
imageMessage, videoMessage, documentMessage, audioMessage |
ExtendedTextMessageWebhook |
ExtendedTextMessage |
ButtonsMessageWebhook |
ButtonsMessage |
ContactMessageWebhook |
ContactMessage |
ContactsArrayMessageWebhook |
ContactMessage |
TemplateButtonsReplyMessageWebhook |
TemplateButtonsReplyMessage |
ButtonsResponseMessageWebhook |
ButtonsResponseMessage |
ListResponseMessageWebhook |
ListResponseMessage |
Description | Link to example |
---|---|
How to send message | SendMessageExample.java |
How to create a group and send message | CreateGroupSendMessageExample.java |
How to send a file by uploading from the disk | SendFileByUploadExample.java |
How to send a file by URL | SendFileByUrlExample.java |
How to send a file by UploadFile + SendByUrl | UploadFileAndSendByUrlExample.java |
How to receive incoming notifications | WebhookExample.java |
Method | Description | Documentation |
---|---|---|
account.getSettings() |
The method is aimed for getting the current settings of the account settings | GetSettings{:target="_blank"} |
account.setSettings() |
The method is aimed for setting an account settings settings | SetSettings{:target="_blank"} |
account.getStateInstance() |
The method is aimed for getting the account state | GetStateInstance{:target="_blank"} |
account.getStatusInstance() |
The method is aimed for getting the status of the account instance socket connection with WhatsApp | GetStatusInstance{:target="_blank"} |
account.reboot() |
The method is aimed for rebooting an account | Reboot{:target="_blank"} |
account.logout() |
The method is aimed for logging out an account | Logout{:target="_blank"} |
account.qr() |
The method is aimed for getting QR code | QR{:target="_blank"} |
account.getAuthorizationCode() |
The method is intended to authorize an instance by phone number. The method is used as an alternative to the QR method. | GetAuthorizationCode{:target="_blank"} |
account.setProfilePicture() |
The method is aimed for setting an account picture | SetProfilePicture{:target="_blank"} |
device.getDeviceInfo() |
The method is aimed for getting information about the device (phone) running WhatsApp Business application | GetDeviceInfo{:target="_blank"} |
groups.createGroup() |
The method adds a participant to a group chat. IMPORTANT: If one tries to create a group with a non-existent number, WhatsApp may block the sender's number. | CreateGroup{:target="_blank"} |
groups.updateGroupName() |
The method changes a group chat name | UpdateGroupName{:target="_blank"} |
groups.getGroupData() |
The method gets group chat data | GetGroupData{:target="_blank"} |
groups.addGroupParticipant() |
The method adds a participant to a group chat | AddGroupParticipant{:target="_blank"} |
groups.removeGroupParticipant() |
The method removes a participant from a group chat | RemoveGroupParticipant{:target="_blank"} |
groups.setGroupAdmin() |
The method sets a group chat participant as an administrator | SetGroupAdmin{:target="_blank"} |
groups.removeAdmin() |
The method removes a participant from group chat administartion rights | RemoveAdmin{:target="_blank"} |
groups.setGroupPicture() |
The method sets a group picture | SetGroupPicture{:target="_blank"} |
groups.leaveGroup() |
The method makes the current account user leave the group chat | LeaveGroup{:target="_blank"} |
journals.getChatHistory() |
The method returns the chat message history | GetChatHistory{:target="_blank"} |
journals.getMessage() |
The method returns the chat message | GetMessage{:target="_blank"} |
journals.lastIncomingMessages() |
The method returns the last incoming messages of the account. In the default mode the incoming messages for 24 hours are returned | LastIncomingMessages{:target="_blank"} |
journals.lastOutgoingMessages() |
The method returns the last outgoing messages of the account. In the default mode the last messages for 24 hours are returned | LastOutgoingMessages{:target="_blank"} |
queues.showMessagesQueue() |
The method is aimed for getting a list of messages in the queue to be sent | ShowMessagesQueue{:target="_blank"} |
queues.slearMessagesQueue() |
The method is aimed for clearing the queue of messages to be sent | ClearMessagesQueue{:target="_blank"} |
readMark.readChat() |
The method is aimed for marking messages in a chat as read. Either all messages or a specified message in a chat can be marked as read | ReadChat{:target="_blank"} |
receiving.receiveNotification() |
The method is aimed for receiving one incoming notification from the notifications queue | ReceiveNotification{:target="_blank"} |
receiving.deleteNotification() |
The method is aimed for deleting an incoming notification from the notification queue | DeleteNotification{:target="_blank"} |
receiving.downloadFile() |
The method is aimed for downloading incoming and outgoing files | DownloadFile{:target="_blank"} |
sending.sendMessage() |
The method is aimed for sending a text message to a personal or a group chat | SendMessage{:target="_blank"} |
sending.sendButtons() |
The method is aimed for sending a button message to a personal or a group chat | SendButtons{:target="_blank"} |
sending.sendTemplateButtons() |
The method is aimed for sending a message with template list interacrive buttons to a personal or a group chat | SendTemplateButtons{:target="_blank"} |
sending.sendPoll() |
The method is aimed for sending a poll a personal or a group chat | SendPoll{:target="_blank"} |
sending.sendListMessage() |
The method is aimed for sending a message with a select button from a list of values to a personal or a group chat | SendListMessage{:target="_blank"} |
sending.sendFileByUpload() |
The method is aimed for sending a file uploaded by form (form-data) | SendFileByUpload{:target="_blank"} |
sending.sendFileByUrl() |
The method is aimed for sending a file uploaded by Url | SendFileByUrl{:target="_blank"} |
sending.uploadFile() |
The method is designed to upload a file to the cloud storage, which can be sent using the sendFileByUrl method | UploadFile{:target="_blank"} |
sending.sendLocation() |
The method is aimed for sending a location message | SendLocation{:target="_blank"} |
sending.sendContact() |
The method is aimed for sending a contact message | SendContact{:target="_blank"} |
sending.sendLink() |
The method is aimed for sending a message with a link, by which an image preview, title and description will be added | SendLink{:target="_blank"} |
sending.forwardMessages() |
The method is intended for forwarding messages to a personal or group chat | ForwardMessages{:target="_blank"} |
service.checkWhatsapp() |
The method checks WhatsApp account availability on a phone number | CheckWhatsapp{:target="_blank"} |
service.getAvatar() |
The method returns a user or a group chat avatar | GetAvatar{:target="_blank"} |
service.getContacts() |
The method is aimed for getting a list of the current account contacts | GetContacts{:target="_blank"} |
service.getContactInfo() |
The method is aimed for getting information on a contact | GetContactInfo{:target="_blank"} |
service.deleteMessage() |
The method deletes a message from a chat | DeleteMessage{:target="_blank"} |
service.archiveChat() |
The method archives a chat. One can archive chats that have at least one incoming message | ArchiveChat{:target="_blank"} |
service.unarchiveChat() |
The method unarchives a chat | UnarchiveChat{:target="_blank"} |
service.setDisappearingChat() |
The method is aimed for changing settings of disappearing messages in chats | SetDisappearingChat{:target="_blank"} |
webhook.start() |
The method is aimed for starting to receive webhooks | |
webhook.stop() |
The method is aimed for stopping to receive webhooks |
Licensed under Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) terms. Please see file LICENSE.