| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- // Copyright (c) 2021 Tulir Asokan
- //
- // This Source Code Form is subject to the terms of the Mozilla Public
- // License, v. 2.0. If a copy of the MPL was not distributed with this
- // file, You can obtain one at http://mozilla.org/MPL/2.0/.
- package whatsmeow_test
- import (
- "context"
- "fmt"
- "os"
- "os/signal"
- "syscall"
- "git.bobomao.top/joey/testwh"
- "git.bobomao.top/joey/testwh/store/sqlstore"
- "git.bobomao.top/joey/testwh/types/events"
- waLog "git.bobomao.top/joey/testwh/util/log"
- )
- func eventHandler(evt interface{}) {
- switch v := evt.(type) {
- case *events.Message:
- fmt.Println("Received a message!", v.Message.GetConversation())
- }
- }
- func Example() {
- // |------------------------------------------------------------------------------------------------------|
- // | NOTE: You must also import the appropriate DB connector, e.g. github.com/mattn/go-sqlite3 for SQLite |
- // |------------------------------------------------------------------------------------------------------|
- dbLog := waLog.Stdout("Database", "DEBUG", true)
- ctx := context.Background()
- container, err := sqlstore.New(ctx, "sqlite3", "file:examplestore.db?_foreign_keys=on", dbLog)
- if err != nil {
- panic(err)
- }
- // If you want multiple sessions, remember their JIDs and use .GetDevice(jid) or .GetAllDevices() instead.
- deviceStore, err := container.GetFirstDevice(ctx)
- if err != nil {
- panic(err)
- }
- clientLog := waLog.Stdout("Client", "DEBUG", true)
- client := whatsmeow.NewClient(deviceStore, clientLog)
- client.AddEventHandler(eventHandler)
- if client.Store.ID == nil {
- // No ID stored, new login
- qrChan, _ := client.GetQRChannel(context.Background())
- err = client.Connect()
- if err != nil {
- panic(err)
- }
- for evt := range qrChan {
- if evt.Event == "code" {
- // Render the QR code here
- // e.g. qrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)
- // or just manually `echo 2@... | qrencode -t ansiutf8` in a terminal
- fmt.Println("QR code:", evt.Code)
- } else {
- fmt.Println("Login event:", evt.Event)
- }
- }
- } else {
- // Already logged in, just connect
- err = client.Connect()
- if err != nil {
- panic(err)
- }
- }
- // Listen to Ctrl+C (you can also do something else that prevents the program from exiting)
- c := make(chan os.Signal, 1)
- signal.Notify(c, os.Interrupt, syscall.SIGTERM)
- <-c
- client.Disconnect()
- }
|