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: add chat list and messages UI components with auto-reply improvements (#347)

Aldino Kemal208a69b2b84a
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index e82697ba..bc5d9b05 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -57,13 +57,13 @@ def verify_webhook_signature(payload, signature, secret):
All webhook payloads share these common fields:
-| Field | Type | Description |
-|-------|------|-------------|
-| `sender_id` | string | User part of sender JID (phone number without @s.whatsapp.net) |
-| `chat_id` | string | User part of chat JID |
-| `from` | string | JID of the sender |
-| `timestamp` | string | RFC3339 formatted timestamp |
-| `pushname` | string | Display name of the sender |
+| **Field** | **Type** | **Description** |
+|----------------|----------|------------------------------------------------------------------------|
+| `sender_id` | string | User part of sender JID (phone number, without `@s.whatsapp.net`) |
+| `chat_id` | string | User part of chat JID |
+| `from` | string | Full JID of the sender (e.g., `[email protected]`) |
+| `timestamp` | string | RFC3339 formatted timestamp (e.g., `2023-10-15T10:30:00Z`) |
+| `pushname` | string | Display name of the sender |
## Message Events
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index b3811b84..9fcae782 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -427,7 +427,7 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
handleAutoMarkRead(ctx, evt)
// Handle auto-reply if configured
- handleAutoReply(evt)
+ handleAutoReply(ctx, evt, chatStorageRepo)
// Forward to webhook if configured
handleWebhookForward(ctx, evt)
@@ -479,16 +479,56 @@ func handleAutoMarkRead(_ context.Context, evt *events.Message) {
}
}
-func handleAutoReply(evt *events.Message) {
+func handleAutoReply(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository) {
if config.WhatsappAutoReplyMessage != "" &&
!utils.IsGroupJID(evt.Info.Chat.String()) &&
!evt.Info.IsIncomingBroadcast() &&
- evt.Message.GetExtendedTextMessage().GetText() != "" {
- _, _ = cli.SendMessage(
- context.Background(),
- utils.FormatJID(evt.Info.Sender.String()),
+ !evt.Info.IsFromMe {
+
+ // Check if the incoming message has text content using the utility function
+ messageText := utils.ExtractMessageTextFromEvent(evt)
+ if messageText == "" {
+ return // Don't auto-reply to non-text messages
+ }
+
+ // Format recipient JID
+ recipientJID := utils.FormatJID(evt.Info.Sender.String())
+
+ // Send the auto-reply message
+ response, err := cli.SendMessage(
+ ctx,
+ recipientJID,
&waE2E.Message{Conversation: proto.String(config.WhatsappAutoReplyMessage)},
)
+
+ if err != nil {
+ log.Errorf("Failed to send auto-reply message: %v", err)
+ return
+ }
+
+ // Store the auto-reply message in chat storage if send was successful
+ if chatStorageRepo != nil {
+ // Get our own JID as sender
+ senderJID := ""
+ if cli.Store.ID != nil {
+ senderJID = cli.Store.ID.String()
+ }
+
+ // Store the sent auto-reply message
+ if err := chatStorageRepo.StoreSentMessageWithContext(
+ ctx,
+ response.ID, // Message ID from WhatsApp response
+ senderJID, // Our JID as sender
+ recipientJID.String(), // Recipient JID
+ config.WhatsappAutoReplyMessage, // Auto-reply content
+ response.Timestamp, // Timestamp from response
+ ); err != nil {
+ // Log storage error but don't fail the auto-reply
+ log.Errorf("Failed to store auto-reply message in chat storage: %v", err)
+ } else {
+ log.Debugf("Auto-reply message %s stored successfully in chat storage", response.ID)
+ }
+ }
}
}
diff --git a/src/views/components/ChatList.js b/src/views/components/ChatList.js
new file mode 100644
index 00000000..f3df20ec
--- /dev/null
+++ b/src/views/components/ChatList.js
@@ -0,0 +1,216 @@
+export default {
+ name: 'ChatList',
+ data() {
+ return {
+ chats: [],
+ loading: false,
+ searchQuery: '',
+ includeMediaChats: false,
+ currentPage: 1,
+ pageSize: 10,
+ totalChats: 0,
+ selectedChatJid: ''
+ }
+ },
+ computed: {
+ totalPages() {
+ return Math.ceil(this.totalChats / this.pageSize);
+ },
+ filteredChats() {
+ if (!this.searchQuery) return this.chats;
+ return this.chats.filter(chat =>
+ chat.name?.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
+ chat.jid?.toLowerCase().includes(this.searchQuery.toLowerCase())
+ );
+ }
+ },
+ methods: {
+ openModal() {
+ $('#modalChatList').modal({
+ onApprove: function () {
+ return false;
+ }
+ }).modal('show');
+ this.loadChats();
+ },
+ async loadChats() {
+ this.loading = true;
+ try {
+ const params = new URLSearchParams({
+ offset: (this.currentPage - 1) * this.pageSize,
+ limit: this.pageSize
+ });
+
+ if (this.searchQuery.trim()) {
+ params.append('search', this.searchQuery);
+ }
+
+ if (this.includeMediaChats) {
+ params.append('has_media', 'true');
+ }
+
+ const response = await window.http.get(`/chats?${params}`);
+ this.chats = response.data.results?.data || [];
+ this.totalChats = response.data.results?.pagination?.total || 0;
+ } catch (error) {
+ showErrorInfo(error.response?.data?.message || 'Failed to load chats');
+ } finally {
+ this.loading = false;
+ }
+ },
+ async searchChats() {
+ this.currentPage = 1;
+ await this.loadChats();
+ },
+ nextPage() {
+ if (this.currentPage < this.totalPages) {
+ this.currentPage++;
+ this.loadChats();
+ }
+ },
+ prevPage() {
+ if (this.currentPage > 1) {
+ this.currentPage--;
+ this.loadChats();
+ }
+ },
+ selectChat(jid) {
+ this.selectedChatJid = jid;
+ // Store the JID for the chat messages component
+ localStorage.setItem('selectedChatJid', jid);
+
+ // Close the current modal and trigger ChatMessages openModal method
+ $('#modalChatList').modal({
+ onHidden: function() {
+ setTimeout(() => {
+ // Trigger a custom event to open ChatMessages modal properly
+ window.dispatchEvent(new CustomEvent('openChatMessages'));
+ }, 100);
+ }
+ }).modal('hide');
+ },
+ formatTimestamp(timestamp) {
+ if (!timestamp) return 'N/A';
+ return moment(timestamp).format('MMM DD, YYYY HH:mm');
+ },
+ formatJid(jid) {
+ if (!jid) return '';
+ if (jid.includes('@g.us')) return 'Group';
+ if (jid.includes('@s.whatsapp.net')) return 'Contact';
+ return 'Other';
+ }
+ },
+ 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">Chat List</div>
+ <div class="description">
+ View all chats with search and pagination
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal ChatList -->
+ <div class="ui large modal" id="modalChatList">
+ <i class="close icon"></i>
+ <div class="header">
+ <i class="comments icon"></i>
+ Chat List
+ </div>
+ <div class="content">
+ <div class="ui form">
+ <div class="fields">
+ <div class="twelve wide field">
+ <label>Search Chats</label>
+ <div class="ui icon input">
+ <input type="text"
+ placeholder="Search by name or JID..."
+ v-model="searchQuery"
+ @input="searchChats">
+ <i class="search icon"></i>
+ </div>
+ </div>
+ <div class="four wide field">
+ <label>&nbsp;</label>
+ <div class="ui checkbox">
+ <input type="checkbox" v-model="includeMediaChats" @change="searchChats">
+ <label>Media chats only</label>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="ui divider"></div>
+
+ <div v-if="loading" class="ui active centered inline loader"></div>
+
+ <div v-else-if="filteredChats.length === 0" class="ui placeholder segment">
+ <div class="ui icon header">
+ <i class="comments outline icon"></i>
+ No chats found
+ </div>
+ </div>
+
+ <div v-else>
+ <table class="ui celled striped table">
+ <thead>
+ <tr>
+ <th>Name</th>
+ <th>Type</th>
+ <th>JID</th>
+ <th>Last Message</th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="chat in filteredChats" :key="chat.jid">
+ <td>
+ <div class="ui header">
+ <div class="content">
+ {{ chat.name || 'Unknown' }}
+ </div>
+ </div>
+ </td>
+ <td>
+ <div class="ui label" :class="chat.jid?.includes('@g.us') ? 'blue' : 'green'">
+ {{ formatJid(chat.jid) }}
+ </div>
+ </td>
+ <td class="collapsing">
+ <code>{{ chat.jid }}</code>
+ </td>
+ <td>
+ {{ formatTimestamp(chat.last_message_time) }}
+ </td>
+ <td class="collapsing">
+ <button class="ui small primary button"
+ @click="selectChat(chat.jid)">
+ <i class="eye icon"></i>
+ View Messages
+ </button>
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <!-- Pagination -->
+ <div class="ui pagination menu" v-if="totalPages > 1">
+ <a class="icon item" @click="prevPage" :class="{ disabled: currentPage === 1 }">
+ <i class="left chevron icon"></i>
+ </a>
+ <div class="item">
+ Page {{ currentPage }} of {{ totalPages }}
+ </div>
+ <a class="icon item" @click="nextPage" :class="{ disabled: currentPage === totalPages }">
+ <i class="right chevron icon"></i>
+ </a>
+ </div>
+ </div>
+ </div>
+ <div class="actions">
+ <div class="ui approve button">Close</div>
+ </div>
+ </div>
+ `
+}
\ No newline at end of file
diff --git a/src/views/components/ChatMessages.js b/src/views/components/ChatMessages.js
new file mode 100644
index 00000000..606dda76
--- /dev/null
+++ b/src/views/components/ChatMessages.js
@@ -0,0 +1,341 @@
+export default {
+ name: "ChatMessages",
+ data() {
+ return {
+ jid: "",
+ messages: [],
+ loading: false,
+ searchQuery: "",
+ startTime: "",
+ endTime: "",
+ isFromMe: "",
+ onlyMedia: false,
+ currentPage: 1,
+ pageSize: 20,
+ totalMessages: 0,
+ };
+ },
+ computed: {
+ totalPages() {
+ return Math.ceil(this.totalMessages / this.pageSize);
+ },
+ formattedJid() {
+ return (
+ this.jid.trim() + (this.jid.includes("@") ? "" : "@s.whatsapp.net")
+ );
+ },
+ },
+ methods: {
+ isValidForm() {
+ return this.jid.trim().length > 0;
+ },
+ openModal() {
+ // Check if there's a pre-selected JID from chat list
+ const selectedJid = localStorage.getItem("selectedChatJid");
+ if (selectedJid) {
+ this.jid = selectedJid;
+ localStorage.removeItem("selectedChatJid"); // Clean up
+
+ this.loadMessages();
+ }
+
+ $("#modalChatMessages")
+ .modal({
+ onShow: function () {
+ // Initialize accordion after modal is shown
+ setTimeout(() => {
+ $("#modalChatMessages .ui.accordion").accordion();
+ }, 100);
+ },
+ })
+ .modal("show");
+ },
+ async loadMessages() {
+ if (!this.isValidForm()) {
+ showErrorInfo("Please enter a valid JID");
+ return;
+ }
+
+ this.loading = true;
+ try {
+ const params = new URLSearchParams({
+ offset: (this.currentPage - 1) * this.pageSize,
+ limit: this.pageSize,
+ });
+
+ if (this.searchQuery.trim()) {
+ params.append("search", this.searchQuery);
+ }
+
+ if (this.startTime) {
+ params.append("start_time", this.startTime);
+ }
+
+ if (this.endTime) {
+ params.append("end_time", this.endTime);
+ }
+
+ if (this.isFromMe !== "") {
+ params.append("is_from_me", this.isFromMe);
+ }
+
+ if (this.onlyMedia) {
+ params.append("media_only", "true");
+ }
+
+ const response = await window.http.get(
+ `/chat/${this.formattedJid}/messages?${params}`
+ );
+ this.messages = response.data.results?.data || [];
+ this.totalMessages = response.data.results?.pagination?.total || 0;
+
+ if (this.messages.length === 0) {
+ showErrorInfo("No messages found for the specified criteria");
+ }
+ } catch (error) {
+ showErrorInfo(
+ error.response?.data?.message || "Failed to load messages"
+ );
+ } finally {
+ this.loading = false;
+ }
+ },
+ searchMessages() {
+ this.currentPage = 1;
+ this.loadMessages();
+ },
+ nextPage() {
+ if (this.currentPage < this.totalPages) {
+ this.currentPage++;
+ this.loadMessages();
+ }
+ },
+ prevPage() {
+ if (this.currentPage > 1) {
+ this.currentPage--;
+ this.loadMessages();
+ }
+ },
+ handleReset() {
+ this.jid = "";
+ this.messages = [];
+ this.searchQuery = "";
+ this.startTime = "";
+ this.endTime = "";
+ this.isFromMe = "";
+ this.onlyMedia = false;
+ this.currentPage = 1;
+ this.totalMessages = 0;
+ },
+ formatTimestamp(timestamp) {
+ if (!timestamp) return "N/A";
+ return moment(timestamp).format("MMM DD, YYYY HH:mm:ss");
+ },
+ formatMessageType(message) {
+ if (message.media_type) return message.media_type.toUpperCase();
+ if (message.message_type) return message.message_type.toUpperCase();
+ return "TEXT";
+ },
+ formatSender(message) {
+ if (message.is_from_me) return "Me";
+ return message.push_name || message.sender_jid || "Unknown";
+ },
+ getMessageContent(message) {
+ if (message.content) return message.content;
+ if (message.text) return message.text;
+ if (message.caption) return message.caption;
+ if (message.media_type) return `[${message.media_type.toUpperCase()}]`;
+ return "[No content]";
+ },
+ getMessageStyle(message) {
+ const baseStyle = {
+ padding: "1em",
+ margin: "0.5em 0",
+ };
+
+ if (message.is_from_me) {
+ return {
+ ...baseStyle,
+ borderLeft: "4px solid #2185d0",
+ backgroundColor: "#f8f9fa",
+ };
+ } else {
+ return {
+ ...baseStyle,
+ borderLeft: "4px solid #767676",
+ };
+ }
+ },
+ },
+ mounted() {
+ // Store the event handler so we can remove it later
+ this.handleOpenChatMessages = () => {
+ this.openModal();
+ };
+
+ // Listen for custom event from ChatList to open modal properly
+ window.addEventListener('openChatMessages', this.handleOpenChatMessages);
+ },
+ beforeUnmount() {
+ // Clean up event listener
+ if (this.handleOpenChatMessages) {
+ window.removeEventListener('openChatMessages', this.handleOpenChatMessages);
+ }
+ },
+ 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">Chat Messages</div>
+ <div class="description">
+ View messages from specific chats with advanced filtering
+ </div>
+ </div>
+ </div>
+
+ <!-- Modal ChatMessages -->
+ <div class="ui large modal" id="modalChatMessages">
+ <i class="close icon"></i>
+ <div class="header">
+ <i class="comment icon"></i>
+ Chat Messages
+ </div>
+ <div class="content">
+ <div class="ui form">
+ <div class="field">
+ <label>Chat JID</label>
+ <input type="text"
+ placeholder="Enter phone number or full JID (e.g. 1234567890 or [email protected])"
+ v-model="jid">
+ </div>
+
+ <div class="ui accordion">
+ <div class="title">
+ <i class="dropdown icon"></i>
+ Advanced Filters (Optional)
+ </div>
+ <div class="content">
+ <div class="fields">
+ <div class="eight wide field">
+ <label>Search Message Content</label>
+ <input type="text"
+ placeholder="Search in message text..."
+ v-model="searchQuery">
+ </div>
+ <div class="four wide field">
+ <label>Sender Filter</label>
+ <select class="ui dropdown" v-model="isFromMe">
+ <option value="">All messages</option>
+ <option value="true">My messages</option>
+ <option value="false">Their messages</option>
+ </select>
+ </div>
+ <div class="four wide field">
+ <label>&nbsp;</label>
+ <div class="ui checkbox">
+ <input type="checkbox" v-model="onlyMedia">
+ <label>Media only</label>
+ </div>
+ </div>
+ </div>
+
+ <div class="fields">
+ <div class="eight wide field">
+ <label>Start Date/Time</label>
+ <input type="datetime-local" v-model="startTime">
+ </div>
+ <div class="eight wide field">
+ <label>End Date/Time</label>
+ <input type="datetime-local" v-model="endTime">
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <div class="ui divider"></div>
+
+ <div class="actions">
+ <button class="ui primary button"
+ :class="{'disabled': !isValidForm() || loading}"
+ @click="loadMessages">
+ <i class="search icon"></i>
+ {{ loading ? 'Loading...' : 'Load Messages' }}
+ </button>
+ <button class="ui button" @click="handleReset">
+ <i class="refresh icon"></i>
+ Reset
+ </button>
+ </div>
+
+ <div v-if="loading" class="ui active centered inline loader"></div>
+
+ <div v-else-if="messages.length === 0 && totalMessages === 0" class="ui placeholder segment">
+ <div class="ui icon header">
+ <i class="comment outline icon"></i>
+ No messages loaded
+ </div>
+ <p>Enter a JID and click "Load Messages" to view chat history</p>
+ </div>
+
+ <div v-else-if="messages.length > 0">
+ <div style="padding-top: 1em; padding-bottom: 1em;">
+ <div class="ui info message">
+ <div class="header">
+ Chat Messages for {{ formattedJid }}
+ </div>
+ <p>Showing {{ messages.length }} of {{ totalMessages }} messages</p>
+ </div>
+ </div>
+
+ <div class="ui divided items" style="max-height: 400px; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; scrollbar-width: thin;">
+ <div v-for="message in messages" :key="message.id"
+ class="item"
+ :style="getMessageStyle(message)">
+ <div class="content">
+ <div class="header">
+ <div class="ui horizontal label"
+ :class="message.is_from_me ? 'blue' : 'grey'">
+ {{ formatSender(message) }}
+ </div>
+ <div class="ui right floated horizontal label">
+ {{ formatMessageType(message) }}
+ </div>
+ </div>
+ <div class="meta">
+ <span>{{ formatTimestamp(message.timestamp) }}</span>
+ <span v-if="message.id" class="right floated">
+ ID: {{ message.id }}
+ </span>
+ </div>
+ <div class="description">
+ <p>{{ getMessageContent(message) }}</p>
+ <div v-if="message.url" class="ui tiny blue label">
+ <i class="linkify icon"></i>
+ Media Available
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Pagination -->
+ <div class="ui pagination menu" v-if="totalPages > 1">
+ <a class="icon item" @click="prevPage" :class="{ disabled: currentPage === 1 }">
+ <i class="left chevron icon"></i>
+ </a>
+ <div class="item">
+ Page {{ currentPage }} of {{ totalPages }}
+ </div>
+ <a class="icon item" @click="nextPage" :class="{ disabled: currentPage === totalPages }">
+ <i class="right chevron icon"></i>
+ </a>
+ </div>
+ </div>
+ </div>
+ <div class="actions">
+ <div class="ui approve button">Close</div>
+ </div>
+ </div>
+ `,
+};
diff --git a/src/views/index.html b/src/views/index.html
index 9e3978ea..03435787 100644
--- a/src/views/index.html
+++ b/src/views/index.html
@@ -143,6 +143,8 @@
<div class="ui three column doubling grid cards">
<chat-pin-manager></chat-pin-manager>
+ <chat-list></chat-list>
+ <chat-messages></chat-messages>
</div>
</div>
@@ -220,6 +222,8 @@
import AccountUserCheck from "./components/AccountUserCheck.js";
import AccountBusinessProfile from "./components/AccountBusinessProfile.js";
import ChatPinManager from "./components/ChatPinManager.js";
+ import ChatList from "./components/ChatList.js";
+ import ChatMessages from "./components/ChatMessages.js";
const showErrorInfo = (message) => {
$('body').toast({
@@ -259,7 +263,7 @@
GroupList, GroupCreate, GroupJoinWithLink, GroupInfoFromLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic, GroupInfo,
NewsletterList,
AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck, AccountBusinessProfile,
- ChatPinManager
+ ChatPinManager, ChatList, ChatMessages
},
delimiters: ['[[', ']]'],
data() {