(apiId int, apiHash string)
| 49 | } |
| 50 | |
| 51 | func GenerateQRSession(apiId int, apiHash string) error { |
| 52 | ctx, cancel := context.WithCancel(context.Background()) |
| 53 | defer cancel() |
| 54 | fmt.Println("Generating QR session...") |
| 55 | reader := bufio.NewReader(os.Stdin) |
| 56 | dispatcher := tg.NewUpdateDispatcher() |
| 57 | loggedIn := qrlogin.OnLoginToken(dispatcher) |
| 58 | sessionStorage := &session.StorageMemory{} |
| 59 | client := telegram.NewClient(apiId, apiHash, telegram.Options{ |
| 60 | UpdateHandler: dispatcher, |
| 61 | SessionStorage: sessionStorage, |
| 62 | Device: telegram.DeviceConfig{ |
| 63 | DeviceModel: "Pyrogram", |
| 64 | SystemVersion: runtime.GOOS, |
| 65 | AppVersion: "2.0", |
| 66 | }, |
| 67 | }) |
| 68 | var stringSession string |
| 69 | qrWriter := &CustomWriter{} |
| 70 | tickerCtx, cancelTicker := context.WithCancel(context.Background()) |
| 71 | err := client.Run(ctx, func(ctx context.Context) error { |
| 72 | authorization, err := client.QR().Auth(ctx, loggedIn, func(ctx context.Context, token qrlogin.Token) error { |
| 73 | if qrWriter.LineLength == 0 { |
| 74 | fmt.Printf("\033[F\033[K") |
| 75 | } |
| 76 | clearQrCode(qrWriter) |
| 77 | printQrCode(token.URL(), qrWriter) |
| 78 | qrWriter.Write([]byte("\nTo log in, Open your Telegram app and go to Settings > Devices > Scan QR and scan the QR code.\n")) |
| 79 | go func(ctx context.Context) { |
| 80 | ticker := time.NewTicker(1 * time.Second) |
| 81 | defer ticker.Stop() |
| 82 | for { |
| 83 | select { |
| 84 | case <-ctx.Done(): |
| 85 | return |
| 86 | case <-ticker.C: |
| 87 | expiresIn := time.Until(token.Expires()) |
| 88 | if expiresIn <= 0 { |
| 89 | return |
| 90 | } |
| 91 | fmt.Printf("\rThis code expires in %s", expiresIn.Truncate(time.Second)) |
| 92 | } |
| 93 | } |
| 94 | }(tickerCtx) |
| 95 | return nil |
| 96 | }) |
| 97 | if err != nil { |
| 98 | if tgerr.Is(err, "SESSION_PASSWORD_NEEDED") { |
| 99 | cancelTicker() |
| 100 | fmt.Println("\n2FA password is required, enter it below: ") |
| 101 | passkey, _ := reader.ReadString('\n') |
| 102 | strippedPasskey := strings.TrimSpace(passkey) |
| 103 | authorization, err = client.Auth().Password(ctx, strippedPasskey) |
| 104 | if err != nil { |
| 105 | if err.Error() == "invalid password" { |
| 106 | fmt.Println("Invalid password, please try again.") |
| 107 | } |
| 108 | fmt.Println("Error while logging in: ", err) |
no test coverage detected