Skip to content

Repository files navigation

whatsapp-api-client-java

Ссылка русскоязычную инструкцию

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.

API

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.

Authorization

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.

Installation

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'

Examples

How to initialize an object

You can configure your bean, use application.yml, or instantiate class via the constructor.

Via configuration:

@ConfigurationpublicclassGreenApiConf {
@BeanpublicRestTemplaterestTemplate() {
returnnewRestTemplateBuilder().build();
}
@BeanpublicGreenApigreenApi(RestTemplaterestTemplate) {
returnnewGreenApi(
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.comhostMedia: https://media.green-api.cominstanceId: {{yourInstance}}token: {{yourToken}}

Make sure you have a RestTemplate bean with your configuration, like this:

@BeanpublicRestTemplaterestTemplate(RestTemplateBuilderrestTemplateBuilder){
returnrestTemplateBuilder.build();
}

And add com.greenapi.client to the base scanning packages using the @ComponentScan annotation:

@SpringBootApplication@ComponentScan(basePackages = {"com.greenapi.client", "com.example"})
publicclassApplication {
publicstaticvoidmain(String[] args) {
varcontext = SpringApplication.run(Application.class, args);
}
}

Via constructor:

varrestTemplate = newRestTemplateBuilder().build();
vargreenApi1 = newGreenApi(
restTemplate,
"https://media.green-api.com",
"https://api.green-api.com",
{{instanceId1}},
{{instanceToken1}});
vargreenApi2 = newGreenApi(
restTemplate,
"https://media.greenapi.com",
"https://api.greenapi.com",
{{instanceId2}},
{{instanceToken2}});

How to send message

Link to example: sendMessageExample.java.

@Log4j2publicclassSendMessageExample {
privatevoidsendMessageExample(GreenApigreenApi) {
varmessage = 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());
}
}
}

How to create a group and send message

Link to example: CreateGroupSendMessageExample.java.

@Log4j2classCreateGroupSendMessageExample {
privatevoidcreateGroupAndSendMessage(GreenApigreenApi) {
vargroupMembers = newArrayList<String>();
groupMembers.add("11001234567@c.us");
groupMembers.add("11001234566@c.us");
groupMembers.add("11001234565@c.us");
vargroup = greenApi.groups.createGroup(
CreateGroupReq.builder()
.groupName("Test Group")
.chatIds(groupMembers)
.build()).getBody();
if (group != null) {
varmessage = 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());
}
}
}
}

How to send a file by uploading from the disk

To send a file, you need to give the path to the file.

Link to example: SendFileByUploadExample.java.

@Log4j2publicclassSendFileByUploadExample {
privatevoidsendFileByUploadExample(GreenApigreenApi) {
varfile = newFile("User/username/folder/Go-Logo_Blue.svg");
varresponse = 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());
}
}

How to send a file by URL

Link to example: SendFileByUrlExample.java.

@Log4j2publicclassSendFileByUrlExample {
privatevoidsendFileByUrlExample(GreenApigreenApi) {
varresponse = 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());
}
}

How to send a file by UploadFile + SendFileByUrl

Link to example: UploadFileAndSendByUrlExample.java.

@Log4j2publicclassUploadFileAndSendByUrlExample {
privatevoiduploadExample(GreenApigreenApi) throwsIOException {
varfile = newFile("User/username/folder/Go-Logo_Blue.svg");
varresponse = greenApi.sending.uploadFile(file);
if (response.getStatusCode().isError()) {
log.error("upload file failed");
}
varresponseEntity = greenApi.sending.sendFileByUrl(
OutgoingFileByUrl.builder()
.urlFile(Objects.requireNonNull(response.getBody()).getUrlFile())
.build());
log.info("file sent, message id: " + Objects.requireNonNull(responseEntity.getBody()).getIdMessage());
}
}

How to send a Poll

Link to example: SendPollExample.java.

@Log4j2publicclassSendPollExample {
privatevoidsendPollExample(GreenApigreenApi) {
varoptions = newArrayList<Option>();
options.add(newOption("option 1"));
options.add(newOption("option 2"));
options.add(newOption("option 3"));
vardto = OutgoingPoll.builder()
.chatId("111111111111@c.us")
.message("text message")
.options(options)
.multipleAnswers(false)
.build();
varresponse = greenApi.sending.sendPoll(dto);
log.info(response);
}
}

How to receive incoming notifications

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.

publicinterfaceWebhookHandler {
voidhandle(Notificationnotification);
}

Link to example: WebhookExample.java.

@SpringBootApplicationpublicclassWebhookExample {
publicstaticvoidmain(String[] args) {
varcontext = SpringApplication.run(WebhookExample.class, args);
varwebhookConsumer = (WebhookConsumer) context.getBean("webhookConsumer");
webhookConsumer.start(notification -> System.out.println("New webhook received: " + notification));
}
}

How to work with contacts

Link to example: ContactsMethodsExample.java.

@Log4j2classContactsMethodsExample {
privatevoidaddContact(GreenApigreenApi) {
varaddContactReq = AddContactReq.builder()
.chatId("11001234567@c.us")
.firstName("John")
.lastName("Doe")
.build();
varaddContactResp = greenApi.contacts.addContact(addContactReq).getBody();
}
privatevoideditContact(GreenApigreenApi) {
vareditContactReq = EditContactReq.builder()
.chatId("11001234567@c.us")
.firstName("Jane")
.lastName("Smith")
.build();
vareditContactResp = greenApi.contacts.editContact(editContactReq).getBody();
}
privatevoiddeleteContact(GreenApigreenApi) {
vardeleteContactReq = DeleteContactReq.builder()
.chatId("11001234567@c.us")
.build();
vardeleteContactResp = greenApi.contacts.deleteContact(deleteContactReq).getBody();
}
}

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 objectWebhook's json object
TextMessageWebhookTextMessage
TemplateMessageWebhookTemplateMessage
StickerMessageWebhookStickerMessage
ReactionMessageWebhookReactionMessage
QuotedMessageWebhookQuotedMessage
PollUpdateMessageWebhookPollUpdateMessage
PollMessageWebhookPollMessage
LocationMessageWebhookLocationMessage
ListMessageWebhookListMessage
GroupInviteMessageWebhookGroupInviteMessage
FileMessageWebhookimageMessage, videoMessage, documentMessage, audioMessage
ExtendedTextMessageWebhookExtendedTextMessage
ButtonsMessageWebhookButtonsMessage
ContactMessageWebhookContactMessage
ContactsArrayMessageWebhookContactMessage
TemplateButtonsReplyMessageWebhookTemplateButtonsReplyMessage
ButtonsResponseMessageWebhookButtonsResponseMessage
ListResponseMessageWebhookListResponseMessage

List of examples

DescriptionLink to example
How to send messageSendMessageExample.java
How to create a group and send messageCreateGroupSendMessageExample.java
How to send a file by uploading from the diskSendFileByUploadExample.java
How to send a file by URLSendFileByUrlExample.java
How to send a file by UploadFile + SendByUrlUploadFileAndSendByUrlExample.java
How to receive incoming notificationsWebhookExample.java
How to work with contactsContactsMethodsExample.java
How to forward messagesForwardMessagesExample.java
How to send interactive buttonsSendInteractiveButtonsExample.java
How to send a typing/recording indicatorSendTypingExample.java
How to get the list of chatsGetChatsExample.java
How to get incoming and outgoing callsCallsJournalExample.java
How to update group settingsUpdateGroupSettingsExample.java
How to use getStateInstanceHistory and updateApiTokenAccountMethodsExample.java
How to delete a statusDeleteStatusExample.java
How to send a message with typing time and custom previewSendMessageWithPreviewExample.java
How to send a file with typing indicatorSendFileWithTypingExample.java

List of all library methods

MethodDescriptionDocumentation
account.getSettings()The method is aimed for getting the current settings of the account settingsGetSettings
account.setSettings()The method is aimed for setting an account settings settingsSetSettings
account.getStateInstance()The method is aimed for getting the account stateGetStateInstance
account.getStatusInstance()The method is aimed for getting the status of the account instance socket connection with WhatsAppGetStatusInstance
account.reboot()The method is aimed for rebooting an accountReboot
account.logout()The method is aimed for logging out an accountLogout
account.qr()The method is aimed for getting QR codeQR
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
account.setProfilePicture()The method is aimed for setting an account pictureSetProfilePicture
account.getStateInstanceHistory()The method returns the history of instance state changesGetStateInstanceHistory
account.updateApiToken()The method generates a new API token for the instanceUpdateApiToken
contacts.addContact()The method is aimed for adding a number to contactsAddContact
contacts.editContact()The method is used to edit a number in contactsEditContact
contacts.deleteContact()The method is used to remove a number from contactsDeleteContact
device.getDeviceInfo()The method is aimed for getting information about the device (phone) running WhatsApp Business applicationGetDeviceInfo
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
groups.updateGroupName()The method changes a group chat nameUpdateGroupName
groups.getGroupData()The method gets group chat dataGetGroupData
groups.addGroupParticipant()The method adds a participant to a group chatAddGroupParticipant
groups.removeGroupParticipant()The method removes a participant from a group chatRemoveGroupParticipant
groups.setGroupAdmin()The method sets a group chat participant as an administratorSetGroupAdmin
groups.removeAdmin()The method removes a participant from group chat administartion rightsRemoveAdmin
groups.setGroupPicture()The method sets a group pictureSetGroupPicture
groups.leaveGroup()The method makes the current account user leave the group chatLeaveGroup
groups.updateGroupSettings()The method updates the group's permission settings (who can send messages, edit group info)UpdateGroupSettings
journals.getChatHistory()The method returns the chat message historyGetChatHistory
journals.getMessage()The method returns the chat messageGetMessage
journals.lastIncomingMessages()The method returns the last incoming messages of the account. In the default mode the incoming messages for 24 hours are returnedLastIncomingMessages
journals.lastOutgoingMessages()The method returns the last outgoing messages of the account. In the default mode the last messages for 24 hours are returnedLastOutgoingMessages
journals.lastIncomingCalls()The method returns the last incoming calls of the accountLastIncomingCalls
journals.lastOutgoingCalls()The method returns the last outgoing calls of the accountLastOutgoingCalls
queues.showMessagesQueue()The method is aimed for getting a list of messages in the queue to be sentShowMessagesQueue
queues.slearMessagesQueue()The method is aimed for clearing the queue of messages to be sentClearMessagesQueue
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 readReadChat
receiving.receiveNotification()The method is aimed for receiving one incoming notification from the notifications queueReceiveNotification
receiving.deleteNotification()The method is aimed for deleting an incoming notification from the notification queueDeleteNotification
receiving.downloadFile()The method is aimed for downloading incoming and outgoing filesDownloadFile
sending.sendMessage()The method is aimed for sending a text message to a personal or a group chatSendMessage
sending.sendButtons()The method is aimed for sending a button message to a personal or a group chatSendButtons
sending.sendTemplateButtons()The method is aimed for sending a message with template list interacrive buttons to a personal or a group chatSendTemplateButtons
sending.sendPoll()The method is aimed for sending a poll a personal or a group chatSendPoll
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 chatSendListMessage
sending.sendFileByUpload()The method is aimed for sending a file uploaded by form (form-data)SendFileByUpload
sending.sendFileByUrl()The method is aimed for sending a file uploaded by UrlSendFileByUrl
sending.uploadFile()The method is designed to upload a file to the cloud storage, which can be sent using the sendFileByUrl methodUploadFile
sending.sendLocation()The method is aimed for sending a location messageSendLocation
sending.sendContact()The method is aimed for sending a contact messageSendContact
sending.sendLink()The method is aimed for sending a message with a link, by which an image preview, title and description will be addedSendLink
sending.forwardMessages()The method is intended for forwarding messages to a personal or group chatForwardMessages
sending.sendInteractiveButtons()The method sends a message with action buttons (url, call, copy code) to a chatSendInteractiveButtons
sending.sendInteractiveButtonsReply()The method sends a message with reply buttons to a chat. Beta featureSendInteractiveButtonsReply
service.checkWhatsapp()The method checks WhatsApp account availability on a phone numberCheckWhatsapp
service.getAvatar()The method returns a user or a group chat avatarGetAvatar
service.getContacts()The method is aimed for getting a list of the current account contactsGetContacts
service.getContactInfo()The method is aimed for getting information on a contactGetContactInfo
service.deleteMessage()The method deletes a message from a chatDeleteMessage
service.archiveChat()The method archives a chat. One can archive chats that have at least one incoming messageArchiveChat
service.unarchiveChat()The method unarchives a chatUnarchiveChat
service.setDisappearingChat()The method is aimed for changing settings of disappearing messages in chatsSetDisappearingChat
service.editMessage()The method is aimed for editing a text message in a chatEditMessage
service.sendTyping()The method shows a typing or recording indicator to the chat recipientSendTyping
service.getChats()The method returns the list of chats for the current accountGetChats
webhook.start()The method is aimed for starting to receive webhooks
webhook.stop()The method is aimed for stopping to receive webhooks
statuses.sendTextStatus()The method is used to send a text statusSendTextStatus
statuses.sendVoiceStatus()The method is used to send a voice statusSendVoiceStatus
statuses.sendMediaStatus()The method is used to send a pictures or video statusSendMediaStatus
statuses.getIncomingStatuses()The method is used to get the incoming status messages of the instanceGetIncomingStatuses
statuses.getOutgoingStatuses()The method is used to get the outgoing statuses of the accountGetOutgoingStatuses
statuses.getStatusStatistic()The method is used to get an array of recipients marked sent/delivered/read for a given statusGetStatusStatistic
statuses.deleteStatus()The method deletes a sent statusDeleteStatus

Service methods documentation

Service methods documentation

License

Licensed under Creative Commons Attribution-NoDerivatives 4.0 International (CC BY-ND 4.0) terms. Please see file LICENSE.

About

This library helps you easily create a Java application to send WhatsApp messages

Topics

Resources

Stars

16 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages