whatsapp

package module
v0.0.0-...-93fb4c5 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2026 License: AGPL-3.0 Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// The default host part for user JIDs on WhatsApp.
	DefaultUserServer = types.DefaultUserServer

	// The default host part for group JIDs on WhatsApp.
	DefaultGroupServer = types.GroupServer
)

Variables

This section is empty.

Functions

func IsAnonymousJID

func IsAnonymousJID(id string) bool

IsAnonymousJID returns true if the JID given is not addressible, that is, if it's actually a LID.

Types

type Actor

type Actor struct {
	JID  string
	LID  string
	IsMe bool
}

Actor identifies who has triggered the event. It is either a contact identified by a proper JID (in 1:1) or a participant identified by a LID (in groups).

type Album

type Album struct {
	IsAlbum    bool // Whether or not the message is an album, regardless of calculated media counts.
	ImageCount int  // The calculated amount of images in the album, might not be accurate.
	VideoCount int  // The calculated amount of videos in the album, might not be accurate.
}

A Album message represents a collection of media files, typically images and videos.

type Attachment

type Attachment struct {
	MIME     string // The MIME type for attachment.
	Filename string // The recommended file name for this attachment. May be an auto-generated name.
	Caption  string // The user-provided caption, provided alongside this attachment.
	Data     []byte // Data for the attachment.
	// contains filtered or unexported fields
}

A Attachment represents additional binary data (e.g. images, videos, documents) provided alongside a message, for display or storage on the recepient client.

func (*Attachment) GetSpec

func (a *Attachment) GetSpec(ctx context.Context) (*media.Spec, error)

GetSpec returns metadata for this attachment, as derived from the underlying attachment data.

type Avatar

type Avatar struct {
	ID  string // The unique ID for this avatar, used for persistent caching.
	URL string // The HTTP URL over which this avatar might be retrieved. Can change for the same ID.

	ResourceID string // JID of the group or contact this avatar concerns
	IsGroup    bool   // Whether this JID is a group or a contact
}

A Avatar represents a small image set for a Contact or Group.

type Call

type Call struct {
	State     CallState
	Actor     Actor
	Timestamp int64
}

A Call represents an incoming or outgoing voice/video call made over WhatsApp. Full support for calls is currently not implemented, and this structure contains the bare minimum data required for notifying on missed calls.

type CallState

type CallState int

CallState represents the state of the call to synchronize with.

const (
	CallUnknown CallState = iota
	CallIncoming
	CallMissed
)

The call states handled by the overarching session event handler.

type Chat

type Chat struct {
	JID     string
	IsGroup bool
}

Chat identifies a contact or a group, in other words, the "conversation" where an event takes place.

type ChatState

type ChatState struct {
	Kind  ChatStateKind
	Chat  Chat
	Actor Actor
}

A ChatState represents the activity of a contact within a certain discussion, for instance, whether the contact is currently composing a message. This is separate to the concept of a Presence, which is the contact's general state across all discussions.

type ChatStateKind

type ChatStateKind int

ChatStateKind represents the different kinds of chat-states possible in WhatsApp.

const (
	ChatStateUnknown ChatStateKind = iota
	ChatStateComposing
	ChatStatePaused
)

The chat states handled by the overarching session event handler.

type Connect

type Connect struct {
	JID   string // The device JID given for this connection.
	Error string // The connection error, if any.
}

Connect represents event data related to a connection to WhatsApp being established, or failing to do so (based on the [Connect.Error] result).

type Contact

type Contact struct {
	Actor    Actor
	Name     string // The user-set, human-readable name for this contact.
	IsFriend bool   // Whether this contact is in the user's contact list.
}

A Contact represents any entity that be communicated with directly in WhatsApp. This typically represents people, but may represent a business or bot as well, but not a group-chat.

type EventKind

type EventKind int

EventKind represents all event types recognized by the Python session adapter, as emitted by the Go session adapter.

const (
	EventUnknown EventKind = iota
	EventQRCode
	EventPairDeviceID
	EventConnect
	EventLoggedOut
	EventContact
	EventPresence
	EventMessage
	EventChatState
	EventReceipt
	EventGroup
	EventCall
	EventAvatar
)

The event types handled by the overarching session adapter handler.

type EventPayload

type EventPayload struct {
	QRCode       string
	PairDeviceID string
	Connect      Connect
	LoggedOut    LoggedOut
	Contact      Contact
	Presence     Presence
	Message      Message
	ChatState    ChatState
	Receipt      Receipt
	Group        Group
	Call         Call
	Avatar       Avatar
}

EventPayload represents the collected payloads for all event types handled by the overarching session adapter handler. Only specific fields will be populated in events emitted by internal handlers, see documentation for specific types for more information.

type Gateway

type Gateway struct {
	DBPath   string // The filesystem path for the client database.
	Name     string // The name to display when linking devices on WhatsApp.
	LogLevel string // The verbosity level to use when logging messages.
	TempDir  string // The directory to create temporary files under.
	// contains filtered or unexported fields
}

A Gateway represents a persistent process for establishing individual sessions between linked devices and WhatsApp.

func NewGateway

func NewGateway() *Gateway

NewGateway returns a new, un-initialized Gateway. This function should always be followed by calls to Gateway.Init, assuming a valid [Gateway.DBPath] is set.

func (*Gateway) CleanupSession

func (w *Gateway) CleanupSession(device LinkedDevice) error

CleanupSession will remove all invalid and obsolete references to the given device, and should be used when pairing a new device or unregistering from the Gateway.

func (*Gateway) Init

func (w *Gateway) Init() error

Init performs initialization procedures for the Gateway, and is expected to be run before any calls to [Gateway.Session].

func (*Gateway) NewSession

func (w *Gateway) NewSession(device LinkedDevice) *Session

NewSession returns a new Session for the LinkedDevice given. If the linked device does not have a valid ID, a pair operation will be required, as described in Session.Login.

type Group

type Group struct {
	JID          string             // The WhatsApp JID for this group.
	Name         string             // The user-defined, human-readable name for this group.
	Subject      GroupSubject       // The longer-form, user-defined description for this group.
	Nickname     string             // Our own nickname in this group-chat.
	Participants []GroupParticipant // The list of participant contacts for this group, including ourselves.
	InviteCode   string             // The code for inviting members to this group-chat.
}

A Group represents a named, many-to-many chat space which may be joined or left at will. All fields apart from the group JID are considered to be optional, and may not be set in cases where group information is being updated against previous assumed state. Groups in WhatsApp are generally invited to out-of-band with respect to overarching adaptor; see the documentation for Session.GetGroups for more information.

type GroupAffiliation

type GroupAffiliation int

GroupAffiliation represents the set of privilidges given to a specific participant in a group.

const (
	GroupAffiliationNone  GroupAffiliation = iota // None, or normal member group affiliation.
	GroupAffiliationAdmin                         // Can perform some management operations.
	GroupAffiliationOwner                         // Can manage group fully, including destroying the group.
)

type GroupParticipant

type GroupParticipant struct {
	Actor       Actor
	Nickname    string                 // The user-set name for this participant, typically only set for anonymous participants.
	Affiliation GroupAffiliation       // The set of priviledges given to this specific participant.
	Action      GroupParticipantAction // The specific action to take for this participant; typically to add.
}

A GroupParticipant represents a contact who is currently joined in a given group. Participants in WhatsApp can generally be derived back to their individual Contact; there are no anonymous groups in WhatsApp.

type GroupParticipantAction

type GroupParticipantAction int

GroupParticipantAction represents the distinct set of actions that can be taken when encountering a group participant, typically to add or remove.

const (
	GroupParticipantActionAdd     GroupParticipantAction = iota // Default action; add participant to list.
	GroupParticipantActionRemove                                // Remove participant from list, if existing.
	GroupParticipantActionPromote                               // Make group member into administrator.
	GroupParticipantActionDemote                                // Make group administrator into member.
)

type GroupSubject

type GroupSubject struct {
	Subject string // The user-defined group description.
	SetAt   int64  // The exact time this group description was set at, as a timestamp.
	SetBy   Actor  // The name of the user that set the subject.
}

A GroupSubject represents the user-defined group description and attached metadata thereof, for a given Group.

type HandleEventFunc

type HandleEventFunc func(EventKind, *EventPayload)

HandleEventFunc represents a handler for incoming events sent to the Python adapter, accepting an event type and payload.

type LinkedDevice

type LinkedDevice struct {
	// ID is an opaque string identifying this LinkedDevice to the Session. Noted that this string
	// is currently equivalent to a password, and needs to be protected accordingly.
	ID string
}

A LinkedDevice represents a unique pairing session between the gateway and WhatsApp. It is not unique to the underlying "main" device (or phone number), as multiple linked devices may be paired with any main device.

func (LinkedDevice) JID

func (d LinkedDevice) JID() types.JID

JID returns the WhatsApp JID corresponding to the LinkedDevice ID. Empty or invalid device IDs may return invalid JIDs, and this function does not handle errors.

type Location

type Location struct {
	Latitude  float64
	Longitude float64
	Accuracy  int
	IsLive    bool

	// Optional fields given for named locations.
	Name    string
	Address string
	URL     string
}

A Location represents additional metadata given to location messages.

type LoggedOut

type LoggedOut struct {
	Reason string // The human-readable reason for logging out, if any.
}

LoggedOut repreents event data related to an explicit or implicit log-out event.

type Message

type Message struct {
	Kind        MessageKind  // The concrete message kind being sent or received.
	ID          string       // The unique message ID, used for referring to a specific Message instance.
	Actor       Actor        // Identifies who sent this message
	Chat        Chat         // The JID of the group or contact.
	OriginActor Actor        // Identifies who sent a message being referred to for reaction, replies and moderation
	Body        string       // The plain-text message body. For attachment messages, this can be a caption.
	Timestamp   int64        // The Unix timestamp denoting when this message was created.
	IsForwarded bool         // Whether or not the message was forwarded from another source.
	ReplyID     string       // The unique message ID this message is in reply to, if any.
	ReplyBody   string       // The full body of the message this message is in reply to, if any.
	Attachments []Attachment // The list of file (image, video, etc.) attachments contained in this message.
	Preview     Preview      // A short description for the URL provided in the message body, if any.
	Location    Location     // The location metadata for messages, if any.
	Poll        Poll         // The multiple-choice poll contained in the message, if any.
	Album       Album        // The image album message, if any.
	GroupInvite Group        // Group information for the invite group included in this message, if any.
	MentionJIDs []string     // A list of JIDs mentioned in this message, if any.
	Receipts    []Receipt    // The receipt statuses for the message, typically provided alongside historical messages.
	Reactions   []Message    // Reactions attached to message, typically provided alongside historical messages.
	IsHistory   bool         // Whether or not the message is derived from message history.
	ReferenceID string       // A message referenced in this message, for edits.
}

A Message represents one of many kinds of bidirectional communication payloads, for example, a text message, a file (image, video) attachment, an emoji reaction, etc. Messages of different kinds are denoted as such, and re-use fields where the semantics overlap.

type MessageKind

type MessageKind int

MessageKind represents all concrete message types (plain-text messages, edit messages, reactions) recognized by the Python session adapter.

const (
	MessagePlain MessageKind = iota
	MessageEdit
	MessageRevoke
	MessageReaction
	MessageAttachment
	MessagePoll
)

The message types handled by the overarching session event handler.

type Poll

type Poll struct {
	Title   string       // The human-readable name of this poll.
	Options []PollOption // The list of choices to vote on in the poll.
}

A Poll represents a multiple-choice question, on which each choice might be voted for one or more times.

type PollOption

type PollOption struct {
	Title string // The human-readable name for the poll option.
}

A PollOption represents an individual choice within a broader poll.

type Presence

type Presence struct {
	Actor    Actor
	Kind     PresenceKind
	LastSeen int64
}

Precence represents a contact's general state of activity, and is periodically updated as contacts start or stop paying attention to their client of choice.

type PresenceKind

type PresenceKind int

PresenceKind represents the different kinds of activity states possible in WhatsApp.

const (
	PresenceUnknown PresenceKind = iota
	PresenceAvailable
	PresenceUnavailable
)

The presences handled by the overarching session event handler.

type Preview

type Preview struct {
	Kind        PreviewKind // The kind of preview to show, defaults to plain URL preview.
	URL         string      // The original (or canonical) URL this preview was generated for.
	Title       string      // The short title for the URL preview.
	Description string      // The (optional) long-form description for the URL preview.
	Thumbnail   []byte      // The (optional) thumbnail image data.
}

A Preview represents a short description for a URL provided in a message body, as usually derived from the content of the page pointed at.

type PreviewKind

type PreviewKind int

PreviewKind represents different ways of previewingadditional data inline with messages.

const (
	PreviewPlain PreviewKind = iota
	PreviewVideo
)

type Receipt

type Receipt struct {
	Kind        ReceiptKind // The distinct kind of receipt presented.
	MessageIDs  []string    // The list of message IDs to mark for receipt.
	Actor       Actor
	OriginActor Actor
	Chat        Chat
	Timestamp   int64
}

A Receipt represents a notice of delivery or presentation for Message instances sent or received. Receipts can be delivered for many messages at once, but are generally all delivered under one specific state at a time.

type ReceiptKind

type ReceiptKind int

ReceiptKind represents the different types of delivery receipts possible in WhatsApp.

const (
	ReceiptUnknown ReceiptKind = iota
	ReceiptDelivered
	ReceiptRead
)

The delivery receipts handled by the overarching session event handler.

type Session

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

A Session represents a connection (active or not) between a linked device and WhatsApp. Active sessions need to be established by logging in, after which incoming events will be forwarded to the adapter event handler, and outgoing events will be forwarded to WhatsApp.

func (*Session) CreateGroup

func (s *Session) CreateGroup(name string, participants []string) (Group, error)

CreateGroup attempts to create a new WhatsApp group for the given human-readable name and participant JIDs given.

func (*Session) Disconnect

func (s *Session) Disconnect() error

Disconnects detaches the current connection to WhatsApp without removing any linked device state.

func (*Session) FindContact

func (s *Session) FindContact(phone string) (Contact, error)

FindContact attempts to check for a registered contact on WhatsApp corresponding to the given phone number, returning a concrete instance if found; typically, only the contact JID is set. No error is returned if no contact was found, but any unexpected errors will otherwise be returned directly.

func (*Session) GenerateMessageID

func (s *Session) GenerateMessageID() string

GenerateMessageID returns a valid, pseudo-random message ID for use in outgoing messages.

func (*Session) GetAvatar

func (s *Session) GetAvatar(resourceID, avatarID string) (Avatar, error)

GetAvatar fetches a profile picture for the Contact or Group JID given. If a non-empty `avatarID` is also given, GetAvatar will return an empty Avatar instance with no error if the remote state for the given ID has not changed.

func (*Session) GetContacts

func (s *Session) GetContacts(refresh bool) ([]Contact, error)

GetContacts subscribes to the WhatsApp roster currently stored in the Session's internal state. If `refresh` is `true`, FetchRoster will pull application state from the remote service and synchronize any contacts found with the adapter.

func (*Session) GetGroups

func (s *Session) GetGroups() ([]Group, error)

GetGroups returns a list of all group-chats currently joined in WhatsApp, along with additional information on present participants.

func (*Session) LeaveGroup

func (s *Session) LeaveGroup(resourceID string) error

LeaveGroup attempts to remove our own user from the given WhatsApp group, for the JID given.

func (*Session) Login

func (s *Session) Login() error

Login attempts to authenticate the given Session, either by re-using the LinkedDevice attached or by initiating a pairing session for a new linked device. Callers are expected to have set an event handler in order to receive any incoming events from the underlying WhatsApp session.

func (*Session) Logout

func (s *Session) Logout() error

Logout disconnects and removes the current linked device locally and initiates a logout remotely.

func (*Session) PairPhone

func (s *Session) PairPhone(phone string) (string, error)

PairPhone returns a one-time code from WhatsApp, used for pairing this Session against the user's primary device, as identified by the given phone number. This will return an error if the Session is already paired, or if the phone number given is empty or invalid.

func (*Session) RequestAvatar

func (s *Session) RequestAvatar(resourceID, avatarID string)

Enqueue an avatar refresh. Processed in an anonymous go routine defined in Session.login()

func (*Session) RequestMessageHistory

func (s *Session) RequestMessageHistory(resourceID string, oldestMessage Message) error

RequestMessageHistory sends and asynchronous request for message history related to the given resource (e.g. Contact or Group JID), ending at the oldest message given. Messages returned from history should then be handled as a `HistorySync` event of type `ON_DEMAND`, in the session-wide event handler. An error will be returned if requesting history fails for any reason.

func (*Session) SendChatState

func (s *Session) SendChatState(state ChatState) error

SendChatState sends the given chat state notification (e.g. composing message) to WhatsApp for the contact specified within.

func (*Session) SendMessage

func (s *Session) SendMessage(message Message) error

SendMessage processes the given Message and sends a WhatsApp message for the kind and contact JID specified within. In general, different message kinds require different fields to be set; see the documentation for the Message type for more information.

func (*Session) SendPresence

func (s *Session) SendPresence(presence PresenceKind, statusMessage string) error

SendPresence sets the activity state and (optional) status message for the current session and user. An error is returned if setting availability fails for any reason.

func (*Session) SendReceipt

func (s *Session) SendReceipt(receipt Receipt) error

SendReceipt sends a read receipt to WhatsApp for the message IDs specified within.

func (*Session) SetAvatar

func (s *Session) SetAvatar(resourceID string, avatar []byte) (string, error)

SetAvatar updates the profile picture for the Contact or Group JID given; it can also update the profile picture for our own user by providing an empty JID. The unique picture ID is returned, typically used as a cache reference or in providing to future calls for Session.GetAvatar.

func (*Session) SetEventHandler

func (s *Session) SetEventHandler(h HandleEventFunc)

SetEventHandler assigns the given handler function for propagating internal events into the Python gateway. Note that the event handler function is not entirely safe to use directly, and all calls should instead be sent to the Gateway via its internal call channel.

func (*Session) SetGroupName

func (s *Session) SetGroupName(resourceID, name string) error

SetGroupName updates the name of a WhatsApp group for the Group JID given.

func (*Session) SetGroupTopic

func (s *Session) SetGroupTopic(resourceID, topic string) error

SetGroupName updates the topic of a WhatsApp group for the Group JID given.

func (*Session) SubscribeToPresences

func (s *Session) SubscribeToPresences() error

func (*Session) UpdateGroupParticipants

func (s *Session) UpdateGroupParticipants(resourceID string, participants []GroupParticipant) ([]GroupParticipant, error)

UpdateGroupParticipants processes changes to the given group's participants, including additions, removals, and changes to privileges. Participant JIDs given must be part of the authenticated session's roster at least, and must also be active group participants for other types of changes.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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