whatsapp

package module
v0.0.0-...-923db9c Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2024 License: AGPL-3.0 Imports: 30 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

This section is empty.

Types

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.
	Path     string // Local path to the file is stored on disk.
	// 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.

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.
}

A Avatar represents a small image representing a Contact or Group.

type Call

type Call struct {
	State     CallState
	JID       string
	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 (
	CallMissed CallState = 1 + iota
)

The call states handled by the overarching session event handler.

type ChatState

type ChatState struct {
	Kind     ChatStateKind
	JID      string
	GroupJID string
}

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 (
	ChatStateComposing ChatStateKind = 1 + iota
	ChatStatePaused
)

The chat states handled by the overarching session event handler.

type Contact

type Contact struct {
	JID  string // The WhatsApp JID for this contact.
	Name string // The user-set, human-readable name for this contact.
}

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 ErrorLevel

type ErrorLevel int

A ErrorLevel is a value representing the severity of a log message being handled.

const (
	LevelError ErrorLevel = 1 + iota
	LevelWarning
	LevelInfo
	LevelDebug
)

The log levels handled by the overarching Session logger.

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
	EventPair
	EventConnected
	EventLoggedOut
	EventContact
	EventPresence
	EventMessage
	EventChatState
	EventReceipt
	EventGroup
	EventCall
)

The event types handled by the overarching session adapter handler.

type EventPayload

type EventPayload struct {
	QRCode       string
	PairDeviceID string
	ConnectedJID string
	Contact      Contact
	Presence     Presence
	Message      Message
	ChatState    ChatState
	Receipt      Receipt
	Group        Group
	Call         Call
}

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.
	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.

func (*Gateway) SetLogHandler

func (w *Gateway) SetLogHandler(h HandleLogFunc)

SetLogHandler specifies the log handling function to use for all Gateway and Session operations.

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.
}

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 {
	JID         string                 // The WhatsApp JID for this participant.
	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 always 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.
	GroupParticipantActionUpdate                               // Update existing participant information.
	GroupParticipantActionRemove                               // Remove participant from list, if existing.
)

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.
	SetByJID string // The JID 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 Session, accepting an event type and payload. Note that this is distinct to the [Session.handleEvent] function, which may emit events into the Python Session event handler but which otherwise does not process across Python/Go boundaries.

type HandleLogFunc

type HandleLogFunc func(ErrorLevel, string)

HandleLogFunc is the signature for the overarching Gateway log handling function.

func (HandleLogFunc) Debugf

func (h HandleLogFunc) Debugf(msg string, args ...interface{})

Debugf handles the given message as representing an internal-only debug message.

func (HandleLogFunc) Errorf

func (h HandleLogFunc) Errorf(msg string, args ...interface{})

Errorf handles the given message as representing a (typically) fatal error.

func (HandleLogFunc) Infof

func (h HandleLogFunc) Infof(msg string, args ...interface{})

Infof handles the given message as representing an informational notice.

func (HandleLogFunc) Sub

Sub is a no-op and will return the receiver itself.

func (HandleLogFunc) Warnf

func (h HandleLogFunc) Warnf(msg string, args ...interface{})

Warn handles the given message as representing a non-fatal error or warning thereof.

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 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.
	JID         string       // The JID this message concerns, semantics can change based on IsCarbon.
	GroupJID    string       // The JID of the group-chat this message was sent in, if any.
	OriginJID   string       // For reactions and replies in groups, the JID of the original user.
	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.
	IsCarbon    bool         // Whether or not this message concerns the gateway user themselves.
	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.
}

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 = 1 + iota
	MessageEdit
	MessageRevoke
	MessageReaction
	MessageAttachment
)

The message types handled by the overarching session event handler.

type Presence

type Presence struct {
	JID      string
	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 (
	PresenceAvailable PresenceKind = 1 + iota
	PresenceUnavailable
)

The presences handled by the overarching session event handler.

type Preview

type Preview struct {
	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.
	ImagePath   string // The local path for the image associated with the URL.
}

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 Receipt

type Receipt struct {
	Kind       ReceiptKind // The distinct kind of receipt presented.
	MessageIDs []string    // The list of message IDs to mark for receipt.
	JID        string
	GroupJID   string
	Timestamp  int64
	IsCarbon   bool
}

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 (
	ReceiptDelivered ReceiptKind = 1 + iota
	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) 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) 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) 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, avatarPath string) (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 made via the [propagateEvent] function.

Jump to

Keyboard shortcuts

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