Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: support send sticker (#420)

Aldino Kemal1fd92cd15e5f
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index b68ad47c..444d5a0b 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,7 +1,7 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 6.11.0
+ version: 6.12.0
description: This API is used for sending whatsapp via API
servers:
- url: http://localhost:3000
@@ -634,6 +634,58 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /send/sticker:
+ post:
+ operationId: sendSticker
+ tags:
+ - send
+ summary: Send Sticker
+ description: Send sticker with automatic conversion to WebP format
+ requestBody:
+ content:
+ multipart/form-data:
+ schema:
+ type: object
+ properties:
+ phone:
+ type: string
+ example: '[email protected]'
+ description: Phone number with country code
+ sticker:
+ type: string
+ format: binary
+ description: Sticker image file (jpg/jpeg/png/webp/gif)
+ sticker_url:
+ type: string
+ example: https://example.com/sticker.png
+ description: URL of sticker image to send
+ duration:
+ type: integer
+ example: 3600
+ description: Disappearing message duration in seconds (optional)
+ is_forwarded:
+ type: boolean
+ example: false
+ description: Whether this is a forwarded sticker
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SendResponse'
+ '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'
/send/video:
post:
operationId: sendVideo
diff --git a/gallery/send-sticker.png b/gallery/send-sticker.png
new file mode 100644
index 00000000..e69de29b
diff --git a/readme.md b/readme.md
index cf4525ae..732e6e2d 100644
--- a/readme.md
+++ b/readme.md
@@ -49,6 +49,10 @@ Download:
- `@phoneNumber`
- example: `Hello @628974812XXXX, @628974812XXXX`
- Post Whatsapp Status
+- **Send Stickers** - Automatically converts images to WebP sticker format
+ - Supports JPG, JPEG, PNG, WebP, and GIF formats
+ - Automatic resizing to 512x512 pixels
+ - Preserves transparency for PNG images
- Compress image before send
- Compress video before send
- Change OS name become your app (it's the device name when connect via mobile)
@@ -215,6 +219,7 @@ The WhatsApp MCP server provides comprehensive tools for AI agents to interact w
- `whatsapp_send_link` - Send links with custom captions
- `whatsapp_send_location` - Send location coordinates (latitude/longitude)
- `whatsapp_send_image` - Send images with captions, compression, and view-once options
+- `whatsapp_send_sticker` - Send stickers with automatic WebP conversion (supports JPG/PNG/GIF)
##### **πŸ“‹ Chat & Contact Management**
@@ -416,6 +421,7 @@ You can fork or edit this source code !
| βœ… | Send Audio | POST | /send/audio |
| βœ… | Send File | POST | /send/file |
| βœ… | Send Video | POST | /send/video |
+| βœ… | Send Sticker | POST | /send/sticker |
| βœ… | Send Contact | POST | /send/contact |
| βœ… | Send Link | POST | /send/link |
| βœ… | Send Location | POST | /send/location |
@@ -482,6 +488,7 @@ You can fork or edit this source code !
| Send Image | ![Send Image](./gallery/send-image.png) |
| Send File | ![Send File](./gallery/send-file.png) |
| Send Video | ![Send Video](./gallery/send-video.png) |
+| Send Sticker | ![Send Sticker](./gallery/send-sticker.png) |
| Send Contact | ![Send Contact](./gallery/send-contact.png) |
| Send Location | ![Send Location](./gallery/send-location.png) |
| Send Audio | ![Send Audio](./gallery/send-audio.png) |
diff --git a/src/domains/send/interfaces.go b/src/domains/send/interfaces.go
index aa54072e..69c1d5d1 100644
--- a/src/domains/send/interfaces.go
+++ b/src/domains/send/interfaces.go
@@ -15,6 +15,7 @@ type IMediaSender interface {
SendFile(ctx context.Context, request FileRequest) (response GenericResponse, err error)
SendVideo(ctx context.Context, request VideoRequest) (response GenericResponse, err error)
SendAudio(ctx context.Context, request AudioRequest) (response GenericResponse, err error)
+ SendSticker(ctx context.Context, request StickerRequest) (response GenericResponse, err error)
}
// IInteractionSender handles interaction message sending operations
diff --git a/src/domains/send/sticker.go b/src/domains/send/sticker.go
new file mode 100644
index 00000000..376fbfe5
--- /dev/null
+++ b/src/domains/send/sticker.go
@@ -0,0 +1,9 @@
+package send
+
+import "mime/multipart"
+
+type StickerRequest struct {
+ BaseRequest
+ Sticker *multipart.FileHeader `json:"sticker" form:"sticker"`
+ StickerURL *string `json:"sticker_url" form:"sticker_url"`
+}
\ No newline at end of file
diff --git a/src/ui/mcp/send.go b/src/ui/mcp/send.go
index e7b6194d..f23c6b73 100644
--- a/src/ui/mcp/send.go
+++ b/src/ui/mcp/send.go
@@ -26,6 +26,7 @@ func (s *SendHandler) AddSendTools(mcpServer *server.MCPServer) {
mcpServer.AddTool(s.toolSendLink(), s.handleSendLink)
mcpServer.AddTool(s.toolSendLocation(), s.handleSendLocation)
mcpServer.AddTool(s.toolSendImage(), s.handleSendImage)
+ mcpServer.AddTool(s.toolSendSticker(), s.handleSendSticker)
}
func (s *SendHandler) toolSendText() mcp.Tool {
@@ -346,3 +347,53 @@ func (s *SendHandler) handleSendImage(ctx context.Context, request mcp.CallToolR
return mcp.NewToolResultText(fmt.Sprintf("Image sent successfully with ID %s", res.MessageID)), nil
}
+
+func (s *SendHandler) toolSendSticker() mcp.Tool {
+ sendStickerTool := mcp.NewTool("whatsapp_send_sticker",
+ mcp.WithDescription("Send a sticker to a WhatsApp contact or group. Images are automatically converted to WebP sticker format."),
+ mcp.WithString("phone",
+ mcp.Required(),
+ mcp.Description("Phone number or group ID to send sticker to"),
+ ),
+ mcp.WithString("sticker_url",
+ mcp.Description("URL of the image to convert to sticker and send"),
+ ),
+ mcp.WithBoolean("is_forwarded",
+ mcp.Description("Whether this is a forwarded sticker"),
+ ),
+ )
+
+ return sendStickerTool
+}
+
+func (s *SendHandler) handleSendSticker(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ phone, ok := request.GetArguments()["phone"].(string)
+ if !ok {
+ return nil, errors.New("phone must be a string")
+ }
+
+ stickerURL, stickerURLOk := request.GetArguments()["sticker_url"].(string)
+ if !stickerURLOk || stickerURL == "" {
+ return nil, errors.New("sticker_url must be a non-empty string")
+ }
+
+ isForwarded := false
+ if val, ok := request.GetArguments()["is_forwarded"].(bool); ok {
+ isForwarded = val
+ }
+
+ stickerRequest := domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{
+ Phone: phone,
+ IsForwarded: isForwarded,
+ },
+ StickerURL: &stickerURL,
+ }
+
+ res, err := s.sendService.SendSticker(ctx, stickerRequest)
+ if err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Sticker sent successfully with ID %s", res.MessageID)), nil
+}
diff --git a/src/ui/rest/send.go b/src/ui/rest/send.go
index 0a38b0e3..e388b889 100644
--- a/src/ui/rest/send.go
+++ b/src/ui/rest/send.go
@@ -16,6 +16,7 @@ func InitRestSend(app fiber.Router, service domainSend.ISendUsecase) Send {
app.Post("/send/image", rest.SendImage)
app.Post("/send/file", rest.SendFile)
app.Post("/send/video", rest.SendVideo)
+ app.Post("/send/sticker", rest.SendSticker)
app.Post("/send/contact", rest.SendContact)
app.Post("/send/link", rest.SendLink)
app.Post("/send/location", rest.SendLocation)
@@ -114,6 +115,29 @@ func (controller *Send) SendVideo(c *fiber.Ctx) error {
})
}
+func (controller *Send) SendSticker(c *fiber.Ctx) error {
+ var request domainSend.StickerRequest
+ err := c.BodyParser(&request)
+ utils.PanicIfNeeded(err)
+
+ // Try to get file but ignore error if not provided
+ if stickerFile, errFile := c.FormFile("sticker"); errFile == nil {
+ request.Sticker = stickerFile
+ }
+
+ utils.SanitizePhone(&request.Phone)
+
+ response, err := controller.Service.SendSticker(c.UserContext(), request)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: response.Status,
+ Results: response,
+ })
+}
+
func (controller *Send) SendContact(c *fiber.Ctx) error {
var request domainSend.ContactRequest
err := c.BodyParser(&request)
diff --git a/src/usecase/send.go b/src/usecase/send.go
index f120eb33..b7ad2dc5 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -8,6 +8,7 @@ import (
"net/http"
"os"
"os/exec"
+ "path/filepath"
"strings"
"time"
@@ -898,6 +899,189 @@ func (service serviceSend) getMentionFromText(_ context.Context, messages string
return result
}
+func (service serviceSend) SendSticker(ctx context.Context, request domainSend.StickerRequest) (response domainSend.GenericResponse, err error) {
+ // Validate request
+ err = validations.ValidateSendSticker(ctx, request)
+ if err != nil {
+ return response, err
+ }
+
+ dataWaRecipient, err := utils.ValidateJidWithLogin(whatsapp.GetClient(), request.Phone)
+ if err != nil {
+ return response, err
+ }
+
+ var (
+ stickerPath string
+ deletedItems []string
+ stickerBytes []byte
+ )
+
+ // Resolve absolute base directory for send items
+ absBaseDir, err := filepath.Abs(config.PathSendItems)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to resolve base directory: %v", err))
+ }
+
+ defer func() {
+ // Delete temporary files
+ for _, path := range deletedItems {
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ logrus.Warnf("Failed to cleanup temporary file %s: %v", path, err)
+ }
+ }
+ }()
+
+ // Handle sticker from URL or file
+ if request.StickerURL != nil && *request.StickerURL != "" {
+ // Download sticker from URL
+ imageData, _, err := utils.DownloadImageFromURL(*request.StickerURL)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to download sticker from URL: %v", err))
+ }
+
+ // Create safe temporary file within base dir
+ f, err := os.CreateTemp(absBaseDir, "sticker_*")
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to create temp file: %v", err))
+ }
+ stickerPath = f.Name()
+ if _, err := f.Write(imageData); err != nil {
+ f.Close()
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to write sticker: %v", err))
+ }
+ _ = f.Close()
+ deletedItems = append(deletedItems, stickerPath)
+ } else if request.Sticker != nil {
+ // Create safe temporary file within base dir
+ f, err := os.CreateTemp(absBaseDir, "sticker_*")
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to create temp file: %v", err))
+ }
+ stickerPath = f.Name()
+ _ = f.Close()
+
+ // Save uploaded file to safe path
+ err = fasthttp.SaveMultipartFile(request.Sticker, stickerPath)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to save sticker: %v", err))
+ }
+ deletedItems = append(deletedItems, stickerPath)
+ }
+
+ // Convert image to WebP format for sticker (512x512 max size)
+ srcImage, err := imaging.Open(stickerPath)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to open image for sticker conversion: %v", err))
+ }
+
+ // Resize image to max 512x512 maintaining aspect ratio
+ bounds := srcImage.Bounds()
+ width := bounds.Dx()
+ height := bounds.Dy()
+
+ if width > 512 || height > 512 {
+ if width > height {
+ srcImage = imaging.Resize(srcImage, 512, 0, imaging.Lanczos)
+ } else {
+ srcImage = imaging.Resize(srcImage, 0, 512, imaging.Lanczos)
+ }
+ }
+
+ // Convert to WebP using external command (ffmpeg or cwebp)
+ webpPath := filepath.Join(absBaseDir, fmt.Sprintf("sticker_%s.webp", fiberUtils.UUIDv4()))
+ deletedItems = append(deletedItems, webpPath)
+
+ // First save as PNG temporarily
+ pngPath := filepath.Join(absBaseDir, fmt.Sprintf("temp_%s.png", fiberUtils.UUIDv4()))
+ deletedItems = append(deletedItems, pngPath)
+
+ err = imaging.Save(srcImage, pngPath)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to save temporary PNG: %v", err))
+ }
+
+ // Try to use ffmpeg first (most common), then cwebp
+ var convertCmd *exec.Cmd
+
+ // Add execution timeout for conversion
+ convCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
+ defer cancel()
+
+ // Check if ffmpeg is available
+ if _, err := exec.LookPath("ffmpeg"); err == nil {
+ // Use ffmpeg to convert to WebP with transparency support, overwrite if exists
+ convertCmd = exec.CommandContext(convCtx, "ffmpeg", "-y", "-i", pngPath, "-vcodec", "libwebp", "-lossless", "0", "-compression_level", "6", "-q:v", "60", "-preset", "default", "-loop", "0", "-an", "-vsync", "0", webpPath)
+ } else if _, err := exec.LookPath("cwebp"); err == nil {
+ // Use cwebp as fallback
+ convertCmd = exec.CommandContext(convCtx, "cwebp", "-q", "60", "-o", webpPath, pngPath)
+ } else {
+ // If neither tool is available, return error
+ return response, pkgError.InternalServerError("neither ffmpeg nor cwebp is installed for WebP conversion")
+ }
+
+ var stderr bytes.Buffer
+ convertCmd.Stderr = &stderr
+
+ if err := convertCmd.Run(); err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to convert sticker to WebP: %v, stderr: %s", err, stderr.String()))
+ }
+
+ // Read the WebP file
+ stickerBytes, err = os.ReadFile(webpPath)
+ if err != nil {
+ return response, pkgError.InternalServerError(fmt.Sprintf("failed to read WebP sticker: %v", err))
+ }
+
+ // Upload sticker to WhatsApp servers
+ stickerUploaded, err := service.uploadMedia(ctx, whatsmeow.MediaImage, stickerBytes, dataWaRecipient)
+ if err != nil {
+ return response, pkgError.WaUploadMediaError(fmt.Sprintf("failed to upload sticker: %v", err))
+ }
+
+ // Create sticker message
+ msg := &waE2E.Message{
+ StickerMessage: &waE2E.StickerMessage{
+ URL: proto.String(stickerUploaded.URL),
+ DirectPath: proto.String(stickerUploaded.DirectPath),
+ Mimetype: proto.String("image/webp"),
+ FileLength: proto.Uint64(stickerUploaded.FileLength),
+ FileSHA256: stickerUploaded.FileSHA256,
+ FileEncSHA256: stickerUploaded.FileEncSHA256,
+ MediaKey: stickerUploaded.MediaKey,
+ Width: proto.Uint32(uint32(srcImage.Bounds().Dx())),
+ Height: proto.Uint32(uint32(srcImage.Bounds().Dy())),
+ IsAnimated: proto.Bool(false),
+ },
+ }
+
+ if request.BaseRequest.IsForwarded {
+ msg.StickerMessage.ContextInfo = &waE2E.ContextInfo{
+ IsForwarded: proto.Bool(true),
+ ForwardingScore: proto.Uint32(100),
+ }
+ }
+
+ if request.BaseRequest.Duration != nil && *request.BaseRequest.Duration > 0 {
+ if msg.StickerMessage.ContextInfo == nil {
+ msg.StickerMessage.ContextInfo = &waE2E.ContextInfo{}
+ }
+ msg.StickerMessage.ContextInfo.Expiration = proto.Uint32(uint32(*request.BaseRequest.Duration))
+ }
+
+ content := "🎨 Sticker"
+
+ // Send the sticker message
+ ts, err := service.wrapSendMessage(ctx, dataWaRecipient, msg, content)
+ if err != nil {
+ return response, err
+ }
+
+ response.MessageID = ts.ID
+ response.Status = fmt.Sprintf("Sticker sent to %s (server timestamp: %s)", request.Phone, ts.Timestamp.String())
+ return response, nil
+}
+
func (service serviceSend) uploadMedia(ctx context.Context, mediaType whatsmeow.MediaType, media []byte, recipient types.JID) (uploaded whatsmeow.UploadResponse, err error) {
if recipient.Server == types.NewsletterServer {
uploaded, err = whatsapp.GetClient().UploadNewsletter(ctx, media, mediaType)
diff --git a/src/validations/send_validation.go b/src/validations/send_validation.go
index eabac580..59d44aeb 100644
--- a/src/validations/send_validation.go
+++ b/src/validations/send_validation.go
@@ -120,6 +120,61 @@ func ValidateSendImage(ctx context.Context, request domainSend.ImageRequest) err
return nil
}
+func ValidateSendSticker(ctx context.Context, request domainSend.StickerRequest) error {
+ err := validation.ValidateStructWithContext(ctx, &request,
+ validation.Field(&request.Phone, validation.Required),
+ )
+
+ if err != nil {
+ return pkgError.ValidationError(err.Error())
+ }
+
+ // Custom validation for phone number format
+ if err := validatePhoneNumber(request.Phone); err != nil {
+ return err
+ }
+
+ // Either Sticker or StickerURL must be provided
+ if request.Sticker == nil && (request.StickerURL == nil || *request.StickerURL == "") {
+ return pkgError.ValidationError("either Sticker or StickerURL must be provided")
+ }
+
+ // Both cannot be provided at the same time
+ if request.Sticker != nil && request.StickerURL != nil && *request.StickerURL != "" {
+ return pkgError.ValidationError("cannot provide both Sticker file and StickerURL")
+ }
+
+ // Validate file type if sticker file is provided
+ if request.Sticker != nil {
+ availableMimes := map[string]bool{
+ "image/jpeg": true,
+ "image/jpg": true,
+ "image/png": true,
+ "image/webp": true, // Also accept WebP directly
+ "image/gif": true, // Support GIF for animated stickers
+ }
+
+ if !availableMimes[request.Sticker.Header.Get("Content-Type")] {
+ return pkgError.ValidationError("your sticker is not allowed. please use jpg/jpeg/png/webp/gif")
+ }
+ }
+
+ // Validate URL if provided
+ if request.StickerURL != nil && *request.StickerURL != "" {
+ err := validation.Validate(*request.StickerURL, is.URL)
+ if err != nil {
+ return pkgError.ValidationError("StickerURL must be a valid URL")
+ }
+ }
+
+ // Validate duration
+ if err := validateDuration(request.Duration); err != nil {
+ return err
+ }
+
+ return nil
+}
+
func ValidateSendFile(ctx context.Context, request domainSend.FileRequest) error {
err := validation.ValidateStructWithContext(ctx, &request,
validation.Field(&request.Phone, validation.Required),
diff --git a/src/validations/send_validation_test_sticker.go b/src/validations/send_validation_test_sticker.go
new file mode 100644
index 00000000..08192f1f
--- /dev/null
+++ b/src/validations/send_validation_test_sticker.go
@@ -0,0 +1,163 @@
+package validations
+
+import (
+ "context"
+ "mime/multipart"
+ "testing"
+
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestValidateSendSticker(t *testing.T) {
+ sticker := &multipart.FileHeader{
+ Filename: "sample-sticker.png",
+ Size: 100,
+ Header: map[string][]string{"Content-Type": {"image/png"}},
+ }
+
+ type args struct {
+ request domainSend.StickerRequest
+ }
+ tests := []struct {
+ name string
+ args args
+ err any
+ }{
+ {
+ name: "should success with sticker file",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ Sticker: sticker,
+ },
+ },
+ err: nil,
+ },
+ {
+ name: "should success with sticker URL",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ StickerURL: func() *string { s := "https://example.com/sticker.png"; return &s }(),
+ },
+ },
+ err: nil,
+ },
+ {
+ name: "should error without phone",
+ args: args{
+ request: domainSend.StickerRequest{
+ Sticker: sticker,
+ },
+ },
+ err: pkgError.ValidationError("Phone: cannot be blank."),
+ },
+ {
+ name: "should error without sticker and sticker_url",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ },
+ },
+ err: pkgError.ValidationError("either Sticker or StickerURL must be provided"),
+ },
+ {
+ name: "should error with both sticker and sticker_url",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ Sticker: sticker,
+ StickerURL: func() *string { s := "https://example.com/sticker.png"; return &s }(),
+ },
+ },
+ err: pkgError.ValidationError("cannot provide both Sticker file and StickerURL"),
+ },
+ {
+ name: "should error with invalid URL",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ StickerURL: func() *string { s := "not-a-valid-url"; return &s }(),
+ },
+ },
+ err: pkgError.ValidationError("StickerURL must be a valid URL"),
+ },
+ {
+ name: "should success with WebP sticker",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ Sticker: &multipart.FileHeader{
+ Filename: "sample-sticker.webp",
+ Size: 100,
+ Header: map[string][]string{"Content-Type": {"image/webp"}},
+ },
+ },
+ },
+ err: nil,
+ },
+ {
+ name: "should success with GIF sticker",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ Sticker: &multipart.FileHeader{
+ Filename: "sample-sticker.gif",
+ Size: 100,
+ Header: map[string][]string{"Content-Type": {"image/gif"}},
+ },
+ },
+ },
+ err: nil,
+ },
+ {
+ name: "should error with unsupported file type",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{Phone: "+6289123456"},
+ Sticker: &multipart.FileHeader{
+ Filename: "sample-sticker.bmp",
+ Size: 100,
+ Header: map[string][]string{"Content-Type": {"image/bmp"}},
+ },
+ },
+ },
+ err: pkgError.ValidationError("your sticker is not allowed. please use jpg/jpeg/png/webp/gif"),
+ },
+ {
+ name: "should success with valid duration",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{
+ Phone: "+6289123456",
+ Duration: func() *int { d := 3600; return &d }(),
+ },
+ Sticker: sticker,
+ },
+ },
+ err: nil,
+ },
+ {
+ name: "should error with invalid duration",
+ args: args{
+ request: domainSend.StickerRequest{
+ BaseRequest: domainSend.BaseRequest{
+ Phone: "+6289123456",
+ Duration: func() *int { d := -1; return &d }(),
+ },
+ Sticker: sticker,
+ },
+ },
+ err: pkgError.ValidationError("duration must be between 0 and 4294967295 seconds (0 means no expiry)"),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateSendSticker(context.Background(), tt.args.request)
+ assert.Equal(t, tt.err, err)
+ })
+ }
+}
\ No newline at end of file
diff --git a/src/views/components/SendSticker.js b/src/views/components/SendSticker.js
new file mode 100644
index 00000000..cae0c61f
--- /dev/null
+++ b/src/views/components/SendSticker.js
@@ -0,0 +1,190 @@
+import FormRecipient from "./generic/FormRecipient.js";
+
+export default {
+ name: 'SendSticker',
+ components: {
+ FormRecipient
+ },
+ data() {
+ return {
+ phone: '',
+ type: window.TYPEUSER,
+ loading: false,
+ selected_file: null,
+ sticker_url: null,
+ preview_url: null,
+ is_forwarded: false,
+ duration: 0
+ }
+ },
+ computed: {
+ phone_id() {
+ return this.phone + this.type;
+ },
+ },
+ methods: {
+ openModal() {
+ $('#modalSendSticker').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ },
+ isShowAttributes() {
+ return this.type !== window.TYPESTATUS;
+ },
+ isValidForm() {
+ if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
+ return false;
+ }
+
+ if (!this.selected_file && !this.sticker_url) {
+ return false;
+ }
+
+ return true;
+ },
+ async handleSubmit() {
+ if (!this.isValidForm() || this.loading) {
+ return;
+ }
+
+ try {
+ let response = await this.submitApi()
+ showSuccessInfo(response)
+ $('#modalSendSticker').modal('hide');
+ } catch (err) {
+ showErrorInfo(err)
+ }
+ },
+ async submitApi() {
+ this.loading = true;
+ try {
+ let payload = new FormData();
+ payload.append("phone", this.phone_id)
+ payload.append("is_forwarded", this.is_forwarded)
+ if (this.duration && this.duration > 0) {
+ payload.append("duration", this.duration)
+ }
+
+ const fileInput = $("#file_sticker");
+ if (fileInput.length > 0 && fileInput[0].files.length > 0) {
+ const file = fileInput[0].files[0];
+ payload.append('sticker', file);
+ }
+ if (this.sticker_url) {
+ payload.append('sticker_url', this.sticker_url)
+ }
+
+ let response = await window.http.post(`/send/sticker`, payload)
+ this.handleReset();
+ return response.data.message;
+ } catch (error) {
+ if (error.response) {
+ throw new Error(error.response.data.message);
+ }
+ throw new Error(error.message);
+ } finally {
+ this.loading = false;
+ }
+ },
+ handleReset() {
+ this.phone = '';
+ this.preview_url = null;
+ this.selected_file = null;
+ this.sticker_url = null;
+ this.is_forwarded = false;
+ this.duration = 0;
+ $("#file_sticker").val('');
+ },
+ handleStickerChange(event) {
+ const file = event.target.files[0];
+ if (file) {
+ this.preview_url = URL.createObjectURL(file);
+ // Add small delay to allow DOM update before scrolling
+ setTimeout(() => {
+ const modalContent = document.querySelector('#modalSendSticker .content');
+ if (modalContent) {
+ modalContent.scrollTop = modalContent.scrollHeight;
+ }
+ this.selected_file = file.name;
+ }, 100);
+ }
+ }
+ },
+ template: `
+ <div class="blue card" @click="openModal()" style="cursor:pointer;">
+ <div class="content">
+ <a class="ui blue right ribbon label">Send</a>
+ <div class="header">Send Sticker</div>
+ <div class="description">
+ Send sticker with automatic conversion to WebP format
+ <div class="ui blue horizontal label">jpg/jpeg/png/webp/gif</div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal SendSticker -->
+ <div class="ui small modal" id="modalSendSticker">
+ <i class="close icon"></i>
+ <div class="header">
+ Send Sticker
+ </div>
+ <div class="content" style="max-height: 70vh; overflow-y: auto;">
+ <form class="ui form">
+ <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="true"/>
+
+ <div class="ui info message">
+ <div class="header">Sticker Information</div>
+ <ul class="list">
+ <li>Images will be automatically converted to WebP sticker format</li>
+ <li>Maximum sticker size is 512x512 pixels (automatic resizing)</li>
+ <li>Supports JPG, JPEG, PNG, WebP, and GIF formats</li>
+ <li>Transparent backgrounds are preserved for PNG images</li>
+ </ul>
+ </div>
+
+ <div class="field" v-if="isShowAttributes()">
+ <label>Is Forwarded</label>
+ <div class="ui toggle checkbox">
+ <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
+ <label>Mark sticker as forwarded</label>
+ </div>
+ </div>
+ <div class="field">
+ <label>Disappearing Duration (seconds)</label>
+ <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
+ </div>
+ <div class="field">
+ <label>Sticker URL</label>
+ <input type="text" v-model="sticker_url" placeholder="https://example.com/sticker.png"
+ aria-label="sticker_url"/>
+ </div>
+ <div style="text-align: left; font-weight: bold; margin: 10px 0;">or you can upload sticker from your device</div>
+ <div class="field" style="padding-bottom: 30px">
+ <label>Sticker Image</label>
+ <input type="file" style="display: none" id="file_sticker" accept="image/png,image/jpg,image/jpeg,image/webp,image/gif" @change="handleStickerChange"/>
+ <label for="file_sticker" class="ui positive medium blue left floated button" style="color: white">
+ <i class="ui upload icon"></i>
+ Upload sticker
+ </label>
+ <div v-if="preview_url" style="margin-top: 60px">
+ <div class="ui segment">
+ <img :src="preview_url" style="max-width: 100%; max-height: 300px; object-fit: contain" />
+ <div class="ui top attached label">Preview (will be converted to WebP sticker)</div>
+ </div>
+ </div>
+ </div>
+ </form>
+ </div>
+ <div class="actions">
+ <button class="ui approve positive right labeled icon button"
+ :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
+ @click.prevent="handleSubmit">
+ Send
+ <i class="send icon"></i>
+ </button>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/index.html b/src/views/index.html
index ef9b5f19..5fa38148 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -73,11 +73,13 @@
<send-file max-file-size="{{ .MaxFileSize }}"></send-file>
<send-video max-video-size="{{ .MaxVideoSize }}"></send-video>
+ <send-sticker></send-sticker>
<send-contact></send-contact>
- <send-location></send-location>
+ <send-location></send-location>
<send-audio></send-audio>
<send-poll></send-poll>
+
<send-presence></send-presence>
<send-chat-presence></send-chat-presence>
@@ -190,6 +192,7 @@
import SendImage from "{{ .AppBasePath }}/components/SendImage.js";
import SendFile from "{{ .AppBasePath }}/components/SendFile.js";
import SendVideo from "{{ .AppBasePath }}/components/SendVideo.js";
+ import SendSticker from "{{ .AppBasePath }}/components/SendSticker.js";
import SendLink from "{{ .AppBasePath }}/components/SendLink.js";
import SendContact from "{{ .AppBasePath }}/components/SendContact.js";
import SendLocation from "{{ .AppBasePath }}/components/SendLocation.js";
@@ -256,7 +259,7 @@
Vue.createApp({
components: {
AppLogin, AppLoginWithCode, AppLogout, AppReconnect,
- SendMessage, SendImage, SendFile, SendVideo, SendLink, SendContact, SendLocation, SendAudio, SendPoll, SendPresence, SendChatPresence,
+ SendMessage, SendImage, SendFile, SendVideo, SendSticker, SendLink, SendContact, SendLocation, SendAudio, SendPoll, SendPresence, SendChatPresence,
MessageDelete, MessageUpdate, MessageReact, MessageRevoke, MessageRead,
GroupList, GroupCreate, GroupJoinWithLink, GroupInfoFromLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic, GroupGetInviteLink, GroupInfo,
NewsletterList,