GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
feat: add disappearing messages management for chats via new API endpoint and UI component
Aldino Kemal871442fdd23b
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 444d5a0b..09a015b6 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -1,7 +1,7 @@openapi: "3.0.0"info:title: WhatsApp API MultiDevice- version: 6.12.0+ version: 6.13.0description: This API is used for sending whatsapp via APIservers:- url: http://localhost:3000@@ -1632,6 +1632,53 @@ paths:schema:$ref: '#/components/schemas/ErrorInternalServer'+ /chat/{chat_jid}/disappearing:+ post:+ operationId: setDisappearingTimer+ tags:+ - chat+ summary: Set disappearing messages timer+ description: Set or disable disappearing messages for a chat. Valid timer values are 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d).+ parameters:+ - in: path+ name: chat_jid+ schema:+ type: string+ required: true+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group)+ example: '[email protected]'+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ timer_seconds:+ type: integer+ example: 86400+ description: 'Timer in seconds: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)'+ required:+ - timer_seconds+ responses:+ '200':+ description: OK+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/SetDisappearingTimerResponse'+ '400':+ description: Bad Request+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorBadRequest'+ '500':+ description: Internal Server Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorInternalServer'+/group/info:get:operationId: groupInfo@@ -3435,6 +3482,33 @@ components:pinned:type: booleanexample: true+ SetDisappearingTimerResponse:+ type: object+ properties:+ status:+ type: integer+ example: 200+ code:+ type: string+ example: SUCCESS+ message:+ type: string+ example: Disappearing messages set to 86400 seconds+ results:+ type: object+ properties:+ status:+ type: string+ example: success+ message:+ type: string+ example: Disappearing messages set to 86400 seconds+ chat_jid:+ type: string+ example: '[email protected]'+ timer_seconds:+ type: integer+ example: 86400GroupInfoResponse:type: objectproperties:diff --git a/readme.md b/readme.mdindex 0a451396..ccb6e871 100644--- a/readme.md+++ b/readme.md@@ -481,6 +481,7 @@ You can fork or edit this source code !| ✅ | Get Chat Messages | GET | /chat/:chat_jid/messages || ✅ | Label Chat | POST | /chat/:chat_jid/label || ✅ | Pin Chat | POST | /chat/:chat_jid/pin |+| ✅ | Set Disappearing Messages | POST | /chat/:chat_jid/disappearing |```txt✅ = Availablediff --git a/src/config/settings.go b/src/config/settings.goindex d323d414..fbc726f8 100644--- a/src/config/settings.go+++ b/src/config/settings.go@@ -5,7 +5,7 @@ import ()var (- AppVersion = "v7.10.1"+ AppVersion = "v7.11.0"AppPort = "3000"AppDebug = falseAppOs = "AldinoKemal"diff --git a/src/domains/chat/chat.go b/src/domains/chat/chat.goindex 669ae3ea..07fef28b 100644--- a/src/domains/chat/chat.go+++ b/src/domains/chat/chat.go@@ -73,3 +73,16 @@ type PaginationResponse struct {Offset int `json:"offset"`Total int `json:"total"`}++// Disappearing Messages operations+type SetDisappearingTimerRequest struct {+ ChatJID string `json:"chat_jid" uri:"chat_jid"`+ TimerSeconds uint32 `json:"timer_seconds"`+}++type SetDisappearingTimerResponse struct {+ Status string `json:"status"`+ Message string `json:"message"`+ ChatJID string `json:"chat_jid"`+ TimerSeconds uint32 `json:"timer_seconds"`+}diff --git a/src/domains/chat/interfaces.go b/src/domains/chat/interfaces.goindex 83679393..baf3b2ae 100644--- a/src/domains/chat/interfaces.go+++ b/src/domains/chat/interfaces.go@@ -9,4 +9,5 @@ type IChatUsecase interface {ListChats(ctx context.Context, request ListChatsRequest) (response ListChatsResponse, err error)GetChatMessages(ctx context.Context, request GetChatMessagesRequest) (response GetChatMessagesResponse, err error)PinChat(ctx context.Context, request PinChatRequest) (response PinChatResponse, err error)+ SetDisappearingTimer(ctx context.Context, request SetDisappearingTimerRequest) (response SetDisappearingTimerResponse, err error)}diff --git a/src/ui/rest/chat.go b/src/ui/rest/chat.goindex b2d2d0e2..dbafdb36 100644--- a/src/ui/rest/chat.go+++ b/src/ui/rest/chat.go@@ -17,6 +17,7 @@ func InitRestChat(app fiber.Router, service domainChat.IChatUsecase) Chat {app.Get("/chats", rest.ListChats)app.Get("/chat/:chat_jid/messages", rest.GetChatMessages)app.Post("/chat/:chat_jid/pin", rest.PinChat)+ app.Post("/chat/:chat_jid/disappearing", rest.SetDisappearingTimer)return rest}@@ -104,3 +105,30 @@ func (controller *Chat) PinChat(c *fiber.Ctx) error {Results: response,})}++func (controller *Chat) SetDisappearingTimer(c *fiber.Ctx) error {+ var request domainChat.SetDisappearingTimerRequest++ // Parse path parameter+ request.ChatJID = c.Params("chat_jid")++ // Parse JSON body+ if err := c.BodyParser(&request); err != nil {+ return c.Status(400).JSON(utils.ResponseData{+ Status: 400,+ Code: "BAD_REQUEST",+ Message: "Invalid request body",+ Results: nil,+ })+ }++ response, err := controller.Service.SetDisappearingTimer(c.UserContext(), request)+ utils.PanicIfNeeded(err)++ return c.JSON(utils.ResponseData{+ Status: 200,+ Code: "SUCCESS",+ Message: response.Message,+ Results: response,+ })+}diff --git a/src/usecase/chat.go b/src/usecase/chat.goindex abbf92f7..b4ff7c85 100644--- a/src/usecase/chat.go+++ b/src/usecase/chat.go@@ -244,3 +244,48 @@ func (service serviceChat) PinChat(ctx context.Context, request domainChat.PinChreturn response, nil}++func (service serviceChat) SetDisappearingTimer(ctx context.Context, request domainChat.SetDisappearingTimerRequest) (response domainChat.SetDisappearingTimerResponse, err error) {+ if err = validations.ValidateSetDisappearingTimer(ctx, &request); err != nil {+ return response, err+ }++ // Validate JID and ensure connection+ targetJID, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.ChatJID)+ if err != nil {+ return response, err+ }++ // Set disappearing timer using whatsmeow+ if err = whatsapp.GetClient().SetDisappearingTimer(ctx, targetJID, time.Duration(request.TimerSeconds)*time.Second, time.Now()); err != nil {+ logrus.WithError(err).WithFields(logrus.Fields{+ "chat_jid": request.ChatJID,+ "timer_seconds": request.TimerSeconds,+ }).Error("Failed to set disappearing timer")+ return response, err+ }++ // Update local storage immediately for consistency+ if existingChat, _ := service.chatStorageRepo.GetChat(request.ChatJID); existingChat != nil {+ existingChat.EphemeralExpiration = request.TimerSeconds+ _ = service.chatStorageRepo.StoreChat(existingChat)+ }++ // Build response+ response.Status = "success"+ response.ChatJID = request.ChatJID+ response.TimerSeconds = request.TimerSeconds++ if request.TimerSeconds == 0 {+ response.Message = "Disappearing messages disabled"+ } else {+ response.Message = fmt.Sprintf("Disappearing messages set to %d seconds", request.TimerSeconds)+ }++ logrus.WithFields(logrus.Fields{+ "chat_jid": request.ChatJID,+ "timer_seconds": request.TimerSeconds,+ }).Info("Disappearing timer set successfully")++ return response, nil+}diff --git a/src/validations/chat_validation.go b/src/validations/chat_validation.goindex 9953fee4..f39e04eb 100644--- a/src/validations/chat_validation.go+++ b/src/validations/chat_validation.go@@ -56,3 +56,37 @@ func ValidatePinChat(ctx context.Context, request *domainChat.PinChatRequest) erreturn nil}++// ValidTimerValues contains WhatsApp's allowed disappearing message durations in seconds+var ValidTimerValues = []uint32{+ 0, // Disabled+ 86400, // 24 hours+ 604800, // 7 days+ 7776000, // 90 days+}++func ValidateSetDisappearingTimer(ctx context.Context, request *domainChat.SetDisappearingTimerRequest) error {+ err := validation.ValidateStructWithContext(ctx, request,+ validation.Field(&request.ChatJID, validation.Required),+ validation.Field(&request.TimerSeconds, validation.By(validateTimerValue)),+ )++ if err != nil {+ return pkgError.ValidationError(err.Error())+ }++ return nil+}++func validateTimerValue(value interface{}) error {+ timer, ok := value.(uint32)+ if !ok {+ return pkgError.ValidationError("timer_seconds must be a valid number")+ }+ for _, valid := range ValidTimerValues {+ if timer == valid {+ return nil+ }+ }+ return pkgError.ValidationError("timer_seconds must be one of: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)")+}diff --git a/src/validations/chat_validation_test.go b/src/validations/chat_validation_test.goindex 643db6ec..57b66030 100644--- a/src/validations/chat_validation_test.go+++ b/src/validations/chat_validation_test.go@@ -183,3 +183,70 @@ func TestValidatePinChat(t *testing.T) {})}}++func TestValidateSetDisappearingTimer(t *testing.T) {+ type args struct {+ request domainChat.SetDisappearingTimerRequest+ }+ tests := []struct {+ name string+ args args+ err any+ }{+ {+ name: "should success with timer disabled (0)",+ args: args{request: domainChat.SetDisappearingTimerRequest{+ ChatJID: "[email protected]",+ TimerSeconds: 0,+ }},+ err: nil,+ },+ {+ name: "should success with 24 hours timer",+ args: args{request: domainChat.SetDisappearingTimerRequest{+ ChatJID: "[email protected]",+ TimerSeconds: 86400,+ }},+ err: nil,+ },+ {+ name: "should success with 7 days timer",+ args: args{request: domainChat.SetDisappearingTimerRequest{+ ChatJID: "[email protected]",+ TimerSeconds: 604800,+ }},+ err: nil,+ },+ {+ name: "should success with 90 days timer",+ args: args{request: domainChat.SetDisappearingTimerRequest{+ ChatJID: "[email protected]",+ TimerSeconds: 7776000,+ }},+ err: nil,+ },+ {+ name: "should error with empty chat_jid",+ args: args{request: domainChat.SetDisappearingTimerRequest{+ ChatJID: "",+ TimerSeconds: 86400,+ }},+ err: pkgError.ValidationError("chat_jid: cannot be blank."),+ },+ {+ name: "should error with invalid timer value",+ args: args{request: domainChat.SetDisappearingTimerRequest{+ ChatJID: "[email protected]",+ TimerSeconds: 12345,+ }},+ err: pkgError.ValidationError("timer_seconds: timer_seconds must be one of: 0 (off), 86400 (24h), 604800 (7d), 7776000 (90d)."),+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := ValidateSetDisappearingTimer(context.Background(), &tt.args.request)+ assert.Equal(t, tt.err, err)+ })+ }+}diff --git a/src/validations/send_validation.go b/src/validations/send_validation.goindex 59d44aeb..2db6fc1c 100644--- a/src/validations/send_validation.go+++ b/src/validations/send_validation.go@@ -13,20 +13,28 @@ import ("github.com/go-ozzo/ozzo-validation/v4/is")-// maxDuration represents the maximum allowed duration in seconds (uint32 max).-const maxDuration int64 = 4294967295+// ValidDurationValues contains WhatsApp's allowed disappearing message durations in seconds.+// 0 = no expiry/disabled, 86400 = 24 hours, 604800 = 7 days, 7776000 = 90 days.+var ValidDurationValues = []int{+ 0, // No expiry / disabled+ 86400, // 24 hours+ 604800, // 7 days+ 7776000, // 90 days+}-// validateDuration validates that the duration pointer is nil or within acceptable bounds.+// validateDuration validates that the duration pointer is nil or one of WhatsApp's standard values.func validateDuration(dur *int) error {if dur == nil {return nil}- if *dur < 0 || int64(*dur) > int64(maxDuration) {- return pkgError.ValidationError(- fmt.Sprintf("duration must be between 0 and %d seconds (0 means no expiry)", maxDuration),- )+ for _, valid := range ValidDurationValues {+ if *dur == valid {+ return nil+ }}- return nil+ return pkgError.ValidationError(+ "duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)",+ )}// validatePhoneNumber validates that the phone number is in international format (not starting with 0)diff --git a/src/validations/send_validation_test.go b/src/validations/send_validation_test.goindex 03d0e522..f537fac0 100644--- a/src/validations/send_validation_test.go+++ b/src/validations/send_validation_test.go@@ -892,24 +892,29 @@ func TestValidateDuration(t *testing.T) {err: nil,},{- name: "should success with valid duration",- duration: func() *int { d := 3600; return &d }(),+ name: "should success with 24h duration",+ duration: func() *int { d := 86400; return &d }(),err: nil,},{- name: "should success with max duration",- duration: func() *int { d := int(maxDuration); return &d }(),+ name: "should success with 7d duration",+ duration: func() *int { d := 604800; return &d }(),err: nil,},{- name: "should error with negative duration",- duration: func() *int { d := -1; return &d }(),- err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),+ name: "should success with 90d duration",+ duration: func() *int { d := 7776000; return &d }(),+ err: nil,},{- name: "should error with duration too high",- duration: func() *int { d := int(maxDuration) + 1; return &d }(),- err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),+ name: "should error with invalid duration",+ duration: func() *int { d := 12345; return &d }(),+ err: pkgError.ValidationError("duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)"),+ },+ {+ name: "should error with negative duration",+ duration: func() *int { d := -1; return &d }(),+ err: pkgError.ValidationError("duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)"),},}@@ -935,7 +940,7 @@ func TestValidateSendMessage_WithDuration(t *testing.T) {args: args{request: domainSend.MessageRequest{BaseRequest: domainSend.BaseRequest{Phone: "[email protected]",- Duration: func() *int { d := 3600; return &d }(),+ Duration: func() *int { d := 86400; return &d }(),},Message: "Hello this is testing",}},@@ -946,11 +951,11 @@ func TestValidateSendMessage_WithDuration(t *testing.T) {args: args{request: domainSend.MessageRequest{BaseRequest: domainSend.BaseRequest{Phone: "[email protected]",- Duration: func() *int { d := -1; return &d }(),+ Duration: func() *int { d := 12345; return &d }(),},Message: "Hello this is testing",}},- err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),+ err: pkgError.ValidationError("duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)"),},}@@ -1023,7 +1028,7 @@ func TestValidateSendFile_WithDuration(t *testing.T) {args: args{request: domainSend.FileRequest{BaseRequest: domainSend.BaseRequest{Phone: "[email protected]",- Duration: func() *int { d := 3600; return &d }(),+ Duration: func() *int { d := 604800; return &d }(),},File: file,}},@@ -1034,11 +1039,11 @@ func TestValidateSendFile_WithDuration(t *testing.T) {args: args{request: domainSend.FileRequest{BaseRequest: domainSend.BaseRequest{Phone: "[email protected]",- Duration: func() *int { d := -1; return &d }(),+ Duration: func() *int { d := 12345; return &d }(),},File: file,}},- err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),+ err: pkgError.ValidationError("duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)"),},}@@ -1070,7 +1075,7 @@ func TestValidateSendAudio_WithDuration(t *testing.T) {args: args{request: domainSend.AudioRequest{BaseRequest: domainSend.BaseRequest{Phone: "[email protected]",- Duration: func() *int { d := 3600; return &d }(),+ Duration: func() *int { d := 7776000; return &d }(),},Audio: audio,}},@@ -1091,11 +1096,11 @@ func TestValidateSendAudio_WithDuration(t *testing.T) {args: args{request: domainSend.AudioRequest{BaseRequest: domainSend.BaseRequest{Phone: "[email protected]",- Duration: func() *int { d := -1; return &d }(),+ Duration: func() *int { d := 12345; return &d }(),},Audio: audio,}},- err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),+ err: pkgError.ValidationError("duration must be one of: 0 (no expiry), 86400 (24h), 604800 (7d), 7776000 (90d)"),},}diff --git a/src/views/components/ChatDisappearingManager.js b/src/views/components/ChatDisappearingManager.jsnew file mode 100644index 00000000..b5465162--- /dev/null+++ b/src/views/components/ChatDisappearingManager.js@@ -0,0 +1,127 @@+import FormRecipient from "./generic/FormRecipient.js";++export default {+ name: 'ChatDisappearingManager',+ components: {+ FormRecipient+ },+ data() {+ return {+ type: window.TYPEUSER,+ phone: '',+ timerSeconds: 86400, // Default to 24 hours+ loading: false,+ }+ },+ computed: {+ phone_id() {+ return this.phone + this.type;+ },+ timerLabel() {+ const labels = {+ 0: 'Off',+ 86400: '24 hours',+ 604800: '7 days',+ 7776000: '90 days'+ };+ return labels[this.timerSeconds] || 'Unknown';+ }+ },+ methods: {+ isValidForm() {+ const isPhoneValid = this.phone.trim().length > 0;+ return isPhoneValid;+ },+ openModal() {+ $('#modalChatDisappearing').modal({+ onApprove: function () {+ return false;+ }+ }).modal('show');+ },+ async handleSubmit() {+ if (!this.isValidForm() || this.loading) {+ return;+ }+ try {+ const response = await this.submitApi();+ showSuccessInfo(response);+ $('#modalChatDisappearing').modal('hide');+ } catch (err) {+ showErrorInfo(err);+ }+ },+ async submitApi() {+ this.loading = true;+ try {+ const payload = {+ timer_seconds: parseInt(this.timerSeconds)+ };++ const response = await window.http.post(`/chat/${this.phone_id}/disappearing`, payload);+ this.handleReset();+ return response.data.message;+ } catch (error) {+ if (error.response?.data?.message) {+ throw new Error(error.response.data.message);+ }+ throw error;+ } finally {+ this.loading = false;+ }+ },+ handleReset() {+ this.phone = '';+ this.timerSeconds = 86400;+ },+ },+ template: `+ <div class="purple card" @click="openModal()" style="cursor: pointer">+ <div class="content">+ <a class="ui purple right ribbon label">Chat</a>+ <div class="header">Disappearing Messages</div>+ <div class="description">+ Set auto-delete timer for chat messages+ </div>+ </div>+ </div>++ <!-- Modal ChatDisappearing -->+ <div class="ui small modal" id="modalChatDisappearing">+ <i class="close icon"></i>+ <div class="header">+ <i class="clock outline icon"></i> Disappearing Messages+ </div>+ <div class="content">+ <form class="ui form">+ <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="false"/>+ <div class="field">+ <label>Timer Duration</label>+ <select class="ui dropdown" v-model="timerSeconds">+ <option :value="0">Off (disabled)</option>+ <option :value="86400">24 hours</option>+ <option :value="604800">7 days</option>+ <option :value="7776000">90 days</option>+ </select>+ </div>+ <div class="ui info message" v-if="timerSeconds > 0">+ <i class="info circle icon"></i>+ Messages will disappear after <strong>{{ timerLabel }}</strong>+ </div>+ <div class="ui warning message" v-else>+ <i class="exclamation triangle icon"></i>+ Disappearing messages will be <strong>disabled</strong>+ </div>+ </form>+ </div>+ <div class="actions">+ <button class="ui approve positive right labeled icon button"+ :class="{'disabled': !isValidForm() || loading, 'loading': loading}"+ @click.prevent="handleSubmit">+ {{ timerSeconds === 0 ? 'Disable Timer' : 'Set Timer' }}+ <i class="clock icon"></i>+ </button>+ </div>+ </div>+ `+}diff --git a/src/views/index.html b/src/views/index.htmlindex 5fa38148..45ef9fb5 100644--- a/src/views/index.html+++ b/src/views/index.html@@ -146,6 +146,7 @@<div class="ui three column doubling grid cards"><chat-pin-manager></chat-pin-manager>+ <chat-disappearing-manager></chat-disappearing-manager><chat-list></chat-list><chat-messages></chat-messages></div>@@ -227,6 +228,7 @@import AccountUserCheck from "{{ .AppBasePath }}/components/AccountUserCheck.js";import AccountBusinessProfile from "{{ .AppBasePath }}/components/AccountBusinessProfile.js";import ChatPinManager from "{{ .AppBasePath }}/components/ChatPinManager.js";+ import ChatDisappearingManager from "{{ .AppBasePath }}/components/ChatDisappearingManager.js";import ChatList from "{{ .AppBasePath }}/components/ChatList.js";import ChatMessages from "{{ .AppBasePath }}/components/ChatMessages.js";@@ -264,7 +266,7 @@GroupList, GroupCreate, GroupJoinWithLink, GroupInfoFromLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic, GroupGetInviteLink, GroupInfo,NewsletterList,AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck, AccountBusinessProfile,- ChatPinManager, ChatList, ChatMessages+ ChatPinManager, ChatDisappearingManager, ChatList, ChatMessages},delimiters: ['[[', ']]'],data() {