How to Use tulir/whatsmeow for Custom WhatsApp Alerts in Go
tulir/whatsmeow is a Go (Golang) library that implements the communication protocol for WhatsApp's multi-device feature. Essentially, it allows you to build applications that can interact with WhatsApp accounts programmatically, just like the official WhatsApp Web or Desktop applications do.
From a software engineer's viewpoint, this library is a powerful tool because it abstracts the complex, reverse-engineered WhatsApp protocol, enabling you to focus on your application's business logic rather than the intricacies of network communication and message encoding.
This library opens up several exciting possibilities for automation, integration, and custom solutions
You can create a service that monitors system metrics, CI/CD pipelines, or database health, and sends real-time WhatsApp alerts directly to your team's group or specific individuals.
It's an excellent foundation for building custom WhatsApp chatbots. These can be used for customer support, processing simple requests, providing information (like order status), or automating internal workflows.
You can integrate WhatsApp messaging into your existing CRM, ERP, or internal tools. For example, automatically sending a WhatsApp message to a customer when their service ticket is updated.
Engineers can use it to script end-to-end tests that simulate real user interactions on WhatsApp or create monitoring tools that ensure message delivery and system uptime.
Since the library is written in Go, it's easy to deploy applications across various operating systems, making your WhatsApp integration highly portable.
Integrating whatsmeow into your Go project is straightforward. Here’s a step-by-step guide
Make sure you have a working Go environment installed on your machine.
Create a new directory for your project and initialize a Go module
mkdir whatsmeow-bot
cd whatsmeow-bot
go mod init your-module-name/whatsmeow-bot
Use the go get command to download and install whatsmeow
go get go.mau.fi/whatsmeow
WhatsApp uses a QR code for the initial multi-device login, similar to WhatsApp Web. Your application will need to
Generate a QR code from the library's output.
Display the QR code.
Wait for a user to scan it with their phone's WhatsApp app.
Once scanned, the session is established and saved (usually to a database or file) for future use, so you don't need to scan the QR code again.
This simple example shows how to connect to WhatsApp and send a basic text message. Note: You'll need to handle the QR code login process separately to make this fully functional.
package main
import (
"context"
"fmt"
"os"
"time"
"go.mau.fi/whatsmeow"
waProto "go.mau.fi/whatsmeow/binary/proto"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
"go.mau.fi/whatsmeow/types/events"
"google.golang.org/protobuf/proto"
)
// A function to handle incoming events (like new messages)
func eventHandler(evt interface{}) {
if v, ok := evt.(*events.Message); ok {
fmt.Printf("Received a message from %s: %s\n", v.Info.Sender, v.Message.GetConversation())
}
}
func main() {
// 1. Setup Database/Store
// We use an in-memory SQLite store for simplicity here, but a real app would use a persistent DB.
dbLog := whatsmeow.DumpLogs(os.Stdout, "Database", false)
container, err := sqlstore.New("sqlite", "file:examplestore.db?_foreign_keys=on", dbLog)
if err != nil {
panic(err)
}
// 2. Get the WhatsApp Client
deviceStore, err := container.Get device(types.JID{User: "YOUR_PHONE_NUMBER", Server: types.DefaultUserServer}) // Replace with your actual phone number JID
if err != nil {
panic(err)
}
clientLog := whatsmeow.DumpLogs(os.Stdout, "Client", false)
client := whatsmeow.NewClient(deviceStore, clientLog)
client.AddEventHandler(eventHandler) // Add our event handler
// 3. QR Code Login or Restore Session
// THIS IS CRUCIAL: You need to implement the QR code login logic here if a session doesn't exist.
// For this example, we assume a session is already saved.
if client.Store.ID == nil {
// Log in via QR code logic would go here:
// client.GenerateQRCode() -> wait for scan -> client.Connect()
fmt.Println("No existing session found. Please implement QR code login.")
return
}
// 4. Connect to WhatsApp
err = client.Connect()
if err != nil {
panic(err)
}
// 5. Send a Message Example
// Wait a moment for connection to stabilize
time.Sleep(5 * time.Second)
// Replace with the recipient's JID (e.g., types.JID{User: "RECIPIENT_PHONE_NUMBER", Server: types.DefaultUserServer})
recipientJID := types.JID{User: "1234567890", Server: types.DefaultUserServer}
msg := &waProto.Message{
Conversation: proto.String("Hello from my Go app using whatsmeow!"),
}
_, err = client.SendMessage(context.Background(), recipientJID, msg)
if err != nil {
fmt.Printf("Failed to send message: %v\n", err)
} else {
fmt.Println("Message sent successfully!")
}
// 6. Keep the client running (or disconnect gracefully)
<-time.After(30 * time.Second) // Keep the app running for a bit to listen for messages
client.Disconnect()
}
Key Takeaways from the Code
sqlstore
The library uses a store (like a database) to save the session data and message history, which is critical for the multi-device API.
client.AddEventHandler
This is how you process incoming data like new messages (events.Message)—the core of building a chatbot.
waProto.Message
WhatsApp uses its own protocol buffers for messages. The library uses these types to construct and send messages.