whatsapp

package
v1.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 22, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package whatsapp – events.go processes incoming WhatsApp events from whatsmeow and converts them into unified DevClaw IncomingMessage types.

Package whatsapp – media.go handles media upload, download, and message building for images, audio, video, documents, and stickers.

Package whatsapp implements the WhatsApp channel for DevClaw using whatsmeow — a native Go WhatsApp Web API library. No Node.js, no Baileys.

Features:

  • QR code login with persistent session
  • Send/receive text, images, audio, video, documents, stickers
  • Group message support
  • Reply and quoting
  • Reactions (emoji)
  • Typing indicators and read receipts
  • Media upload/download with encryption
  • Automatic reconnection with backoff
  • Connection state management and events

This is a core channel (compiled into the binary, not a plugin).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// SessionDir is the directory for session persistence (SQLite).
	// Ignored if DatabasePath is set.
	SessionDir string `yaml:"session_dir"`

	// DatabasePath is the path to the SQLite database file for session storage.
	// If set, the WhatsApp session tables (prefixed with whatsmeow_) will be
	// stored in this database alongside other devclaw data.
	// If empty, defaults to {SessionDir}/whatsapp.db.
	DatabasePath string `yaml:"database_path"`

	// Trigger is the keyword that activates the bot (e.g. "@devclaw").
	Trigger string `yaml:"trigger"`

	// RespondToGroups enables responding in group chats.
	RespondToGroups bool `yaml:"respond_to_groups"`

	// RespondToDMs enables responding in direct messages.
	RespondToDMs bool `yaml:"respond_to_dms"`

	// AutoRead marks incoming messages as read.
	AutoRead bool `yaml:"auto_read"`

	// SendTyping sends typing indicators while processing.
	SendTyping bool `yaml:"send_typing"`

	// MediaDir is the directory for downloaded media files.
	MediaDir string `yaml:"media_dir"`

	// MaxMediaSizeMB is the maximum media file size to process.
	MaxMediaSizeMB int `yaml:"max_media_size_mb"`

	// ReconnectBackoff is the initial backoff duration for reconnection.
	ReconnectBackoff time.Duration `yaml:"reconnect_backoff"`

	// MaxReconnectAttempts is the maximum number of reconnection attempts (0 = unlimited).
	MaxReconnectAttempts int `yaml:"max_reconnect_attempts"`
}

Config holds WhatsApp channel configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults.

type ConnectionEvent

type ConnectionEvent struct {
	State     ConnectionState `json:"state"`
	Previous  ConnectionState `json:"previous,omitempty"`
	Timestamp time.Time       `json:"timestamp"`
	Reason    string          `json:"reason,omitempty"`
	Details   map[string]any  `json:"details,omitempty"`
}

ConnectionEvent represents a connection state change event.

type ConnectionObserver

type ConnectionObserver interface {
	OnConnectionChange(evt ConnectionEvent)
}

ConnectionObserver receives connection state changes.

type ConnectionState

type ConnectionState string

ConnectionState represents the current connection state.

const (
	StateDisconnected ConnectionState = "disconnected"
	StateConnecting   ConnectionState = "connecting"
	StateConnected    ConnectionState = "connected"
	StateReconnecting ConnectionState = "reconnecting"
	StateWaitingQR    ConnectionState = "waiting_qr"
	StateQRScanned    ConnectionState = "qr_scanned"
	StateLoggingOut   ConnectionState = "logging_out"
	StateBanned       ConnectionState = "banned"
)

type QREvent

type QREvent struct {
	// Type is "code", "success", "timeout", "error", or "refresh".
	Type string `json:"type"`
	// Code is the raw QR code string (only for Type == "code").
	Code string `json:"code,omitempty"`
	// Message is a human-readable description.
	Message string `json:"message,omitempty"`
	// ExpiresAt is when the QR code expires.
	ExpiresAt time.Time `json:"expires_at,omitempty"`
	// SecondsLeft is seconds until expiration.
	SecondsLeft int `json:"seconds_left,omitempty"`
}

QREvent represents a QR code event sent to observers.

type QREventEnhanced

type QREventEnhanced struct {
	Type        string    `json:"type"`                   // "code", "success", "timeout", "error", "refresh"
	Code        string    `json:"code,omitempty"`         // Raw QR code string
	Message     string    `json:"message"`                // Human-readable message
	ExpiresAt   time.Time `json:"expires_at,omitempty"`   // When QR code expires
	SecondsLeft int       `json:"seconds_left,omitempty"` // Seconds until expiration
	Attempts    int       `json:"attempts,omitempty"`     // Number of QR attempts
}

QREventEnhanced represents an enhanced QR code event with more details.

type WhatsApp

type WhatsApp struct {
	// contains filtered or unexported fields
}

WhatsApp implements the channels.Channel, channels.MediaChannel, channels.PresenceChannel, and channels.ReactionChannel interfaces.

func New

func New(cfg Config, logger *slog.Logger) *WhatsApp

New creates a new WhatsApp channel instance.

func (*WhatsApp) AddConnectionObserver

func (w *WhatsApp) AddConnectionObserver(obs ConnectionObserver)

AddConnectionObserver registers a connection observer.

func (*WhatsApp) Connect

func (w *WhatsApp) Connect(ctx context.Context) error

Connect establishes the WhatsApp Web connection via whatsmeow. If no existing session is found, the QR login process runs in the background (non-blocking) so the server can start immediately. The QR code is streamed to web UI observers for scanning via browser.

func (*WhatsApp) Disconnect

func (w *WhatsApp) Disconnect() error

Disconnect gracefully closes the WhatsApp connection.

func (*WhatsApp) DownloadMedia

func (w *WhatsApp) DownloadMedia(ctx context.Context, msg *channels.IncomingMessage) ([]byte, string, error)

DownloadMedia downloads media from an incoming message.

func (*WhatsApp) GetState

func (w *WhatsApp) GetState() ConnectionState

GetState returns the current connection state (public API).

func (*WhatsApp) Health

func (w *WhatsApp) Health() channels.HealthStatus

Health returns the WhatsApp channel health status.

func (*WhatsApp) IsConnected

func (w *WhatsApp) IsConnected() bool

IsConnected returns true if WhatsApp is connected.

func (*WhatsApp) Logout

func (w *WhatsApp) Logout() error

Logout logs out and clears the session.

func (*WhatsApp) MarkRead

func (w *WhatsApp) MarkRead(ctx context.Context, chatID string, messageIDs []string) error

MarkRead marks messages as read.

func (*WhatsApp) Name

func (w *WhatsApp) Name() string

Name returns "whatsapp".

func (*WhatsApp) NeedsQR

func (w *WhatsApp) NeedsQR() bool

NeedsQR returns true if the WhatsApp session is not linked (needs QR scan).

func (*WhatsApp) Receive

func (w *WhatsApp) Receive() <-chan *channels.IncomingMessage

Receive returns the incoming messages channel.

func (*WhatsApp) RequestNewQR

func (w *WhatsApp) RequestNewQR(ctx context.Context) error

RequestNewQR disconnects and reconnects to generate a fresh QR code. This is used when the web UI needs a new QR after timeout.

func (*WhatsApp) SaveMediaToFile

func (w *WhatsApp) SaveMediaToFile(ctx context.Context, msg *channels.IncomingMessage) (string, error)

SaveMediaToFile downloads and saves media to disk.

func (*WhatsApp) Send

func (w *WhatsApp) Send(ctx context.Context, to string, msg *channels.OutgoingMessage) error

Send sends a text message to the specified JID.

func (*WhatsApp) SendMedia

func (w *WhatsApp) SendMedia(ctx context.Context, to string, media *channels.MediaMessage) error

SendMedia sends a media message (image, audio, video, document, sticker).

func (*WhatsApp) SendPresence

func (w *WhatsApp) SendPresence(ctx context.Context, available bool) error

SendPresence updates the bot's online/offline status.

func (*WhatsApp) SendReaction

func (w *WhatsApp) SendReaction(ctx context.Context, chatID, messageID, emoji string) error

SendReaction sends an emoji reaction to a message.

func (*WhatsApp) SendTyping

func (w *WhatsApp) SendTyping(ctx context.Context, to string) error

SendTyping sends a typing indicator.

func (*WhatsApp) SubscribeQR

func (w *WhatsApp) SubscribeQR() (chan QREvent, func())

SubscribeQR registers a channel to receive QR code events. Returns an unsubscribe function.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL