client_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright (c) 2021 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package whatsmeow_test
  7. import (
  8. "context"
  9. "fmt"
  10. "os"
  11. "os/signal"
  12. "syscall"
  13. "git.bobomao.top/joey/testwh"
  14. "git.bobomao.top/joey/testwh/store/sqlstore"
  15. "git.bobomao.top/joey/testwh/types/events"
  16. waLog "git.bobomao.top/joey/testwh/util/log"
  17. )
  18. func eventHandler(evt interface{}) {
  19. switch v := evt.(type) {
  20. case *events.Message:
  21. fmt.Println("Received a message!", v.Message.GetConversation())
  22. }
  23. }
  24. func Example() {
  25. // |------------------------------------------------------------------------------------------------------|
  26. // | NOTE: You must also import the appropriate DB connector, e.g. github.com/mattn/go-sqlite3 for SQLite |
  27. // |------------------------------------------------------------------------------------------------------|
  28. dbLog := waLog.Stdout("Database", "DEBUG", true)
  29. ctx := context.Background()
  30. container, err := sqlstore.New(ctx, "sqlite3", "file:examplestore.db?_foreign_keys=on", dbLog)
  31. if err != nil {
  32. panic(err)
  33. }
  34. // If you want multiple sessions, remember their JIDs and use .GetDevice(jid) or .GetAllDevices() instead.
  35. deviceStore, err := container.GetFirstDevice(ctx)
  36. if err != nil {
  37. panic(err)
  38. }
  39. clientLog := waLog.Stdout("Client", "DEBUG", true)
  40. client := whatsmeow.NewClient(deviceStore, clientLog)
  41. client.AddEventHandler(eventHandler)
  42. if client.Store.ID == nil {
  43. // No ID stored, new login
  44. qrChan, _ := client.GetQRChannel(context.Background())
  45. err = client.Connect()
  46. if err != nil {
  47. panic(err)
  48. }
  49. for evt := range qrChan {
  50. if evt.Event == "code" {
  51. // Render the QR code here
  52. // e.g. qrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)
  53. // or just manually `echo 2@... | qrencode -t ansiutf8` in a terminal
  54. fmt.Println("QR code:", evt.Code)
  55. } else {
  56. fmt.Println("Login event:", evt.Event)
  57. }
  58. }
  59. } else {
  60. // Already logged in, just connect
  61. err = client.Connect()
  62. if err != nil {
  63. panic(err)
  64. }
  65. }
  66. // Listen to Ctrl+C (you can also do something else that prevents the program from exiting)
  67. c := make(chan os.Signal, 1)
  68. signal.Notify(c, os.Interrupt, syscall.SIGTERM)
  69. <-c
  70. client.Disconnect()
  71. }