Ejemplo n.º 1
0
        public async Task <bool> Auth()
        {
            var client = new TelegramClient(apiId, apiHash, dcIpVersion: DataCenterIPVersion.OnlyIPv4);
            await client.ConnectAsync();

            var hash = await client.SendCodeRequestAsync(phone);

            Console.WriteLine("Code: ");
            var code = Console.ReadLine();
            var user = await client.MakeAuthAsync(phone, hash, code);

            this.Client = client;

            this.IsAuthenticated = true;
            return(true);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var client = new TelegramClient(apiId, apiHash);

            client.ConnectAsync();

            var hash = client.SendCodeRequestAsync(number);
            var code = "23799"; // you can change code in debugger
            var user = client.MakeAuthAsync(number, apiHash, code);

            client.SendMessageAsync(new TLInputPeerUser()
            {
                UserId = groupId
            }, "TEST");
            Console.ReadKey();
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            DotNetEnv.Env.Load();

            telegram = new TelegramClient(GetEnvInt("TELEGRAM_API_ID"), Environment.GetEnvironmentVariable("TELEGRAM_API_HASH"));
            telegram.ConnectAsync().Wait();

            if (telegram.IsUserAuthorized())
            {
                Connect();
            }
            else
            {
                LogIn().Wait();
            }
        }
Ejemplo n.º 4
0
        private async void btnGetCode_Click(object sender, EventArgs e)
        {
            txtPhone.Enabled = false;
            _client          = new TelegramClient(ApiId, ApiHash);
            await _client.ConnectAsync();

            _phone = txtPhone.Text;
            if (!_phone.StartsWith("+"))
            {
                _phone = "+" + _phone;
            }
            _hash = await _client.SendCodeRequestAsync(_phone);

            btnRegister.Enabled = true;
            btnGetCode.Enabled  = false;
        }
Ejemplo n.º 5
0
        /* Send authorization code request to Telegram */
        private async void EstablishTelegramConnection()
        {
            try
            {
                this.client = new TelegramClient(API_ID, API_HASH);
                await client.ConnectAsync();

                this.hash = await client.SendCodeRequestAsync(userNumber);

                // enable controls to enter received code
                code_tb.Enabled          = true;
                authenticate_btn.Enabled = true;
            } catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 6
0
        static async Task Connect(TelegramClient client)
        {
            if (!client.IsUserAuthorized())
            {
                await ConnectAsync(client);

                Console.WriteLine("connected");
            }
            else
            {
                Console.WriteLine("User authorized = " + client.IsUserAuthorized());
                await client.ConnectAsync(false);

                UserId = client.Session.TLUser.Id;
                Console.WriteLine("connected");
            }
        }
Ejemplo n.º 7
0
        public IAuthResult Auth(string session)
        {
            log.Info("Establishing TCP connection...");
            client = new TelegramClient(apiId, apiHash, sessionStore, session, null);
            log.Info("Authenticating Consolegram...");
            client.ConnectAsync().Wait();

            if (client.IsUserAuthorized())
            {
                return(new TLAuthResult());
            }

            log.Info("Sending code...");
            var hash = client.SendCodeRequestAsync(session).Result;

            return(new TLAuthResult(client, hash, session));
        }
Ejemplo n.º 8
0
        public async System.Threading.Tasks.Task AuthAsync()
        {
            var store   = new FileSessionStore();
            var apiId   = 434408;
            var apiHash = "0bdea67547ee00f2e164a5522174d7dc";
            var client  = new TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            if (client.IsUserAuthorized() == false)
            {
                var phone = metroComboBox1.Text + metroTextBox1.Text;
                var hash  = await client.SendCodeRequestAsync(phone);

                var code = Microsoft.VisualBasic.Interaction.InputBox("Введите код полученый в СМС:");
                var user = await client.MakeAuthAsync(phone, hash, code);

                var    photo         = ((TLUserProfilePhoto)user.Photo);
                var    photoLocation = (TLFileLocation)photo.PhotoBig;
                TLFile file          = await client.GetFile(new TLInputFileLocation()
                {
                    LocalId  = photoLocation.LocalId,
                    Secret   = photoLocation.Secret,
                    VolumeId = photoLocation.VolumeId
                }, 1024 * 256);

                using (var m = new MemoryStream(file.Bytes))
                {
                    var img = Image.FromStream(m);
                    img.Save("profileimg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                var rq = new TeleSharp.TL.Users.TLRequestGetFullUser {
                    Id = new TLInputUserSelf()
                };
                TLUserFull rUserSelf = await client.SendRequestAsync <TeleSharp.TL.TLUserFull>(rq);

                TLUser userSelf = (TLUser)rUserSelf.User;
                Properties.Settings.Default.Name = userSelf.Username;
                Properties.Settings.Default.Save();

                this.Hide();
                Main main = new Main();
                main.ShowDialog();
            }
        }
Ejemplo n.º 9
0
        private async Task InitializeClientAsync()
        {
            await _client.ConnectAsync();

            var req = new TLRequestGetFullUser()
            {
                Id = new TLInputUserSelf()
            };

            try
            {
                CurrentUser = (TLUser)(await _client.SendRequestAsync <TLUserFull>(req)).User;
            }
            catch (InvalidOperationException)
            {
                CurrentUser = null;
            }
        }
Ejemplo n.º 10
0
        public async void CodeRequest(string phone, Action <bool, string> callback)
        {
            try
            {
                this.client = new TelegramClient(75558, "ab4f6bacb2ef3ee86d97cd53f8bb1a70");
                await client.ConnectAsync();

                Thread.Sleep(2000);
                this.phone = phone;
                this.hash  = await client.SendCodeRequestAsync(phone);

                callback(true, null);
            }
            catch (Exception ex)
            {
                callback(false, ex.Message);
            }
        }
Ejemplo n.º 11
0
        public async Task SendMessageToChannelTest()
        {
            var client = new TelegramClient(apiId, apiHash);

            await client.ConnectAsync();

            var dialogs = await client.GetUserDialogsAsync();

            var chat = dialogs.chats.lists
                       .Where(c => c.GetType() == typeof(TLChannel))
                       .Cast <TLChannel>()
                       .FirstOrDefault(c => c.title == "TestGroup");

            await client.SendMessageAsync(new TLInputPeerChannel()
            {
                channel_id = chat.id, access_hash = chat.access_hash.Value
            }, "TEST MSG");
        }
Ejemplo n.º 12
0
        private void EnsureConnected(CancellationToken cancelToken = default(CancellationToken))
        {
            if (m_telegramClient.IsReallyConnected())
            {
                return;
            }

            cancelToken.ThrowIfCancellationRequested();

            m_telegramClient.ConnectAsync(false, cancelToken).GetAwaiter().GetResult();

            cancelToken.ThrowIfCancellationRequested();

            if (m_telegramClient.IsReallyConnected() == false)
            {
                throw new WebException("Unable to connect to telegram");
            }
        }
Ejemplo n.º 13
0
        public async Task SignUpNewUser()
        {
            var client = new TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var hash = await client.SendCodeRequestAsync(NotRegisteredNumberToSignUp);

            var code = "";

            var registeredUser = await client.SignUpAsync(NotRegisteredNumberToSignUp, hash, code, "TLSharp", "User");

            Assert.IsNotNull(registeredUser);
            Assert.IsTrue(client.IsUserAuthorized());

            var loggedInUser = await client.MakeAuthAsync(NotRegisteredNumberToSignUp, hash, code);

            Assert.IsNotNull(loggedInUser);
        }
Ejemplo n.º 14
0
        public async System.Threading.Tasks.Task GetUnReadMassages()
        {
            var store   = new FileSessionStore();
            var apiId   = 434408;
            var apiHash = "0bdea67547ee00f2e164a5522174d7dc";
            var client  = new TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

            foreach (var element in dialogs.Dialogs)
            {
                if (element is TLDialog)
                {
                    TLDialog chat = element as TLDialog;
                    label3.Text = chat.UnreadCount.ToString();
                }
            }
        }
Ejemplo n.º 15
0
        static async void a()
        {
            var store  = new FileSessionStore();
            var client = new TelegramClient(apiId, apiHash, store, "session");// or C:\\Temp\\mySession
            await client.ConnectAsync();

            if (!client.IsUserAuthorized())
            {
                var hash = await client.SendCodeRequestAsync(phoneNumber);      //отсылаем запрос на создании сессии

                var code = Console.ReadLine();                                  // код который придет от Telegram

                var user = await client.MakeAuthAsync(phoneNumber, hash, code); // создаем сессию
            }

            //var userByPhoneId = await client.("791812312323"); // импорт по номеру телефона
            //var userByUserNameId = await await client.ImportByUserName("userName"); // импорт по юзернейму

            var s = await client.IsPhoneRegisteredAsync("xxxxxxxxxxx");//WHO WRITE//WHO WRITE

            var f = await client.GetContactsAsync();

            Console.WriteLine("контакты");
            f.contacts.lists.ForEach(_ => { Console.WriteLine(_.user_id); });

            TeleSharp.TL.Contacts.TLRequestImportContacts requestImportContacts = new TeleSharp.TL.Contacts.TLRequestImportContacts();
            requestImportContacts.contacts = new TLVector <TLInputPhoneContact>();
            requestImportContacts.contacts.lists.Add(new TLInputPhoneContact()
            {
                phone      = "xxxxxxxxxxx",//WHO WRITE//WHO WRITE//WHO WRITE//WHO WRITE//WHO WRITE?
                first_name = "",
                last_name  = ""
            });
            var o = await client.SendRequestAsync <TeleSharp.TL.Contacts.TLImportedContacts>((TLMethod)requestImportContacts);

            var NewUserId = (o.users.lists.First() as TLUser).id;
            var d         = await client.SendMessageAsync(new TLInputPeerUser()
            {
                user_id = NewUserId
            }, "text xxx");

            //return true;
        }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            var    store   = new FileSessionStore();
            var    asaf    = "972528356489";
            var    m       = "972543143131";
            var    hash    = "54a578ab2c70e02c22";
            int    apiId   = 121845;
            string apiHash = "888c93f37abef8dde1b7a1cf40580ebb";
            var    client  = new TelegramClient(apiId, apiHash, store);

            client.ConnectAsync().Wait();
            var estaRegistrado = client.IsPhoneRegisteredAsync("972546252491").Result;

            if (estaRegistrado)
            {
                if (!client.IsUserAuthorized())
                {
                    {
                        hash = client.SendCodeRequestAsync("972546252491").Result;
                        // var code = "63811"; // you can change code in debugger
                        Console.WriteLine("Codigo recibido:");
                        var strCodigo = Console.ReadLine();
                        var user      = client.MakeAuthAsync("972546252491", hash, strCodigo).Result;
                    }
                }
                //send message
                //get available contacts
                var result = client.GetContactsAsync().Result;
                //find recipient in contacts
                var userd = result.Users
                            .Where(x => x.GetType() == typeof(TLUser))
                            .Cast <TLUser>()
                            .FirstOrDefault(x => x.Phone == m);



                client.SendMessageAsync(new TLInputPeerUser()
                {
                    UserId = userd.Id
                }, "test").Wait();
            }
        }
Ejemplo n.º 17
0
        public virtual async Task DownloadFileFromContactTest()
        {
            var client = new TelegramClient(apiId, apiHash);

            await client.ConnectAsync();

            var result = await client.GetContactsAsync();

            var user = result.Users
                       .OfType <TLUser>()
                       .FirstOrDefault(x => x.Phone == NumberToSendMessage);

            var inputPeer = new TLInputPeerUser()
            {
                UserId = user.Id
            };
            var res = await client.SendRequestAsync <TLMessagesSlice>(new TLRequestGetHistory()
            {
                Peer = inputPeer
            });

            var document = res.Messages
                           .OfType <TLMessage>()
                           .Where(m => m.Media != null)
                           .Select(m => m.Media)
                           .OfType <TLMessageMediaDocument>()
                           .Select(md => md.Document)
                           .OfType <TLDocument>()
                           .First();

            var resFile = await client.GetFile(
                new TLInputDocumentFileLocation()
            {
                AccessHash = document.AccessHash,
                Id         = document.Id,
                Version    = document.Version
            },
                document.Size);

            Assert.IsTrue(resFile.Bytes.Length > 0);
        }
Ejemplo n.º 18
0
        public async Task <bool> PhoneCheck(string phone)
        {
            if (InternetConnection.IsConnectionExist == false)
            {
                MainWindowViewModel.instance.Alert(new BitmapImage(new Uri("pack://application:,,,/Resources/Icons/telegram.png")), "Telegram", "Возможно отсутствует подключение к интернету. Статус интернет подключение : " + InternetConnection.IsConnectionExist);
                return(false);
            }
            else
            {
                if (String.IsNullOrEmpty(phone) == true)
                {
                    MainWindowViewModel.instance.Alert(new BitmapImage(new Uri("pack://application:,,,/Resources/Icons/telegram.png")), "Telegram", "Номер телефона не введен. Пожалуйста введите номер.");
                }
                else
                {
                    try
                    {
                        client = await CreateClientAsync();

                        if (client != null)
                        {
                            await client.ConnectAsync();

                            if (client.IsConnected)
                            {
                                hash = await client.SendCodeRequestAsync(phone);

                                CurrectPhone = phone;
                                return(true);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MainWindowViewModel.instance.Alert(new BitmapImage(new Uri("pack://application:,,,/Resources/Icons/telegram.png")), "Telegram", "Ошибка входа. " + ex.Message);
                        return(false);
                    }
                }
                return(false);
            }
        }
Ejemplo n.º 19
0
        public async Task AuthUser()
        {
            if (TelegramClient == null)
            {
                throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram");
            }
            await TelegramClient.ConnectAsync();

            var hash = await TelegramClient.SendCodeRequestAsync(TelegramSettings.NumberToAuthenticate);

            var code = TelegramSettings.CodeToAuthenticate;             // you can change code in debugger too

            if (String.IsNullOrWhiteSpace(code))
            {
                throw new Exception("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram");
            }

            TLUser user = null;

            try
            {
                user = await TelegramClient.MakeAuthAsync(TelegramSettings.NumberToAuthenticate, hash, code);

                if (user != null)
                {
                    IsAuthorized = true;
                }
            }
            catch (CloudPasswordNeededException ex)
            {
                var passwordSetting = await TelegramClient.GetPasswordSetting();

                var password = TelegramSettings.PasswordToAuthenticate;

                user = await TelegramClient.MakeAuthWithPasswordAsync(passwordSetting, password);
            }
            catch (InvalidPhoneCodeException ex)
            {
                throw;
            }
        }
Ejemplo n.º 20
0
        private async Task <int> GetTelegramCode()
        {
            try
            {
                var client = new TelegramClient(57982, "19706860344842eadeb0cc00f28d0902");
                await client.ConnectAsync();

                var hash = await client.SendCodeRequestAsync(this.txtBoxPhone.Text.Trim());
            }
            catch (Exception ex)
            {
                var st    = new StackTrace(ex, true);
                var frame = st.GetFrame(0);
                var line  = frame.GetFileLineNumber();

                // --- Report on error and continue
                emailHelper.SendExceptionEmail(ex.Message + " " + line);
            }

            return(1);
        }
Ejemplo n.º 21
0
        public static async Task <TelegramClient> ConnectAsync(BotDisguisedAsUserBotInfo userbot)
        {
            var apiId = userbot.GetApiId();

            if (apiId == null)
            {
                return(null);
            }

            var t = new TelegramClient(apiId.Value, userbot.GetApiHash(), sessionUserId: userbot.GetSessionUserId());
            await t.ConnectAsync();

            if (t.IsUserAuthorized())
            {
                return(t);
            }

            var r = await t.AuthImportBotAuthorization(userbot.GetToken());

            return(r?.User != null ? t : null);
        }
Ejemplo n.º 22
0
        private async Task <int> SendTelegram(string message)
        {
            try
            {
                var client = new TelegramClient(57982, "19706860344842eadeb0cc00f28d0902");
                await client.ConnectAsync();

                var hash = await client.SendCodeRequestAsync(this.txtBoxPhone.Text.Trim());

                var code = this.txtBoxTelegramCode.Text.Trim(); // you can change code in debugger

                var user = await client.MakeAuthAsync(this.txtBoxPhone.Text.Trim(), hash, code);

                //get available contacts
                var result = await client.GetContactsAsync();

                //find recipient in contacts
                var recipient = result.users.lists
                                .Where(x => x.GetType() == typeof(TLUser))
                                .Cast <TLUser>()
                                .FirstOrDefault(x => x.phone == this.txtBoxPhone.Text.Trim());

                //send message
                await client.SendMessageAsync(new TLInputPeerUser()
                {
                    user_id = recipient.id
                }, message);
            }
            catch (Exception ex)
            {
                var st    = new StackTrace(ex, true);
                var frame = st.GetFrame(0);
                var line  = frame.GetFileLineNumber();

                // --- Report on error and continue
                emailHelper.SendExceptionEmail(ex.Message + " " + line);
            }

            return(1);
        }
Ejemplo n.º 23
0
        public async Task <Result> SendMessageAsync(MessageModel message)
        {
            Result result = new Result();

            try
            {
                using (var client = new TelegramClient(telegramSettings.ApiId, telegramSettings.ApiHash))
                {
                    await client.ConnectAsync();

                    var dialogs = (TLDialogs)await client.GetUserDialogsAsync();

                    var chat = dialogs.Chats.Where(x => x.GetType() == typeof(TLChannel)).Cast <TLChannel>().FirstOrDefault(x => x.Title == telegramSettings.Channel);
                    await client.SendMessageAsync(new TLInputPeerChannel()
                    {
                        ChannelId = chat.Id, AccessHash = chat.AccessHash.Value
                    },
                                                  $"{message.Subject} {Environment.NewLine} {message.Body}");
                }
                result = new Result()
                {
                    Success = true, Data = GetType().Name, ProjectId = message.ProjectId
                };
            }

            catch (Exception ex)
            {
                result = new Result()
                {
                    Success = false, Errors = new List <string>()
                    {
                        ex.Message
                    }, Data = GetType().Name, ProjectId = message.ProjectId
                };
            }

            await Log(result);

            return(result);
        }
        public static async Task <TelegramClient> CreateTelegramClientAsync(string phoneNumber)
        {
            var client = TelegramClients.FirstOrDefault(x => x.Session.TLUser.Phone == phoneNumber);

            if (client != null)
            {
                return(client);
            }

            int    apiId   = 907056;
            string apiHash = "697525d840e31523f43a972dff47e16a";

            client = new TelegramClient(apiId, apiHash, sessionUserId: phoneNumber);
            await client.ConnectAsync();

            if (!client.IsUserAuthorized())
            {
                throw new System.Exception("Session not found");
            }
            TelegramClients.Add(client);
            return(client);
        }
Ejemplo n.º 25
0
        public async Task Enviartelegram(EnviarTelegramDto dto)
        {
            var apiId   = 92426;
            var apiHash = "77135e73f47f49813618b53e8c51ee89";
            var client  = new TelegramClient(apiId, apiHash);
            await client.ConnectAsync();

            var user = await client.MakeAuthAsync("+5565992291443", dto.Hash, dto.Code);

            var result = await client.GetContactsAsync();

            //find recipient in contacts
            var userR = result.users.lists
                        .Where(x => x.GetType() == typeof(TLUser))
                        .Cast <TLUser>()
                        .FirstOrDefault(x => x.phone == "5565981250768");

            //send message
            await client.SendMessageAsync(new TLInputPeerUser()
            {
                user_id = userR.id
            }, dto.Mensagem);
        }
Ejemplo n.º 26
0
        private async void button1_Click(object sender, EventArgs e)
        {
            //int unixTime = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

            //TimeSpan hours = new TimeSpan(-1, 0, 0);
            //var time = DateTime.Now.Add(hours);
            // Message mes = new Message();
            // var telephone = GetChatForNumber("+79951209052");

            //var dictionaty_chat = mes.GetLastIdMessage(telephone, "+79951209052");

            //     mes.GetReplyDictionary(dictionaty_chat);

            //mes.GetLastIdMessage("DataLight stAff");

            var store = new FileSessionStore();

            client = new TelegramClient(632369, "7cb0f9a3d2e5108a4b9a961b86fd564a", store, "session3");

            await client.ConnectAsync();

            hash = await client.SendCodeRequestAsync("+79951209052");
        }
Ejemplo n.º 27
0
        public async Task SendMessageTest()
        {
            var client = new TelegramClient(apiId, apiHash);

            await client.ConnectAsync();

            var result = await client.GetContactsAsync();

            var user = result.users.lists
                       .Where(x => x.GetType() == typeof(TLUser))
                       .Cast <TLUser>()
                       .FirstOrDefault(x => x.phone == NumberToSendMessage);
            await client.SendTypingAsync(new TLInputPeerUser()
            {
                user_id = user.id
            });

            Thread.Sleep(3000);
            await client.SendMessageAsync(new TLInputPeerUser()
            {
                user_id = user.id
            }, "TEST");
        }
Ejemplo n.º 28
0
        public async Task <TLUser> Connect(TelegramClient client)
        {
            await client.ConnectAsync();

            var hash = await client.SendCodeRequestAsync(_numberAccount);

            Console.WriteLine("Ввести код из приложения: ");
            var code = Console.ReadLine();

            if (String.IsNullOrWhiteSpace(code))
            {
                Console.WriteLine("CodeToAuthenticate is empty in the app.config file, fill it with the code you just got now by SMS/Telegram");
            }

            Console.WriteLine("Попытка получения пользователя");
            TLUser user = null;

            try
            {
                user = await client.MakeAuthAsync(_numberAccount, hash, code);
            }
            catch (CloudPasswordNeededException ex)
            {
                var passwordSetting = await client.GetPasswordSetting();

                var password = _passTelegram;

                user = await client.MakeAuthWithPasswordAsync(passwordSetting, password);
            }
            catch (InvalidPhoneCodeException ex)
            {
                Console.WriteLine("CodeToAuthenticate is wrong in the app.config file, fill it with the code you just got now by SMS/Telegram",
                                  ex);
            }

            return(user);
        }
Ejemplo n.º 29
0
        private async void GetPeerChannel(string[] ChannelsName)
        {
            await client.ConnectAsync();

            #region auth by pass
            //var hash = await client.SendCodeRequestAsync("+380954694118");
            //var code = "";
            //TeleSharp.TL.TLUser user;
            //try
            //{
            //    user = await client.MakeAuthAsync("+380954694118", hash, code);
            //}
            //catch (CloudPasswordNeededException ex)
            //{
            //    var password = await client.GetPasswordSetting();
            //    var password_str = "blackwhales";

            //    user = await client.MakeAuthWithPasswordAsync(password, password_str);
            //}
            #endregion
            dialogs = (TeleSharp.TL.Messages.TLDialogsSlice) await client.GetUserDialogsAsync();

            nullDilog : if (dialogs == null)
            {
                goto nullDilog;
            }
            foreach (var item in ChannelsName)
            {
                var channel = dialogs.Chats.OfType <TLChannel>().Cast <TLChannel>().FirstOrDefault(c => c.Title == item);
                channels.Add(new Channel(new TLInputPeerChannel()
                {
                    ChannelId = channel.Id, AccessHash = (long)channel.AccessHash
                }, 0, item));                                                                                                                 //0- it is must be previous value
            }
            first_channels();
            await Task.Run(() => this.getMessages());
        }
Ejemplo n.º 30
0
        //Обработчик логики авторизации
        private async void Btn_Auth_Click(object sender, RoutedEventArgs e)
        {
            if (Txb_Code1.Text.Length > 0)
            {
                if (hash_1 != null)
                {
                    //Подключаемся к существующему файлу сессии если она есть и данные совпадают. Если же файла нет -
                    //он создается, если файл есть но данные не идентичны - перезаписываем сессию.
                    var session = new FileSessionStore();
                    //Подключаем клиент с указанием файла сессии.
                    var cl = new TelegramClient(API_ID, API_HASH, session, "session");

                    //Отправляем запрос на подключение клиента
                    await client.ConnectAsync();

                    //Авторизовываем пользователя
                    var user1 = await client.MakeAuthAsync(Txb_Phone1.Text, hash_1, Txb_Code1.Text);

                    //Запоминаем пользователя и клиент в соответствующие переменные
                    user = user1;

                    client = cl;

                    //Запускаем следующее окно
                    AddPhones nextWin = new AddPhones();
                    nextWin.Show();
                }
                else
                {
                    MessageBox.Show("Что-то не так. Попробуйте снова",
                                    "Ошибка",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error,
                                    MessageBoxResult.OK);
                }
            }
        }