forked from Rhymen/go-whatsapp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
77 lines (71 loc) · 1.59 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main
import (
"encoding/gob"
"fmt"
"github.com/Baozisoftware/qrcode-terminal-go"
"github.com/linzy/go-whatsapp"
"os"
"time"
)
func main() {
//create new WhatsApp connection
wac, err := whatsapp.NewConn(5 * time.Second)
if err != nil {
fmt.Fprintf(os.Stderr, "error creating connection: %v\n", err)
return
}
//load saved session
session, err := readSession()
if err == nil {
//restore session
session, err = wac.RestoreWithSession(session)
if err != nil {
fmt.Fprintf(os.Stderr, "restoring failed: %v\n", err)
return
}
} else {
//no saved session -> regular login
qr := make(chan string)
go func() {
terminal := qrcodeTerminal.New()
terminal.Get(<-qr).Print()
}()
session, err = wac.Login(qr)
if err != nil {
fmt.Fprintf(os.Stderr, "error during login: %v\n", err)
}
}
//save session
err = writeSession(session)
if err != nil {
fmt.Fprintf(os.Stderr, "error saving session: %v\n", err)
}
fmt.Printf("login successful, session: %v\n", session)
}
func readSession() (whatsapp.Session, error) {
session := whatsapp.Session{}
file, err := os.Open(os.TempDir() + "/whatsappSession.gob")
if err != nil {
return session, err
}
defer file.Close()
decoder := gob.NewDecoder(file)
err = decoder.Decode(&session)
if err != nil {
return session, err
}
return session, nil
}
func writeSession(session whatsapp.Session) error {
file, err := os.Create(os.TempDir() + "/whatsappSession.gob")
if err != nil {
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(session)
if err != nil {
return err
}
return nil
}