whapp

package
v0.0.0-...-01eed2d Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2020 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package whapp implements a nice library around WhatsApp web, puppeteering a chromium instance.

Index

Constants

This section is empty.

Variables

View Source
var ErrCDPUnknown = errors.New("unknown CDP error")

ErrCDPUnknown will be returned in some cases as an error when the called function/method encountered an unknown error with CDP.

View Source
var ErrLoggedIn = errors.New("logged in, should be logged out")

ErrLoggedIn will be returned as an error when the called function/method expects you to be logged out, but you are logged in.

View Source
var ErrLoggedOut = errors.New("logged out, should be logged in")

ErrLoggedOut will be returned as an error when the called function/method expects you to be logged in, but you are logged out.

Functions

This section is empty.

Types

type Chat

type Chat struct {
	ID                    ID        `json:"id"`
	HasPendingMessages    bool      `json:"pendingMsgs"`
	LastReceivedMessageID MessageID `json:"lastReceivedKey"`
	Timestamp             int64     `json:"t"`
	UnreadCount           int       `json:"unreadCount"`
	Archived              bool      `json:"archive"`
	IsReadOnly            bool      `json:"isReadOnly"`
	MuteInfo              MuteInfo  `json:"muteInfo"`

	Name        string       `json:"name"`
	Description *Description `json:"description"`

	PinTimestamp int64 `json:"pin"`

	NotSpam  bool     `json:"notSpam"`
	Kind     string   `json:"kind"`
	Contact  Contact  `json:"contact"`
	Presence Presence `json:"presence"`

	IsGroupChat bool `json:"isGroup"`
}

Chat represents a chat in WhatsApp.

func (Chat) AddParticipant

func (c Chat) AddParticipant(ctx context.Context, wi *Instance, userID ID) error

AddParticipant adds the user with the given userID to the current chat.

func (Chat) GetMessagesFromChatTillDate

func (c Chat) GetMessagesFromChatTillDate(
	ctx context.Context,
	wi *Instance,
	timestamp int64,
) ([]Message, error)

GetMessagesFromChatTillDate returns messages in the current chat with a timestamp equal to or greater than `timestamp`.

func (Chat) GetPresence

func (c Chat) GetPresence(ctx context.Context, wi *Instance) (Presence, error)

GetPresence retrieves and returns the presence of the current private chat.

func (Chat) Participants

func (c Chat) Participants(ctx context.Context, wi *Instance) ([]Participant, error)

Participants retrieves and returns a slice containing all participants of the current group chat.

func (Chat) PinTime

func (c Chat) PinTime() (pinTime time.Time, set bool)

PinTime returns the timestamp when the current chat was pinned, and whether or not it is currently pinned.

func (Chat) RemoveParticipant

func (c Chat) RemoveParticipant(ctx context.Context, wi *Instance, userID ID) error

RemoveParticipant removes the user with the given userID from the current chat.

func (Chat) SetAdmin

func (c Chat) SetAdmin(ctx context.Context, wi *Instance, userID ID, setAdmin bool) error

SetAdmin sets the admin state of the user with given userID in the current chat.

func (Chat) Title

func (c Chat) Title() string

Title returns the name of the current chat, with support for contacts without a name.

type Contact

type Contact struct {
	ID                ID     `json:"id"`
	Name              string `json:"name"`
	Type              string `json:"type"`
	PlaintextDisabled bool   `json:"plaintextDisabled"`
	StatusMute        bool   `json:"statusMute"`

	IsMe        bool `json:"isMe"`
	IsMyContact bool `json:"isMyContact"`
	IsPSA       bool `json:"isPSA"`
	IsUser      bool `json:"isUser"`
	IsWAContact bool `json:"isWAContact"`
	IsBusiness  bool `json:"isBusiness"`

	ProfilePictureURL string `json:"profilePictureUrl"`

	ShortName     string `json:"formattedShortName"`
	PushName      string `json:"pushname"`
	FormattedName string `json:"formattedName"`
}

Contact represents a contact in the users contacts list.

func (Contact) GetCommonGroups

func (c Contact) GetCommonGroups(ctx context.Context, wi *Instance) ([]Chat, error)

GetCommonGroups gets the groups both the logged-in user and the contact c are in.

func (Contact) GetName

func (c Contact) GetName() string

GetName returns the name of the current contact, tries to get the best matching name possible. When the contact doesn't have a name in the user's contacts, this function will try to use the PushName, if the contact has one.

type Description

type Description struct {
	ID          string `json:"id"`
	Description string `json:"desc"`
	SetBy       ID     `json:"owner"`
	Timestamp   int64  `json:"time"`
}

A Description tells more about a group chat.

func (Description) Time

func (d Description) Time() time.Time

Time returns the timestamp of the current description converted to a time.Time instance.

type ID

type ID struct {
	Server string `json:"server"`
	User   string `json:"user"`
}

ID contains an ID of an user.

func (ID) String

func (id ID) String() string

type Instance

type Instance struct {
	LoginState LoginState
	// contains filtered or unexported fields
}

Instance is an instance to Whatsapp Web.

func MakeInstance

func MakeInstance(
	ctx context.Context,
	headless bool,
	loggingLevel LoggingLevel,
) (*Instance, error)

MakeInstance makes a new Instance.

func MakeInstanceWithPool

func MakeInstanceWithPool(
	ctx context.Context,
	pool *chromedp.Pool,
	headless bool,
	loggingLevel LoggingLevel,
) (*Instance, error)

MakeInstanceWithPool makes a new Instance using the given pool.

func (*Instance) GetAllChats

func (wi *Instance) GetAllChats(ctx context.Context) ([]Chat, error)

GetAllChats returns a slice containing all the chats the user has participated in.

func (*Instance) GetLocalStorage

func (wi *Instance) GetLocalStorage(ctx context.Context) (map[string]string, error)

GetLocalStorage retrieves and returns the localstorage of the current instance on the current tab. This method expects you to already have Whatsapp Web open.

func (*Instance) GetLoginCode

func (wi *Instance) GetLoginCode(ctx context.Context) (string, error)

GetLoginCode retrieves the login code for the current instance. This can be used to generate a QR code which can be scanned using the Whatsapp mobile app.

func (*Instance) GetMe

func (wi *Instance) GetMe(ctx context.Context) (Me, error)

GetMe returns the Me object for the current instance.

func (*Instance) GetPhoneActive

func (wi *Instance) GetPhoneActive(ctx context.Context) (bool, error)

GetPhoneActive returns Whether or not the user's phone is active.

func (*Instance) ListenForMessages

func (wi *Instance) ListenForMessages(ctx context.Context, interval time.Duration) (<-chan Message, <-chan error)

ListenForMessages listens for new messages by polling every `interval`.

func (*Instance) ListenForPhoneActiveChange

func (wi *Instance) ListenForPhoneActiveChange(ctx context.Context, interval time.Duration) (<-chan bool, <-chan error)

ListenForPhoneActiveChange listens for changes in the user's phone activity.

func (*Instance) ListenLoggedIn

func (wi *Instance) ListenLoggedIn(ctx context.Context, interval time.Duration) (<-chan bool, <-chan error)

ListenLoggedIn listens for login state changes by polling it every `interval`.

func (*Instance) Navigate

func (wi *Instance) Navigate(ctx context.Context) error

Navigate opens a tab with WhatsApp Web, without checking the login state.

func (*Instance) Open

func (wi *Instance) Open(ctx context.Context) (LoginState, error)

Open opens a tab with WhatsApp Web and returns the current login state.

func (*Instance) SendMessageToChatID

func (wi *Instance) SendMessageToChatID(ctx context.Context, chatID ID, message string) error

SendMessageToChatID sends the given `message` to the chat with the given `chatID`.

func (*Instance) SetLocalStorage

func (wi *Instance) SetLocalStorage(ctx context.Context, localStorage map[string]string) error

SetLocalStorage adds all keys given by `localStorage` to the localStorage of the current instance.

func (*Instance) Shutdown

func (wi *Instance) Shutdown(ctx context.Context) error

Shutdown shuts down the current Instance.

func (*Instance) WaitLogin

func (wi *Instance) WaitLogin(ctx context.Context) error

WaitLogin waits until the current instance has been done logging in. (the user scanned the QR code and is accepted)

type LocationData

type LocationData struct {
	Latitude   float64 `json:"latitude"`
	Longitude  float64 `json:"longitude"`
	InfoString string  `json:"string"`
}

LocationData contains information specific to a location message.

func (LocationData) String

func (loc LocationData) String() string

type LoggingLevel

type LoggingLevel int

LoggingLevel represents the level of logging by the CDP instance.

const (
	// LogLevelVerbose is the highest level of logging verbosity.
	LogLevelVerbose LoggingLevel = iota
	// LogLevelNormal is the normal level of logging verbosity.
	LogLevelNormal = iota
)

type LoginState

type LoginState int

LoginState represents the login state of an Instance.

const (
	// Loggedout is the state of a logged out instance.
	Loggedout LoginState = iota
	// Loggedin is the state of a logged in instance.
	Loggedin = iota
)

type Me

type Me struct {
	LoginCode         string    `json:"ref"`
	LoginCodeTTL      int       `json:"refTTL"`
	Connected         bool      `json:"connected"`
	SelfID            ID        `json:"me"`
	ProtocolVersion   []int     `json:"protoVersion"`
	ClientToken       string    `json:"clientToken"`
	ServerToken       string    `json:"serverToken"`
	BatteryPercentage int       `json:"battery"`
	PluggedIn         bool      `json:"plugged"`
	Location          string    `json:"lc"`
	Language          string    `json:"lg"`
	Uses24HourTime    bool      `json:"is24h"`
	Platform          string    `json:"platform"`
	Pushname          string    `json:"pushname"`
	Phone             PhoneInfo `json:"phone"`
}

Me contains info about the user logged in and their phone.

type MediaData

type MediaData struct {
	Type        string       `json:"type"`
	MediaStage  string       `json:"mediaStage"`
	Size        int64        `json:"size"`
	Filehash    string       `json:"filehash"`
	Mimetype    string       `json:"mimetype"`
	FullHeight  int          `json:"fullHeight"`
	FullWidth   int          `json:"fullWidth"`
	AspectRatio float64      `json:"aspectRatio"`
	Preview     MediaPreview `json:"preview"`
}

MediaData contains information about the media of a media message.

type MediaPreview

type MediaPreview struct {
	RetainCount       int    `json:"_retainCount"`
	InAutoreleasePool bool   `json:"_inAutoreleasePool"`
	Released          bool   `json:"released"`
	Base64            string `json:"_b64"` // TODO bytes
	Mimetype          string `json:"_mimetype"`
}

MediaPreview contains information about the preview of a media message.

type Message

type Message struct {
	ID         MessageID `json:"id"`
	Timestamp  int64     `json:"t"`
	NotifyName string    `json:"notifyName"`
	Sender     *Contact  `json:"senderObj"`
	From       ID        `json:"from"`
	To         ID        `json:"to"`
	Body       string    `json:"body"`
	Self       string    `json:"self"`
	Ack        int       `json:"ack"`
	Invis      bool      `json:"invis"`
	Starred    bool      `json:"star"`

	Type    string `json:"type"`
	Subtype string `json:"subtype"`

	RecipientIDs []ID `json:"recipients"`
	MentionedIDs []ID `json:"mentionedJidList"`

	IsGIF          bool `json:"isGif"`
	IsLive         bool `json:"isLive"`
	IsNewMessage   bool `json:"isNewMsg"`
	IsGroupMessage bool `json:"isGroupMsg"`
	IsLink         bool `json:"isLink"`
	IsMMS          bool `json:"isMMS"`
	IsNotification bool `json:"isNotification"`
	IsPSA          bool `json:"isPSA"`

	IsSentByMe        bool `json:"isSentByMe"`
	IsSentByMeFromWeb bool `json:"isSentByMeFromWeb"`

	IsMedia        bool      `json:"isMedia"`
	MediaData      MediaData `json:"mediaData"`
	MediaKey       string    `json:"mediaKey"` // make this nicer
	MimeType       string    `json:"mimetype"`
	MediaClientURL string    `json:"clientUrl"`
	MediaFileHash  string    `json:"filehash"`
	MediaFilename  string    `json:"filename"`
	Caption        string    `json:"caption"`

	Location *LocationData `json:"location"`

	PDFPageCount uint `json:"pageCount"`

	QuotedMessage *Message `json:"quotedMsgObj"`

	Chat Chat `json:"chat"`
}

Message represents any kind of message on Whatsapp. This also means the stuff like notifications (in the sense of e2e notifications, for example) are also represented by this struct.

func (Message) Content

func (msg Message) Content(participants []Participant, ownName string) string

Content returns the body of the current message, with mentions correctly resolved with support for files (just prints "--file--") and their captions.

func (Message) DownloadMedia

func (msg Message) DownloadMedia() ([]byte, error)

DownloadMedia downloads the media included in this message, if any

func (Message) FormatBody

func (msg Message) FormatBody(participants []Participant, ownName string) string

FormatBody returns the body of the current message, with mentions correctly resolved.

func (Message) FormatCaption

func (msg Message) FormatCaption(participants []Participant, ownName string) string

FormatCaption returns the body of the current message, with mentions correctly resolved.

func (Message) Time

func (msg Message) Time() time.Time

Time returns the timestamp of the current message converted to a time.Time instance.

type MessageID

type MessageID struct {
	FromMe     bool   `json:"fromMe"`
	ChatID     ID     `json:"remote"`
	ID         string `json:"id"`
	Serialized string `json:"_serialized"`
}

MessageID contains various IDs for a message.

type MuteInfo

type MuteInfo struct {
	IsMuted             bool  `json:"isMuted"`
	ExpirationTimestamp int64 `json:"expiration"`
}

MuteInfo contains information about the mute state of a chat.

func (MuteInfo) Expiration

func (i MuteInfo) Expiration() time.Time

Expiration returns the time when the mute is removed.

type Participant

type Participant struct {
	ID           ID      `json:"id"`
	IsAdmin      bool    `json:"isAdmin"`
	IsSuperAdmin bool    `json:"isSuperAdmin"`
	Contact      Contact `json:"contact"`
}

Participant represents a participants in a group chat.

type PhoneInfo

type PhoneInfo struct {
	WhatsAppVersion    string `json:"wa_version"`
	OsVersion          string `json:"os_version"`
	DeviceManufacturer string `json:"device_manufacturer"`
	DeviceModel        string `json:"device_model"`
	OsBuildNumber      string `json:"os_build_number"`
}

PhoneInfo contains info about the connected phone.

type Presence

type Presence struct {
	ID        ID     `json:"id"`
	Timestamp int64  `json:"timestamp"`
	Type      string `json:"type"`

	ChatActive bool `json:"chatActive"`
	HasData    bool `json:"hasData"`
	IsGroup    bool `json:"isGroup"`
	IsOnline   bool `json:"isOnline"`
	IsUser     bool `json:"isUser"`
}

Presence contains information about the presence of a contact of the user.

func (Presence) Time

func (p Presence) Time() time.Time

Time returns the timestamp of the current presence converted to a time.Time instance.

Jump to

Keyboard shortcuts

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