whatsapp

package module
v0.5.8-0...-88fffa0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2021 License: MIT Imports: 29 Imported by: 0

README

go-whatsapp

Package rhymen/go-whatsapp implements the WhatsApp Web API to provide a clean interface for developers. Big thanks to all contributors of the sigalor/whatsapp-web-reveng project. The official WhatsApp Business API was released in August 2018. You can check it out here.

Installation

go get github.com/Rhymen/go-whatsapp

Usage

Creating a connection
import (
    whatsapp "github.com/Rhymen/go-whatsapp"
)

wac, err := whatsapp.NewConn(20 * time.Second)

The duration passed to the NewConn function is used to timeout login requests. If you have a bad internet connection use a higher timeout value. This function only creates a websocket connection, it does not handle authentication.

Login
qrChan := make(chan string)
go func() {
    fmt.Printf("qr code: %v\n", <-qrChan)
    //show qr code or save it somewhere to scan
}()
sess, err := wac.Login(qrChan)

The authentication process requires you to scan the qr code, that is send through the channel, with the device you are using whatsapp on. The session struct that is returned can be saved and used to restore the login without scanning the qr code again. The qr code has a ttl of 20 seconds and the login function throws a timeout err if the time has passed or any other request fails.

Restore
newSess, err := wac.RestoreWithSession(sess)

The restore function needs a valid session and returns the new session that was created.

Add message handlers
type myHandler struct{}

func (myHandler) HandleError(err error) {
	fmt.Fprintf(os.Stderr, "%v", err)
}

func (myHandler) HandleTextMessage(message whatsapp.TextMessage) {
	fmt.Println(message)
}

func (myHandler) HandleImageMessage(message whatsapp.ImageMessage) {
	fmt.Println(message)
}

func (myHandler) HandleDocumentMessage(message whatsapp.DocumentMessage) {
	fmt.Println(message)
}

func (myHandler) HandleVideoMessage(message whatsapp.VideoMessage) {
	fmt.Println(message)
}

func (myHandler) HandleAudioMessage(message whatsapp.AudioMessage){	
	fmt.Println(message)
}

func (myHandler) HandleJsonMessage(message string) {
	fmt.Println(message)
}

func (myHandler) HandleContactMessage(message whatsapp.ContactMessage) {
	fmt.Println(message)
}

func (myHandler) HandleBatteryMessage(msg whatsapp.BatteryMessage) {
	fmt.Println(message)
}

func (myHandler) HandleNewContact(contact whatsapp.Contact) {
	fmt.Println(contact)
}

wac.AddHandler(myHandler{})

The message handlers are all optional, you don't need to implement anything but the error handler to implement the interface. The ImageMessage, VideoMessage, AudioMessage and DocumentMessage provide a Download function to get the media data.

Sending text messages
text := whatsapp.TextMessage{
    Info: whatsapp.MessageInfo{
        RemoteJid: "0123456789@s.whatsapp.net",
    },
    Text: "Hello Whatsapp",
}

err := wac.Send(text)
Sending Contact Messages
contactMessage := whatsapp.ContactMessage{
			Info: whatsapp.MessageInfo{ 
                RemoteJid: "0123456789@s.whatsapp.net", 
                },
			DisplayName: "Luke Skylwallker",
			Vcard: "BEGIN:VCARD\nVERSION:3.0\nN:Skyllwalker;Luke;;\nFN:Luke Skywallker\nitem1.TEL;waid=0123456789:+1 23 456789789\nitem1.X-ABLabel:Mobile\nEND:VCARD",
		}

id, error := client.WaConn.Send(contactMessage)

The message will be send over the websocket. The attributes seen above are the required ones. All other relevant attributes (id, timestamp, fromMe, status) are set if they are missing in the struct. For the time being we only support text messages, but other types are planned for the near future.

This code is in no way affiliated with, authorized, maintained, sponsored or endorsed by WhatsApp or any of its affiliates or subsidiaries. This is an independent and unofficial software. Use at your own risk.

License

The MIT License (MIT)

Copyright (c) 2018

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package whatsapp provides a developer API to interact with the WhatsAppWeb-Servers.

Index

Constants

View Source
const (
	StreamUpdate = "update"
	StreamSleep  = "asleep"
)
View Source
const (
	Error       MessageStatus = 0
	Pending                   = 1
	ServerAck                 = 2
	DeliveryAck               = 3
	Read                      = 4
	Played                    = 5
)
View Source
const (
	OldUserSuffix   = "@c.us"
	NewUserSuffix   = "@s.whatsapp.net"
	GroupSuffix     = "@g.us"
	BroadcastSuffix = "@broadcast"
)

Variables

View Source
var (
	ErrAlreadyConnected           = errors.New("already connected")
	ErrAlreadyLoggedIn            = errors.New("already logged in")
	ErrSessionExists              = errors.New("a session with keys is already present")
	ErrInvalidSession             = errors.New("invalid session")
	ErrLoginInProgress            = errors.New("login or restore already running")
	ErrNotConnected               = errors.New("not connected")
	ErrNotLoggedIn                = errors.New("not logged in")
	ErrInvalidWsData              = errors.New("received invalid data")
	ErrInvalidWsState             = errors.New("can't handle binary data when not logged in")
	ErrConnectionTimeout          = errors.New("connection timed out")
	ErrMissingMessageTag          = errors.New("no messageTag specified or to short")
	ErrInvalidHmac                = errors.New("invalid hmac")
	ErrInvalidServerResponse      = errors.New("invalid response received from server")
	ErrServerRespondedWith404     = errors.New("server responded with status 404")
	ErrMediaDownloadFailedWith404 = errors.New("download failed with status code 404")
	ErrMediaDownloadFailedWith410 = errors.New("download failed with status code 410")
	ErrLoginTimedOut              = errors.New("login timed out")
	ErrQueryTimeout               = errors.New("query timed out")
	ErrRestoreSessionInitTimeout  = errors.New("restore session init timed out")
	ErrLoginCancelled             = errors.New("login cancelled")
	ErrAbortLogin                 = errors.New("abort login")
	ErrPingFalse                  = errors.New("ping returned false")
	ErrWebsocketKeepaliveFailed   = errors.New("websocket keepalive failed")

	ErrBadRequest   = errors.New("400 (bad request)")
	ErrUnpaired     = errors.New("401 (unpaired from phone)")
	ErrAccessDenied = errors.New("403 (access denied)")
	ErrLoggedIn     = errors.New("405 (already logged in)")
	ErrReplaced     = errors.New("409 (logged in from another location)")

	ErrNoURLPresent       = errors.New("no url present")
	ErrFileLengthMismatch = errors.New("file length does not match")
	ErrInvalidHashLength  = errors.New("hash too short")
	ErrTooShortFile       = errors.New("file too short")
	ErrInvalidMediaHMAC   = errors.New("invalid media hmac")

	ErrCantGetInviteLink = errors.New("you don't have the permission to view the invite link")
	ErrJoinUnauthorized  = errors.New("you're not allowed to join that group")

	ErrInvalidWebsocket = errors.New("invalid websocket")

	ErrWebsocketClosedBeforeLogin = errors.New("connection closed before login finished")

	ErrMessageTypeNotImplemented = errors.New("message type not implemented")
	ErrOptionsNotProvided        = errors.New("new conn options not provided")
)

Functions

func Download

func Download(url string, mediaKey []byte, appInfo MediaType, fileLength int) ([]byte, error)

func GetLiveLocationProto

func GetLiveLocationProto(msg LiveLocationMessage) *proto.WebMessageInfo

func GetLocationProto

func GetLocationProto(msg LocationMessage) *proto.WebMessageInfo

func ParseNodeMessage

func ParseNodeMessage(msg binary.Node) interface{}

func ParseProtoMessage

func ParseProtoMessage(msg *proto.WebMessageInfo) interface{}

Types

type Acknowledgement

type Acknowledgement int
const (
	AckMessageSent      Acknowledgement = 1
	AckMessageDelivered Acknowledgement = 2
	AckMessageRead      Acknowledgement = 3
)

type ArchiveMessage

type ArchiveMessage struct {
	JID        string
	IsArchived bool
}

type AudioMessage

type AudioMessage struct {
	Info    MessageInfo
	Length  uint32
	Type    string
	Content io.Reader
	Ptt     bool

	ContextInfo ContextInfo
	// contains filtered or unexported fields
}

AudioMessage represents a audio message. Unexported fields are needed for media up/downloading and media validation. Provide a io.Reader as Content for message sending.

func (*AudioMessage) Download

func (m *AudioMessage) Download() ([]byte, error)

Download is the function to retrieve media data. The media gets downloaded, validated and returned.

func (AudioMessage) GetInfo

func (m AudioMessage) GetInfo() MessageInfo

type BatteryMessage

type BatteryMessage struct {
	Plugged    bool
	Powersave  bool
	Percentage int
}

BatteryMessage represents a battery level and charging state.

type BroadcastListInfo

type BroadcastListInfo struct {
	Status int16 `json:"status"`

	Name string `json:"name"`

	Recipients []struct {
		JID JID `json:"id"`
	} `json:"recipients"`
}

type CallInfo

type CallInfo struct {
	ID   string       `json:"id"`
	Type CallInfoType `json:"type"`
	From string       `json:"from"`

	Platform string `json:"platform"`
	Version  []int  `json:"version"`

	Data [][]interface{} `json:"data"`
}

type CallInfoType

type CallInfoType string
const (
	CallOffer        CallInfoType = "offer"
	CallOfferVideo   CallInfoType = "offer_video"
	CallTransport    CallInfoType = "transport"
	CallRelayLatency CallInfoType = "relaylatency"
	CallTerminate    CallInfoType = "terminate"
)

type Chat

type Chat struct {
	JID             JID
	Name            string
	ModifyTag       string
	UnreadCount     int
	LastMessageTime int64
	MutedUntil      int64
	IsMarkedSpam    bool
	IsArchived      bool
	IsPinned        bool
	Source          map[string]string
	ReceivedAt      time.Time
}

type ChatActionType

type ChatActionType string
const (
	ChatActionNameChange  ChatActionType = "subject"
	ChatActionAddTopic    ChatActionType = "desc_add"
	ChatActionRemoveTopic ChatActionType = "desc_remove"
	ChatActionRestrict    ChatActionType = "restrict"
	ChatActionAnnounce    ChatActionType = "announce"
	ChatActionPromote     ChatActionType = "promote"
	ChatActionDemote      ChatActionType = "demote"
	ChatActionIntroduce   ChatActionType = "introduce"
	ChatActionCreate      ChatActionType = "create"
	ChatActionRemove      ChatActionType = "remove"
	ChatActionAdd         ChatActionType = "add"
)

type ChatUpdate

type ChatUpdate struct {
	JID     string            `json:"id"`
	Command ChatUpdateCommand `json:"cmd"`
	Data    ChatUpdateData    `json:"data"`
}

type ChatUpdateCommand

type ChatUpdateCommand string
const (
	ChatUpdateCommandAction ChatUpdateCommand = "action"
)

type ChatUpdateData

type ChatUpdateData struct {
	Action    ChatActionType
	SenderJID string

	NameChange struct {
		Name  string `json:"subject"`
		SetAt int64  `json:"s_t"`
		SetBy string `json:"s_o"`
	}

	AddTopic struct {
		Topic string `json:"desc"`
		ID    string `json:"descId"`
		SetAt int64  `json:"descTime"`
		SetBy string `json:"descOwner"`
	}

	RemoveTopic struct {
		ID string `json:"descId"`
	}

	Introduce struct {
		CreationTime int64    `json:"creation"`
		Admins       []string `json:"admins"`
		SuperAdmins  []string `json:"superadmins"`
		Regulars     []string `json:"regulars"`
	}

	Restrict bool

	Announce bool

	UserChange struct {
		JIDs []string `json:"participants"`
	}
}

func (*ChatUpdateData) UnmarshalJSON

func (cud *ChatUpdateData) UnmarshalJSON(data []byte) error

type CommandType

type CommandType string
const (
	CommandPicture    CommandType = "picture"
	CommandDisconnect CommandType = "disconnect"
	CommandChallenge  CommandType = "challenge"
)

type Conn

type Conn struct {
	Store          *Store
	ServerLastSeen time.Time

	Proxy func(*http.Request) (*url.URL, error)

	CountTimeoutHook func(wsKeepaliveErrorCount int)
	AdminTestHook    func(err error)
	// contains filtered or unexported fields
}

Conn is created by NewConn. Interacting with the initialized Conn is the main way of interacting with our package. It holds all necessary information to make the package work internally.

func NewConn

func NewConn(opt *Options) *Conn

func (*Conn) AddHandler

func (wac *Conn) AddHandler(handler Handler)

AddHandler adds an handler to the list of handler that receive dispatched messages. The provided handler must at least implement the Handler interface. Additionally implemented handlers(TextMessageHandler, ImageMessageHandler) are optional. At runtime it is checked if they are implemented and they are called if so and needed.

func (*Conn) AddMember

func (wac *Conn) AddMember(jid JID, participants []string) (<-chan string, error)

func (*Conn) AdminTest

func (wac *Conn) AdminTest() error

func (*Conn) AdminTestWithSuppress

func (wac *Conn) AdminTestWithSuppress(suppressHook bool) error

func (*Conn) BlockContact

func (wac *Conn) BlockContact(jid JID) (<-chan string, error)

func (*Conn) Chats

func (wac *Conn) Chats() (*binary.Node, error)

func (*Conn) Contacts

func (wac *Conn) Contacts() (*binary.Node, error)

func (*Conn) CountTimeout

func (wac *Conn) CountTimeout()

func (*Conn) CreateGroup

func (wac *Conn) CreateGroup(subject string, participants []JID) (*CreateGroupResponse, error)

func (*Conn) DeleteMessage

func (wac *Conn) DeleteMessage(chatJID JID, msgID MessageID, fromMe bool) error

DeleteMessage deletes a single message for the user (removes the msgbox). To delete the message for everyone, use RevokeMessage

func (*Conn) Disconnect

func (wac *Conn) Disconnect() error

func (*Conn) Emoji

func (wac *Conn) Emoji() (*binary.Node, error)

func (*Conn) Exist

func (wac *Conn) Exist(jid string) (<-chan string, error)

func (*Conn) GetBroadcastMetadata

func (wac *Conn) GetBroadcastMetadata(jid JID) (*BroadcastListInfo, error)

func (*Conn) GetClientVersion

func (wac *Conn) GetClientVersion() []int

GetClientVersion returns WhatsApp client version

func (*Conn) GetGroupMetaData

func (wac *Conn) GetGroupMetaData(jid JID) (*GroupInfo, error)

func (*Conn) GetProfilePicThumb

func (wac *Conn) GetProfilePicThumb(jid string) (*ProfilePicInfo, error)

func (*Conn) GetStatus

func (wac *Conn) GetStatus(jid string) (<-chan string, error)

func (*Conn) GroupAcceptInviteCode

func (wac *Conn) GroupAcceptInviteCode(code string) (jid string, err error)
func (wac *Conn) GroupInviteLink(jid string) (string, error)

func (*Conn) IsConnected

func (wac *Conn) IsConnected() bool

IsConnected returns whether the server connection is established or not

func (*Conn) IsLoggedIn

func (wac *Conn) IsLoggedIn() bool

IsLoggedIn returns whether the you are logged in or not

func (*Conn) IsLoginInProgress

func (wac *Conn) IsLoginInProgress() bool

func (*Conn) LeaveGroup

func (wac *Conn) LeaveGroup(jid JID) (<-chan string, error)

func (*Conn) LoadMediaInfo

func (wac *Conn) LoadMediaInfo(jid, messageId string, fromMe bool) (*binary.Node, error)

func (*Conn) LoadMessages

func (wac *Conn) LoadMessages(jid string, count int) (*binary.Node, error)

func (*Conn) LoadMessagesAfter

func (wac *Conn) LoadMessagesAfter(jid, messageId string, fromMe bool, count int) (*binary.Node, error)

func (*Conn) LoadMessagesBefore

func (wac *Conn) LoadMessagesBefore(jid, messageId string, fromMe bool, count int) (*binary.Node, error)

func (*Conn) Login

func (wac *Conn) Login(qrChan chan<- string, ctx context.Context) (Session, JID, error)

func (*Conn) Logout

func (wac *Conn) Logout() error

Logout is the function to logout from a WhatsApp session. Logging out means invalidating the current session. The session can not be resumed and will disappear on your phone in the WhatsAppWeb client list.

func (*Conn) Presence

func (wac *Conn) Presence(jid string, presence Presence) (<-chan string, error)

func (*Conn) Read

func (wac *Conn) Read(jid JID, id MessageID) (<-chan string, error)

func (*Conn) RemoveAdmin

func (wac *Conn) RemoveAdmin(jid JID, participants []string) (<-chan string, error)

func (*Conn) RemoveHandler

func (wac *Conn) RemoveHandler(handler Handler) bool

RemoveHandler removes a handler from the list of handlers that receive dispatched messages.

func (*Conn) RemoveHandlers

func (wac *Conn) RemoveHandlers()

RemoveHandlers empties the list of handlers that receive dispatched messages.

func (*Conn) RemoveMember

func (wac *Conn) RemoveMember(jid JID, participants []string) (<-chan string, error)

func (*Conn) Restore

func (wac *Conn) Restore(takeover bool, ctx context.Context) error

func (*Conn) Search

func (wac *Conn) Search(search string, count, page int) (*binary.Node, error)

func (*Conn) SendRaw

func (wac *Conn) SendRaw(msg *proto.WebMessageInfo, output chan<- error)

func (*Conn) SetAdmin

func (wac *Conn) SetAdmin(jid JID, participants []string) (<-chan string, error)

func (*Conn) SetClientName

func (wac *Conn) SetClientName(long, short, version string) error

SetClientName sets the long and short client names that are sent to WhatsApp when logging in and displayed in the WhatsApp Web device list. As the values are only sent when logging in, changing them after logging in is not possible.

func (*Conn) SetClientVersion

func (wac *Conn) SetClientVersion(major int, minor int, patch int)

SetClientVersion sets WhatsApp client version Default value is 0.4.2080

func (*Conn) SetSession

func (wac *Conn) SetSession(session Session)

func (*Conn) SubscribePresence

func (wac *Conn) SubscribePresence(jid string) (<-chan string, error)

func (*Conn) UnblockContact

func (wac *Conn) UnblockContact(jid JID) (<-chan string, error)

func (*Conn) UpdateGroupDescription

func (wac *Conn) UpdateGroupDescription(ownJID, groupJID JID, description string) (<-chan string, error)

func (*Conn) UpdateGroupSubject

func (wac *Conn) UpdateGroupSubject(subject string, jid JID) (<-chan string, error)

func (*Conn) Upload

func (wac *Conn) Upload(reader io.Reader, appInfo MediaType) (downloadURL string, mediaKey, fileEncSha256, fileSha256 []byte, fileLength uint64, err error)

func (*Conn) UploadProfilePic

func (wac *Conn) UploadProfilePic(ownJID JID, image, preview []byte) (<-chan string, error)

Pictures must be JPG 640x640 and 96x96, respectively

func (*Conn) WaitForLogin

func (wac *Conn) WaitForLogin()

type ConnInfo

type ConnInfo struct {
	// This is the only field that's always present
	PushName string `json:"pushname"`

	ProtocolVersion []int `json:"protoVersion"`
	BinaryVersion   int   `json:"binVersion"`
	Phone           struct {
		WhatsAppVersion    string `json:"wa_version"`
		MCC                string `json:"mcc"`
		MNC                string `json:"mnc"`
		OSVersion          string `json:"os_version"`
		DeviceManufacturer string `json:"device_manufacturer"`
		DeviceModel        string `json:"device_model"`
		OSBuildNumber      string `json:"os_build_number"`
	} `json:"phone"`
	Features map[string]interface{} `json:"features"`

	// Fields below are only sent right after connection
	Reference  string `json:"ref"`
	WID        JID    `json:"wid"`
	TOS        int    `json:"tos"`
	Connected  bool   `json:"connected"`
	IsResponse string `json:"isResponse"`

	ServerToken  string `json:"serverToken"`
	BrowserToken string `json:"browserToken"`
	ClientToken  string `json:"clientToken"`

	Locale   string `json:"locale"`
	Language string `json:"language"`
	Locales  string `json:"locales"`
	Is24h    bool   `json:"is24h"`

	Plugged  bool   `json:"plugged"`
	Battery  int    `json:"battery"`
	Platform string `json:"platform"`

	// Only present right after initial login
	Secret string `json:"secret"`
}

type Contact

type Contact struct {
	JID    JID
	Notify string
	Name   string
	Short  string
}

type ContactMessage

type ContactMessage struct {
	Info MessageInfo

	DisplayName string
	Vcard       string

	ContextInfo ContextInfo
}

ContactMessage represents a contact message.

func (ContactMessage) GetInfo

func (m ContactMessage) GetInfo() MessageInfo

type ContextInfo

type ContextInfo struct {
	QuotedMessageID string //StanzaId
	QuotedMessage   *proto.Message
	Participant     string
	IsForwarded     bool
	MentionedJID    []string
}

ContextInfo represents contextinfo of every message

type CreateGroupResponse

type CreateGroupResponse struct {
	Status       int `json:"status"`
	GroupID      JID `json:"gid"`
	Participants map[JID]struct {
		Code string `json:"code"`
	} `json:"participants"`

	Source string `json:"-"`
}

type DocumentMessage

type DocumentMessage struct {
	Info      MessageInfo
	Title     string
	PageCount uint32
	Type      string
	FileName  string
	Thumbnail []byte
	Content   io.Reader

	ContextInfo ContextInfo
	// contains filtered or unexported fields
}

DocumentMessage represents a document message. Unexported fields are needed for media up/downloading and media validation. Provide a io.Reader as Content for message sending.

func (*DocumentMessage) Download

func (m *DocumentMessage) Download() ([]byte, error)

Download is the function to retrieve media data. The media gets downloaded, validated and returned.

func (DocumentMessage) GetInfo

func (m DocumentMessage) GetInfo() MessageInfo

type ErrConnectionClosed

type ErrConnectionClosed struct {
	Code int
	Text string
}

func (*ErrConnectionClosed) Error

func (e *ErrConnectionClosed) Error() string

type ErrConnectionFailed

type ErrConnectionFailed struct {
	Err error
}

func (*ErrConnectionFailed) Error

func (e *ErrConnectionFailed) Error() string

type GroupInfo

type GroupInfo struct {
	JID      JID `json:"jid"`
	OwnerJID JID `json:"owner"`

	Name        string `json:"subject"`
	NameSetTime int64  `json:"subjectTime"`
	NameSetBy   JID    `json:"subjectOwner"`

	Announce bool `json:"announce"` // Can only admins send messages?

	Topic      string `json:"desc"`
	TopicID    string `json:"descId"`
	TopicSetAt int64  `json:"descTime"`
	TopicSetBy JID    `json:"descOwner"`

	GroupCreated int64 `json:"creation"`

	Status int16 `json:"status"`

	Participants []struct {
		JID          JID  `json:"id"`
		IsAdmin      bool `json:"isAdmin"`
		IsSuperAdmin bool `json:"isSuperAdmin"`
	} `json:"participants"`
}

type Handler

type Handler interface {
	HandleEvent(event interface{})
}

The Handler interface is the minimal interface that needs to be implemented to be accepted as a valid handler for our dispatching system. The minimal handler is used to dispatch error messages. These errors occur on unexpected behavior by the websocket connection or if we are unable to handle or interpret an incoming message. Error produced by user actions are not dispatched through this handler. They are returned as an error on the specific function call.

type ImageMessage

type ImageMessage struct {
	Info      MessageInfo
	Caption   string
	Thumbnail []byte
	Type      string
	Content   io.Reader

	ContextInfo ContextInfo
	// contains filtered or unexported fields
}

ImageMessage represents a image message. Unexported fields are needed for media up/downloading and media validation. Provide a io.Reader as Content for message sending.

func (*ImageMessage) Download

func (m *ImageMessage) Download() ([]byte, error)

Download is the function to retrieve media data. The media gets downloaded, validated and returned.

func (ImageMessage) GetInfo

func (m ImageMessage) GetInfo() MessageInfo

type JID

type JID = string

JID is a WhatsApp user or group ID.

type JSONCommand

type JSONCommand struct {
	Type CommandType `json:"type"`
	JID  string      `json:"jid"`

	Challenge string `json:"challenge"`

	*ProfilePicInfo
	Kind string `json:"kind"`

	Raw json.RawMessage `json:"-"`
}

type JSONMessage

type JSONMessage []json.RawMessage

type JSONMessageType

type JSONMessageType string
const (
	MessageMsgInfo  JSONMessageType = "MsgInfo"
	MessageMsg      JSONMessageType = "Msg"
	MessagePresence JSONMessageType = "Presence"
	MessageStream   JSONMessageType = "Stream"
	MessageConn     JSONMessageType = "Conn"
	MessageProps    JSONMessageType = "Props"
	MessageCmd      JSONMessageType = "Cmd"
	MessageChat     JSONMessageType = "Chat"
	MessageCall     JSONMessageType = "Call"
)

type JSONMsgInfo

type JSONMsgInfo struct {
	Command         MsgInfoCommand    `json:"cmd"`
	IDs             JSONStringOrArray `json:"id"`
	Acknowledgement Acknowledgement   `json:"ack"`
	MessageFromJID  string            `json:"from"`
	SenderJID       string            `json:"participant"`
	ToJID           string            `json:"to"`
	Timestamp       int64             `json:"t"`
}

type JSONStringOrArray

type JSONStringOrArray []string

func (*JSONStringOrArray) UnmarshalJSON

func (jsoa *JSONStringOrArray) UnmarshalJSON(data []byte) error

type LiveLocationMessage

type LiveLocationMessage struct {
	Info                              MessageInfo
	DegreesLatitude                   float64
	DegreesLongitude                  float64
	AccuracyInMeters                  uint32
	SpeedInMps                        float32
	DegreesClockwiseFromMagneticNorth uint32
	Caption                           string
	SequenceNumber                    int64
	JpegThumbnail                     []byte
	ContextInfo                       ContextInfo
}

LiveLocationMessage represents a live location message

func GetLiveLocationMessage

func GetLiveLocationMessage(msg *proto.WebMessageInfo) LiveLocationMessage

func (LiveLocationMessage) GetInfo

func (m LiveLocationMessage) GetInfo() MessageInfo

type LocationMessage

type LocationMessage struct {
	Info             MessageInfo
	DegreesLatitude  float64
	DegreesLongitude float64
	Name             string
	Address          string
	Url              string
	JpegThumbnail    []byte
	ContextInfo      ContextInfo
}

LocationMessage represents a location message

func GetLocationMessage

func GetLocationMessage(msg *proto.WebMessageInfo) LocationMessage

func (LocationMessage) GetInfo

func (m LocationMessage) GetInfo() MessageInfo

type MediaConn

type MediaConn struct {
	Status    int `json:"status"`
	MediaConn struct {
		Auth  string `json:"auth"`
		TTL   int    `json:"ttl"`
		Hosts []struct {
			Hostname string `json:"hostname"`
			IPs      []struct {
				IP4 net.IP `json:"ip4"`
				IP6 net.IP `json:"ip6"`
			} `json:"ips"`
		} `json:"hosts"`
	} `json:"media_conn"`
}

type MediaType

type MediaType string
const (
	MediaImage    MediaType = "WhatsApp Image Keys"
	MediaVideo    MediaType = "WhatsApp Video Keys"
	MediaAudio    MediaType = "WhatsApp Audio Keys"
	MediaDocument MediaType = "WhatsApp Document Keys"
)

type MessageID

type MessageID = string

MessageID is the internal ID of a WhatsApp message.

type MessageInfo

type MessageInfo struct {
	Id        string
	RemoteJid string
	SenderJid string
	FromMe    bool
	Timestamp uint64
	PushName  string
	Status    MessageStatus

	Source *proto.WebMessageInfo
}

MessageInfo contains general message information. It is part of every of every message type.

type MessageRevocation

type MessageRevocation struct {
	Id          string
	RemoteJid   string
	FromMe      bool
	Participant string
}

type MessageStatus

type MessageStatus int

type MsgInfoCommand

type MsgInfoCommand string
const (
	MsgInfoCommandAck  MsgInfoCommand = "ack"
	MsgInfoCommandAcks MsgInfoCommand = "acks"
)

type MuteMessage

type MuteMessage struct {
	JID        string
	MutedUntil int64
}

type Options

type Options struct {
	Proxy           func(*http.Request) (*url.URL, error)
	Timeout         time.Duration
	Handler         []Handler
	ShortClientName string
	LongClientName  string
	ClientVersion   string
	Store           *Store
	Log             log.Logger
}

type PinMessage

type PinMessage struct {
	JID      string
	IsPinned bool
}

type Presence

type Presence string
const (
	PresenceAvailable   Presence = "available"
	PresenceUnavailable Presence = "unavailable"
	PresenceComposing   Presence = "composing"
	PresenceRecording   Presence = "recording"
	PresencePaused      Presence = "paused"
)

type PresenceEvent

type PresenceEvent struct {
	JID       string   `json:"id"`
	SenderJID string   `json:"participant"`
	Status    Presence `json:"type"`
	Timestamp int64    `json:"t"`
	Deny      bool     `json:"deny"`
}

type ProfilePicInfo

type ProfilePicInfo struct {
	URL string `json:"eurl"`
	Tag string `json:"tag"`

	Status int `json:"status"`
}

func (*ProfilePicInfo) Download

func (ppi *ProfilePicInfo) Download() (io.ReadCloser, error)

func (*ProfilePicInfo) DownloadBytes

func (ppi *ProfilePicInfo) DownloadBytes() ([]byte, error)

type ProtocolProps

type ProtocolProps struct {
	WebPresence            bool   `json:"webPresence"`
	NotificationQuery      bool   `json:"notificationQuery"`
	FacebookCrashLog       bool   `json:"fbCrashlog"`
	Bucket                 string `json:"bucket"`
	GIFSearch              string `json:"gifSearch"`
	Spam                   bool   `json:"SPAM"`
	SetBlock               bool   `json:"SET_BLOCK"`
	MessageInfo            bool   `json:"MESSAGE_INFO"`
	MaxFileSize            int    `json:"maxFileSize"`
	Media                  int    `json:"media"`
	GroupNameLength        int    `json:"maxSubject"`
	GroupDescriptionLength int    `json:"groupDescLength"`
	MaxParticipants        int    `json:"maxParticipants"`
	VideoMaxEdge           int    `json:"videoMaxEdge"`
	ImageMaxEdge           int    `json:"imageMaxEdge"`
	ImageMaxKilobytes      int    `json:"imageMaxKBytes"`
	Edit                   int    `json:"edit"`
	FwdUIStartTimestamp    int    `json:"fwdUiStartTs"`
	GroupsV3               int    `json:"groupsV3"`
	RestrictGroups         int    `json:"restrictGroups"`
	AnnounceGroups         int    `json:"announceGroups"`
}

type RawJSONMessage

type RawJSONMessage struct {
	json.RawMessage
	Tag string
}

type ReadMessage

type ReadMessage struct {
	Jid string
}

ReadMessage represents a chat that the user read on the WhatsApp mobile app.

type ReceivedMessage

type ReceivedMessage struct {
	Index       string
	Jid         string
	Owner       bool
	Participant string
	Type        string
}

ReceivedMessage probably represents a message that the user read on the WhatsApp mobile app.

type ResendFunc

type ResendFunc func() error

type Session

type Session struct {
	ClientID    string
	ClientToken string
	ServerToken string
	EncKey      []byte
	MacKey      []byte
	Wid         string
}

Session contains session individual information. To be able to resume the connection without scanning the qr code every time you should save the Session returned by Login and use RestoreWithSession the next time you want to login. Every successful created connection returns a new Session. The Session(ClientToken, ServerToken) is altered after every re-login and should be saved every time.

type StatusResponse

type StatusResponse struct {
	StatusResponseFields
	RequestType string                 `json:"-"`
	Extra       map[string]interface{} `json:"-"`
}

func (StatusResponse) Error

func (sr StatusResponse) Error() string

func (*StatusResponse) UnmarshalJSON

func (sr *StatusResponse) UnmarshalJSON(data []byte) error

type StatusResponseFields

type StatusResponseFields struct {
	// The response status code. This is always expected to be present.
	Status int `json:"status"`
	// Some error messages include a "tos" value. If it's higher than 0, it
	// might mean the user has been banned for breaking the terms of service.
	TermsOfService int `json:"tos,omitempty"`
	// This is a timestamp that's at least present in message send responses.
	Timestamp int64 `json:"t,omitempty"`
}

type StickerMessage

type StickerMessage struct {
	Info MessageInfo

	Type    string
	Content io.Reader

	ContextInfo ContextInfo
	// contains filtered or unexported fields
}

StickerMessage represents a sticker message.

func (*StickerMessage) Download

func (m *StickerMessage) Download() ([]byte, error)

func (StickerMessage) GetInfo

func (m StickerMessage) GetInfo() MessageInfo

type Store

type Store struct {
	Contacts     map[JID]Contact
	ContactsLock sync.RWMutex
	Chats        map[JID]Chat
	ChatsLock    sync.RWMutex
}

type StreamEvent

type StreamEvent struct {
	Type StreamType

	IsOutdated bool
	Version    string

	Extra []json.RawMessage
}

type StreamType

type StreamType string

type StubMessage

type StubMessage struct {
	Info       MessageInfo
	Type       proto.WebMessageInfo_WebMessageInfoStubType
	Params     []string
	FirstParam string
}

func (StubMessage) GetInfo

func (m StubMessage) GetInfo() MessageInfo

type TextMessage

type TextMessage struct {
	Info        MessageInfo
	Text        string
	ContextInfo ContextInfo
}

TextMessage represents a text message.

func (TextMessage) GetInfo

func (m TextMessage) GetInfo() MessageInfo

type VideoMessage

type VideoMessage struct {
	Info        MessageInfo
	Caption     string
	Thumbnail   []byte
	Length      uint32
	Type        string
	Content     io.Reader
	GifPlayback bool

	ContextInfo ContextInfo
	// contains filtered or unexported fields
}

VideoMessage represents a video message. Unexported fields are needed for media up/downloading and media validation. Provide a io.Reader as Content for message sending.

func (*VideoMessage) Download

func (m *VideoMessage) Download() ([]byte, error)

Download is the function to retrieve media data. The media gets downloaded, validated and returned.

func (VideoMessage) GetInfo

func (m VideoMessage) GetInfo() MessageInfo

Directories

Path Synopsis
crypto package contains cryptographic functions and servers as a support package for github.com/Rhymen/go-whatsapp.
crypto package contains cryptographic functions and servers as a support package for github.com/Rhymen/go-whatsapp.
cbc
CBC describes a block cipher mode.
CBC describes a block cipher mode.
curve25519
In cryptography, Curve25519 is an elliptic curve offering 128 bits of security and designed for use with the elliptic curve Diffie–Hellman (ECDH) key agreement scheme.
In cryptography, Curve25519 is an elliptic curve offering 128 bits of security and designed for use with the elliptic curve Diffie–Hellman (ECDH) key agreement scheme.
hkdf
HKDF is a simple key derivation function (KDF) based on a hash-based message authentication code (HMAC).
HKDF is a simple key derivation function (KDF) based on a hash-based message authentication code (HMAC).

Jump to

Keyboard shortcuts

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